answer
stringlengths
17
10.2M
package com.exedio.cope.console; import java.io.PrintStream; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.exedio.cope.Model; import com.exedio.cops.Cop; import com.exedio.cops.Pageable; import com.exedio.cops.Pager; abstract class ConsoleCop extends Cop { protected static class Args { private static final String AUTO_REFRESH = "ar"; final int autoRefresh; Args(final int autoRefresh) { this.autoRefresh = autoRefresh; } Args(final HttpServletRequest request) { this.autoRefresh = getIntParameter(request, AUTO_REFRESH, 0); } void addParameters(final ConsoleCop cop) { cop.addParameterAccessor(AUTO_REFRESH, autoRefresh, 0); } } private static final String NAME_POSTFIX = ".html"; final String name; final Args args; static final int[] AUTO_REFRESHS = new int[]{0, 2, 5, 15, 60}; protected ConsoleCop(final String tab, final String name, final Args args) { super(tab + NAME_POSTFIX); this.name = name; this.args = args; args.addParameters(this); } long start = 0; private SimpleDateFormat fullDateFormat, todayDateFormat; DecimalFormat nf; void addParameterAccessor(final String key, final int value, final int defaultValue) { addParameter(key, value, defaultValue); } /** * @param request used in subclasses * @param model used in subclasses */ void initialize(final HttpServletRequest request, final Model model) { start = System.currentTimeMillis(); fullDateFormat = new SimpleDateFormat("yyyy/MM/dd'&nbsp;'HH:mm:ss'<small>'.SSS'</small>'"); todayDateFormat = new SimpleDateFormat("HH:mm:ss'<small>'.SSS'</small>'"); final DecimalFormatSymbols nfs = new DecimalFormatSymbols(); nfs.setDecimalSeparator(','); nfs.setGroupingSeparator('\''); nf = new DecimalFormat("", nfs); } protected abstract ConsoleCop newArgs(final Args args); final ConsoleCop toAutoRefresh(final int autoRefresh) { return newArgs(new Args(autoRefresh)); } int getResponseStatus() { return HttpServletResponse.SC_OK; } final ConsoleCop[] getTabs() { return new ConsoleCop[]{ new PropertiesCop(args), new SchemaCop(args), new UnsupportedConstraintCop(args), new TypeColumnCop(args), new CopyConstraintCop(args), new RevisionCop(args), new DatabaseLogCop(args), new ConnectionPoolCop(args), new TransactionCop(args), new ItemCacheCop(args), new QueryCacheCop(args), new PrimaryKeysCop(args), new MediaStatsCop(args), new VmCop(args, false, false), new EnvironmentCop(args), new HiddenCop(args), new ModificationListenerCop(args), new HistoryCop(args), }; } final String getStart() { if(start==0) throw new RuntimeException(); return new SimpleDateFormat("yyyy/MM/dd'&nbsp;'HH:mm:ss.SSS Z (z)").format(new Date(start)); } final long getDuration() { if(start==0) throw new RuntimeException(); return System.currentTimeMillis() - start; } private static final long todayInterval = 6 * 60 * 60 * 1000; // 6 hours final String formatAndHide(final Date date) { return date!=null ? format(date) : ""; } final String format(final Date date) { final long dateMillis = date.getTime(); return ( ( (start-todayInterval) < dateMillis && dateMillis < (start+todayInterval) ) ? todayDateFormat : fullDateFormat).format(date); } final String formatDate(final long date) { return format(new Date(date)); } final String format(final long number) { return nf.format(number); } final String formatAndHide(final long hidden, final long number) { return /*("["+hidden+']') +*/ (number!=hidden ? format(number) : ""); } /** * @param out used in subclasses */ void writeHead(PrintStream out) { // default implementation does nothing } abstract void writeBody(PrintStream out, Model model, HttpServletRequest request, History history, boolean historyModelShown); static final String TAB_PROPERTIES = "properties"; static final String TAB_SCHEMA = "schema"; static final String TAB_UNSUPPORTED_CONSTRAINTS = "unsupportedconstraints"; static final String TAB_TYPE_COLUMNS = "typecolumns"; static final String TAB_COPY_CONSTRAINTS = "copyconstraints"; static final String TAB_REVISION = "revision"; static final String TAB_DATBASE_LOG = "dblogs"; static final String TAB_CONNECTION_POOL = "connections"; static final String TAB_TRANSACTION = "transactions"; static final String TAB_ITEM_CACHE = "itemcache"; static final String TAB_QUERY_CACHE = "querycache"; static final String TAB_HISTORY = "history"; static final String TAB_PRIMARY_KEY = "primarykeys"; static final String TAB_MEDIA_STATS = "mediastats"; static final String TAB_VM = "vm"; static final String TAB_ENVIRONMENT = "environment"; static final String TAB_HIDDEN = "hidden"; static final String TAB_MODIFICATION_LISTENER = "modificationlistener"; static final ConsoleCop getCop(final Model model, final HttpServletRequest request) { final Args args = new Args(request); final String pathInfo = request.getPathInfo(); if("/".equals(pathInfo)) return new PropertiesCop(args); if(pathInfo==null || !pathInfo.startsWith("/") || !pathInfo.endsWith(NAME_POSTFIX)) return new NotFound(args, pathInfo); final String tab = pathInfo.substring(1, pathInfo.length()-NAME_POSTFIX.length()); if(TAB_SCHEMA.equals(tab)) return new SchemaCop(args); if(TAB_UNSUPPORTED_CONSTRAINTS.equals(tab)) return new UnsupportedConstraintCop(args); if(TAB_TYPE_COLUMNS.equals(tab)) return new TypeColumnCop(args); if(TAB_COPY_CONSTRAINTS.equals(tab)) return new CopyConstraintCop(args); if(TAB_PROPERTIES.equals(tab)) return new PropertiesCop(args); if(TAB_REVISION.equals(tab)) return new RevisionCop(args, request); if(TAB_CONNECTION_POOL.equals(tab)) return new ConnectionPoolCop(args); if(TAB_TRANSACTION.equals(tab)) return new TransactionCop(args); if(TAB_DATBASE_LOG.equals(tab)) return new DatabaseLogCop(args); if(TAB_ITEM_CACHE.equals(tab)) return new ItemCacheCop(args); if(TAB_QUERY_CACHE.equals(tab)) return QueryCacheCop.getQueryCacheCop(args, request); if(TAB_HISTORY.equals(tab)) return new HistoryCop(args); if(TAB_PRIMARY_KEY.equals(tab)) return new PrimaryKeysCop(args); if(TAB_MEDIA_STATS.equals(tab)) return new MediaStatsCop(args); if(TAB_VM.equals(tab)) return VmCop.getVmCop(args, request); if(TAB_ENVIRONMENT.equals(tab)) return new EnvironmentCop(args); if(TAB_HIDDEN.equals(tab)) return new HiddenCop(args); if(TAB_MODIFICATION_LISTENER.equals(tab)) return new ModificationListenerCop(args); final MediaCop mediaCop = MediaCop.getMediaCop(model, args, request); if(mediaCop!=null) return mediaCop; return new NotFound(args, pathInfo); } private final static class NotFound extends ConsoleCop { private final String pathInfo; protected NotFound(final Args args, final String pathInfo) { super("Not Found", "Not Found", args); this.pathInfo = pathInfo; } @Override protected ConsoleCop newArgs(final Args args) { return new NotFound(args, pathInfo); } @Override int getResponseStatus() { return HttpServletResponse.SC_NOT_FOUND; } @Override final void writeBody( final PrintStream out, final Model model, final HttpServletRequest request, final History history, final boolean historyModelShown) { Console_Jspm.writeNotFound(out, pathInfo); } } static void writePager(final PrintStream out, final Pageable cop) { final Pager pager = cop.getPager(); if(pager.isNeeded()) { out.print("<span class=\"pager\">"); Console_Jspm.writePagerButton(out, cop, pager.first(), "&lt;&lt;", "disabled"); Console_Jspm.writePagerButton(out, cop, pager.previous(), "&lt;", "disabled"); Console_Jspm.writePagerButton(out, cop, pager.next(), "&gt;", "disabled"); Console_Jspm.writePagerButton(out, cop, pager.last(), "&gt;&gt;", "disabled"); for(final Pager newLimit : pager.newLimits()) Console_Jspm.writePagerButton(out, cop, newLimit, String.valueOf(newLimit.getLimit()), "selected"); out.print(' '); out.print(pager.getFrom()); out.print('-'); out.print(pager.getTo()); out.print('/'); out.print(pager.getTotal()); out.print("</span>"); } } private static final DecimalFormat RATIO_FORMAT = new DecimalFormat("###0.00"); static String ratio(final long dividend, final long divisor) { if(dividend<0 || divisor<0) return "<0"; if(divisor==0) return ""; return RATIO_FORMAT.format(Math.log10(((double)dividend) / ((double)divisor))); } }
package com.android.phone.settings; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.net.sip.SipManager; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceCategory; import android.preference.PreferenceFragment; import android.preference.SwitchPreference; import android.telecom.PhoneAccountHandle; import android.telecom.TelecomManager; import android.telephony.SubscriptionInfo; import android.telephony.SubscriptionManager; import android.telephony.TelephonyManager; import android.util.Log; import com.android.phone.R; import com.android.phone.SubscriptionInfoHelper; import com.android.services.telephony.sip.SipAccountRegistry; import com.android.services.telephony.sip.SipSharedPreferences; import com.android.services.telephony.sip.SipUtil; import java.util.List; public class PhoneAccountSettingsFragment extends PreferenceFragment implements Preference.OnPreferenceChangeListener, Preference.OnPreferenceClickListener, AccountSelectionPreference.AccountSelectionListener { private static final String ACCOUNTS_LIST_CATEGORY_KEY = "phone_accounts_accounts_list_category_key"; private static final String DEFAULT_OUTGOING_ACCOUNT_KEY = "default_outgoing_account"; private static final String CONFIGURE_CALL_ASSISTANT_PREF_KEY = "wifi_calling_configure_call_assistant_preference"; private static final String CALL_ASSISTANT_CATEGORY_PREF_KEY = "phone_accounts_call_assistant_settings_category_key"; private static final String SELECT_CALL_ASSISTANT_PREF_KEY = "wifi_calling_call_assistant_preference"; private static final String SELECT_CALL_ASSISTANT_SWITCH_KEY = "wifi_calling_call_assistant_switch"; private static final String SIP_SETTINGS_CATEGORY_PREF_KEY = "phone_accounts_sip_settings_category_key"; private static final String USE_SIP_PREF_KEY = "use_sip_calling_options_key"; private static final String SIP_RECEIVE_CALLS_PREF_KEY = "sip_receive_calls_key"; private String LOG_TAG = PhoneAccountSettingsFragment.class.getSimpleName(); private TelecomManager mTelecomManager; private SubscriptionManager mSubscriptionManager; private PreferenceCategory mAccountList; private AccountSelectionPreference mDefaultOutgoingAccount; private AccountSelectionPreference mSelectCallAssistant; private SwitchPreference mCallAssistantSwitch; private Preference mConfigureCallAssistant; private ListPreference mUseSipCalling; private CheckBoxPreference mSipReceiveCallsPreference; private SipSharedPreferences mSipSharedPreferences; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); mTelecomManager = TelecomManager.from(getActivity()); mSubscriptionManager = SubscriptionManager.from(getActivity()); } @Override public void onResume() { super.onResume(); if (getPreferenceScreen() != null) { getPreferenceScreen().removeAll(); } addPreferencesFromResource(R.xml.phone_account_settings); TelephonyManager telephonyManager = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE); mAccountList = (PreferenceCategory) getPreferenceScreen().findPreference( ACCOUNTS_LIST_CATEGORY_KEY); if (telephonyManager.getPhoneCount() > 1) { initAccountList(); } else { getPreferenceScreen().removePreference(mAccountList); } mDefaultOutgoingAccount = (AccountSelectionPreference) getPreferenceScreen().findPreference(DEFAULT_OUTGOING_ACCOUNT_KEY); if (mTelecomManager.getCallCapablePhoneAccounts().size() > 1) { mDefaultOutgoingAccount.setListener(this); updateDefaultOutgoingAccountsModel(); } else { getPreferenceScreen().removePreference(mDefaultOutgoingAccount); } List<PhoneAccountHandle> simCallManagers = mTelecomManager.getSimCallManagers(); PreferenceCategory callAssistantCategory = (PreferenceCategory) getPreferenceScreen().findPreference(CALL_ASSISTANT_CATEGORY_PREF_KEY); if (simCallManagers.isEmpty()) { getPreferenceScreen().removePreference(callAssistantCategory); } else { if (simCallManagers.size() == 1) { // If there's only a single call assistant then display an ON/OFF switch. Turning // the switch on enables the call assistant and turning it off disables it. callAssistantCategory.removePreference( getPreferenceScreen().findPreference(SELECT_CALL_ASSISTANT_PREF_KEY)); CharSequence title = mTelecomManager.getPhoneAccount(simCallManagers.get(0)).getLabel(); callAssistantCategory.setTitle(title); mCallAssistantSwitch = (SwitchPreference) getPreferenceScreen().findPreference(SELECT_CALL_ASSISTANT_SWITCH_KEY); mCallAssistantSwitch.setTitle(title); mCallAssistantSwitch.setChecked(simCallManagers.get(0).equals( mTelecomManager.getSimCallManager())); mCallAssistantSwitch.setOnPreferenceChangeListener(this); mCallAssistantSwitch.setEnabled(true); } else { // If there's more than one call assistant then display a list. Choosing an item // from the list enables the corresponding call assistant. callAssistantCategory.removePreference( getPreferenceScreen().findPreference(SELECT_CALL_ASSISTANT_SWITCH_KEY)); mSelectCallAssistant = (AccountSelectionPreference) getPreferenceScreen().findPreference(SELECT_CALL_ASSISTANT_PREF_KEY); mSelectCallAssistant.setListener(this); mSelectCallAssistant.setDialogTitle( R.string.wifi_calling_select_call_assistant_summary); updateCallAssistantModel(); } mConfigureCallAssistant = getPreferenceScreen().findPreference(CONFIGURE_CALL_ASSISTANT_PREF_KEY); mConfigureCallAssistant.setOnPreferenceClickListener(this); updateConfigureCallAssistant(); } if (SipUtil.isVoipSupported(getActivity())) { mSipSharedPreferences = new SipSharedPreferences(getActivity()); mUseSipCalling = (ListPreference) getPreferenceScreen().findPreference(USE_SIP_PREF_KEY); mUseSipCalling.setEntries(!SipManager.isSipWifiOnly(getActivity()) ? R.array.sip_call_options_wifi_only_entries : R.array.sip_call_options_entries); mUseSipCalling.setOnPreferenceChangeListener(this); int optionsValueIndex = mUseSipCalling.findIndexOfValue(mSipSharedPreferences.getSipCallOption()); if (optionsValueIndex == -1) { // If the option is invalid (eg. deprecated value), default to SIP_ADDRESS_ONLY. mSipSharedPreferences.setSipCallOption( getResources().getString(R.string.sip_address_only)); optionsValueIndex = mUseSipCalling.findIndexOfValue(mSipSharedPreferences.getSipCallOption()); } mUseSipCalling.setValueIndex(optionsValueIndex); mUseSipCalling.setSummary(mUseSipCalling.getEntry()); mSipReceiveCallsPreference = (CheckBoxPreference) getPreferenceScreen().findPreference(SIP_RECEIVE_CALLS_PREF_KEY); mSipReceiveCallsPreference.setEnabled(SipUtil.isPhoneIdle(getActivity())); mSipReceiveCallsPreference.setChecked( mSipSharedPreferences.isReceivingCallsEnabled()); mSipReceiveCallsPreference.setOnPreferenceChangeListener(this); } else { getPreferenceScreen().removePreference( getPreferenceScreen().findPreference(SIP_SETTINGS_CATEGORY_PREF_KEY)); } } /** * Handles changes to the preferences. * * @param pref The preference changed. * @param objValue The changed value. * @return True if the preference change has been handled, and false otherwise. */ @Override public boolean onPreferenceChange(Preference pref, Object objValue) { if (pref == mUseSipCalling) { String option = objValue.toString(); mSipSharedPreferences.setSipCallOption(option); mUseSipCalling.setValueIndex(mUseSipCalling.findIndexOfValue(option)); mUseSipCalling.setSummary(mUseSipCalling.getEntry()); return true; } else if (pref == mSipReceiveCallsPreference) { final boolean isEnabled = !mSipReceiveCallsPreference.isChecked(); new Thread(new Runnable() { public void run() { handleSipReceiveCallsOption(isEnabled); } }).start(); return true; } else if (pref == mCallAssistantSwitch) { List<PhoneAccountHandle> simCallManagers = mTelecomManager.getSimCallManagers(); if (simCallManagers.size() == 1) { if (Boolean.TRUE.equals(objValue)) { mTelecomManager.setSimCallManager(simCallManagers.get(0)); } else { mTelecomManager.setSimCallManager(null); } updateConfigureCallAssistant(); } else { Log.w(LOG_TAG, "Single call assistant expected but " + simCallManagers.size() + " found. Ignoring preference change."); } return true; } return false; } @Override public boolean onPreferenceClick(Preference pref) { if (pref == mConfigureCallAssistant) { Intent intent = getConfigureCallAssistantIntent(); if (intent != null) { try { startActivity(intent); } catch (ActivityNotFoundException e) { Log.d(LOG_TAG, "Could not resolve call assistant configure intent: " + intent); } } return true; } return false; } /** * Handles a phone account selection, namely when a call assistant has been selected. * * @param pref The account selection preference which triggered the account selected event. * @param account The account selected. * @return True if the account selection has been handled, and false otherwise. */ @Override public boolean onAccountSelected(AccountSelectionPreference pref, PhoneAccountHandle account) { if (pref == mDefaultOutgoingAccount) { mTelecomManager.setUserSelectedOutgoingPhoneAccount(account); return true; } else if (pref == mSelectCallAssistant) { mTelecomManager.setSimCallManager(account); return true; } return false; } /** * Repopulate the dialog to pick up changes before showing. * * @param pref The account selection preference dialog being shown. */ @Override public void onAccountSelectionDialogShow(AccountSelectionPreference pref) { if (pref == mDefaultOutgoingAccount) { updateDefaultOutgoingAccountsModel(); } else if (pref == mSelectCallAssistant) { updateCallAssistantModel(); updateConfigureCallAssistant(); } } /** * Update the configure preference summary when the call assistant changes. */ @Override public void onAccountChanged(AccountSelectionPreference pref) { if (pref == mSelectCallAssistant) { updateConfigureCallAssistant(); } } private synchronized void handleSipReceiveCallsOption(boolean isEnabled) { Context context = getActivity(); if (context == null) { // Return if the fragment is detached from parent activity before executed by thread. return; } mSipSharedPreferences.setReceivingCallsEnabled(isEnabled); SipUtil.useSipToReceiveIncomingCalls(context, isEnabled); // Restart all Sip services to ensure we reflect whether we are receiving calls. SipAccountRegistry sipAccountRegistry = SipAccountRegistry.getInstance(); sipAccountRegistry.restartSipService(context); } /** * Queries the telcomm manager to update the default outgoing account selection preference * with the list of outgoing accounts and the current default outgoing account. */ private void updateDefaultOutgoingAccountsModel() { mDefaultOutgoingAccount.setModel( mTelecomManager, mTelecomManager.getCallCapablePhoneAccounts(), mTelecomManager.getUserSelectedOutgoingPhoneAccount(), getString(R.string.phone_accounts_ask_every_time)); } /** * Queries the telecomm manager to update the account selection preference with the list of * call assistants, and the currently selected call assistant. */ public void updateCallAssistantModel() { List<PhoneAccountHandle> simCallManagers = mTelecomManager.getSimCallManagers(); mSelectCallAssistant.setModel( mTelecomManager, simCallManagers, mTelecomManager.getSimCallManager(), getString(R.string.wifi_calling_call_assistant_none)); } /** * Shows or hides the "configure call assistant" preference. */ private void updateConfigureCallAssistant() { Intent intent = getConfigureCallAssistantIntent(); boolean shouldShow = intent != null && !mApplicationContext.getPackageManager() .queryIntentActivities(intent, 0).isEmpty(); PreferenceCategory callAssistantCategory = (PreferenceCategory) getPreferenceScreen().findPreference(CALL_ASSISTANT_CATEGORY_PREF_KEY); if (shouldShow) { callAssistantCategory.addPreference(mConfigureCallAssistant); } else { callAssistantCategory.removePreference(mConfigureCallAssistant); } } private void initAccountList() { List<SubscriptionInfo> sil = mSubscriptionManager.getActiveSubscriptionInfoList(); if (sil == null) { return; } for (SubscriptionInfo subscription : sil) { CharSequence label = subscription.getDisplayName(); Intent intent = new Intent(TelecomManager.ACTION_SHOW_CALL_SETTINGS); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); SubscriptionInfoHelper.addExtrasToIntent(intent, subscription); Preference accountPreference = new Preference(getActivity()); accountPreference.setTitle(label); accountPreference.setIntent(intent); mAccountList.addPreference(accountPreference); } } private Intent getConfigureCallAssistantIntent() { PhoneAccountHandle handle = mTelecomManager.getSimCallManager(); if (handle != null) { String packageName = handle.getComponentName().getPackageName(); if (packageName != null) { return new Intent(TelecomManager.ACTION_CONNECTION_SERVICE_CONFIGURE) .addCategory(Intent.CATEGORY_DEFAULT) .setPackage(packageName); } } return null; } }
package com.freetymekiyan.algorithms.level.medium; /** * Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. * <p> * For example, given the following matrix: * <p> * 1 0 1 0 0 * 1 0 1 1 1 * 1 1 1 1 1 * 1 0 0 1 0 * Return 4. * <p> * Company Tags: Apple, Airbnb, Facebook * Tags: Dynamic Programming * Similar Problems: (H) Maximal Rectangle */ public class MaximalSquare { /** * DP. * Finding the largest square's area is the same as finding the edge length. * The recurrence relation here is: * Suppose the largest edge length formed by current grid at matrix[i-1][j-1] is dp[i][j]. * If matrix[i - 1][j - 1] = 1, dp[i][j] = min(dp[i-1][j], dp[i][j], dp[i][j-1]) + 1. * If matrix[i - 1][j - 1] = 0, dp[i][j] = 0. * <p> * To understand the recurrence relation, draw a matrix. * Iff grid [i,j] is 1 and it's just a corners of other 1s, can the length expand. */ public int maximalSquare(char[][] matrix) { if (matrix == null) { return 0; } int r = matrix.length; int c = r == 0 ? 0 : matrix[0].length; int[][] dp = new int[r + 1][c + 1]; // First row and column are all 0. int maxLen = 0; for (int i = 1; i <= r; i++) { // Traverse dp array. Note the equal sign. for (int j = 1; j <= c; j++) { if (matrix[i - 1][j - 1] == '1') { // Update dp[i][j] and the max length. dp[i][j] = Math.min(Math.min(dp[i - 1][j], dp[i][j - 1]), dp[i - 1][j - 1]) + 1; maxLen = Math.max(maxLen, dp[i][j]); } } } return maxLen * maxLen; // Return AREA here. } /** * DP. Space optimized. * Only the previous row and previous column is needed. * So reduce space usage to an array and an integer. */ public int maximalSquareB(char[][] matrix) { if (matrix == null) { return 0; } int r = matrix.length; int c = r == 0 ? 0 : matrix[0].length; int[] dp = new int[c + 1]; // Only need one row. int prev = 0; // Store dp[i-1][j-1]. int maxLen = 0; for (int i = 1; i <= r; i++) { for (int j = 1; j <= c; j++) { int temp = dp[j]; // Store dp[i-1][j-1] of next iteration. if (matrix[i - 1][j - 1] == '1') { dp[j] = Math.min(Math.min(dp[j - 1], dp[j]), prev) + 1; maxLen = Math.max(maxLen, dp[j]); } else { dp[j] = 0; // Have to update when grid is 0. } prev = temp; // dp[j] before update is the dp[i-1][j-1] for the next loop. } } return maxLen * maxLen; // Return the AREA here. } }
package com.gmail.St3venAU.plugins.ArmorStandTools; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.SkullType; import org.bukkit.block.Block; import org.bukkit.block.CommandBlock; import org.bukkit.block.Skull; import org.bukkit.entity.ArmorStand; import org.bukkit.entity.EntityType; import org.bukkit.entity.ItemFrame; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.block.SignChangeEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.inventory.InventoryAction; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryDragEvent; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerInteractAtEntityEvent; import org.bukkit.event.player.PlayerInteractEntityEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.metadata.MetadataValue; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.util.EulerAngle; import java.util.Arrays; import java.util.List; import java.util.UUID; import java.util.regex.Pattern; public class MainListener implements Listener { private final Pattern MC_USERNAME_PATTERN = Pattern.compile("^[a-zA-Z0-9_]{3,16}$"); private final EulerAngle zero = new EulerAngle(0D, 0D, 0D); private final Main plugin; MainListener(Main main) { this.plugin = main; } @SuppressWarnings("ConstantConditions") @EventHandler public void onPlayerInteractAtEntity(PlayerInteractAtEntityEvent event) { if (event.getRightClicked() instanceof ArmorStand) { Player p = event.getPlayer(); if(plugin.carryingArmorStand.containsKey(p.getUniqueId())) { if (playerHasPermission(p, plugin.carryingArmorStand.get(p.getUniqueId()).getLocation().getBlock(), null)) { plugin.carryingArmorStand.remove(p.getUniqueId()); Utils.actionBarMsg(p, Config.asDropped); event.setCancelled(true); return; } else { p.sendMessage(ChatColor.RED + Config.wgNoPerm); } } ArmorStandTool tool = ArmorStandTool.get(p.getItemInHand()); if(tool == null) return; ArmorStand as = (ArmorStand) event.getRightClicked(); if (!playerHasPermission(p, event.getRightClicked().getLocation().getBlock(), tool)) { p.sendMessage(ChatColor.RED + Config.wgNoPerm); return; } double num = event.getClickedPosition().getY() - 0.05; if (num < 0) { num = 0; } else if (num > 2) { num = 2; } num = 2.0 - num; double angle = num * Math.PI; boolean cancel = true; switch(tool) { case HEADX: as.setHeadPose(as.getHeadPose().setX(angle)); break; case HEADY: as.setHeadPose(as.getHeadPose().setY(angle)); break; case HEADZ: as.setHeadPose(as.getHeadPose().setZ(angle)); break; case LARMX: as.setLeftArmPose(as.getLeftArmPose().setX(angle)); break; case LARMY: as.setLeftArmPose(as.getLeftArmPose().setY(angle)); break; case LARMZ: as.setLeftArmPose(as.getLeftArmPose().setZ(angle)); break; case RARMX: as.setRightArmPose(as.getRightArmPose().setX(angle)); break; case RARMY: as.setRightArmPose(as.getRightArmPose().setY(angle)); break; case RARMZ: as.setRightArmPose(as.getRightArmPose().setZ(angle)); break; case LLEGX: as.setLeftLegPose(as.getLeftLegPose().setX(angle)); break; case LLEGY: as.setLeftLegPose(as.getLeftLegPose().setY(angle)); break; case LLEGZ: as.setLeftLegPose(as.getLeftLegPose().setZ(angle)); break; case RLEGX: as.setRightLegPose(as.getRightLegPose().setX(angle)); break; case RLEGY: as.setRightLegPose(as.getRightLegPose().setY(angle)); break; case RLEGZ: as.setRightLegPose(as.getRightLegPose().setZ(angle)); break; case BODYX: as.setBodyPose(as.getBodyPose().setX(angle)); break; case BODYY: as.setBodyPose(as.getBodyPose().setY(angle)); break; case BODYZ: as.setBodyPose(as.getBodyPose().setZ(angle)); break; case MOVEX: as.teleport(as.getLocation().add(0.05 * (p.isSneaking() ? -1 : 1), 0.0, 0.0)); break; case MOVEY: as.teleport(as.getLocation().add(0.0, 0.05 * (p.isSneaking() ? -1 : 1), 0.0)); break; case MOVEZ: as.teleport(as.getLocation().add(0.0, 0.0, 0.05 * (p.isSneaking() ? -1 : 1))); break; case ROTAT: Location l = as.getLocation(); l.setYaw(((float) num) * 180F); as.teleport(l); break; case INVIS: as.setVisible(!as.isVisible()); p.sendMessage(ChatColor.GREEN + Config.asVisible + ": " + (as.isVisible() ? Config.isTrue : Config.isFalse)); break; case CLONE: pickUpArmorStand(clone(as), p, true); p.sendMessage(ChatColor.GREEN + Config.asCloned); Utils.actionBarMsg(p, ChatColor.GREEN + Config.carrying); break; case SAVE: generateCmdBlock(p.getLocation(), as); p.sendMessage(ChatColor.GREEN + Config.cbCreated); break; case SIZE: as.setSmall(!as.isSmall()); p.sendMessage(ChatColor.GREEN + Config.size + ": " + (as.isSmall() ? Config.small : Config.normal)); break; case BASE: as.setBasePlate(!as.hasBasePlate()); p.sendMessage(ChatColor.GREEN + Config.basePlate + ": " + (as.hasBasePlate() ? Config.isOn : Config.isOff)); break; case GRAV: as.setGravity(!as.hasGravity()); p.sendMessage(ChatColor.GREEN + Config.gravity + ": " + (as.hasGravity() ? Config.isOn : Config.isOff)); break; case ARMS: as.setArms(!as.hasArms()); p.sendMessage(ChatColor.GREEN + Config.arms + ": " + (as.hasArms() ? Config.isOn : Config.isOff)); break; case NAME: setName(p, as); break; case PHEAD: setPlayerSkull(p, as); break; case INVUL: p.sendMessage(ChatColor.GREEN + Config.invul + ": " + (NBT.toggleInvulnerability(as) ? Config.isOn : Config.isOff)); break; case SLOTS: p.sendMessage(ChatColor.GREEN + Config.equip + ": " + (NBT.toggleSlotsDisabled(as) ? Config.locked : Config.unLocked)); break; case MOVE: UUID uuid = p.getUniqueId(); if(plugin.carryingArmorStand.containsKey(uuid)) { plugin.carryingArmorStand.remove(uuid); Utils.actionBarMsg(p, Config.asDropped); } else { pickUpArmorStand(as, p, false); Utils.actionBarMsg(p, ChatColor.GREEN + Config.carrying); } break; case NODEL: // Developer tool - do not use if(as.getMaxHealth() == 50) { as.setMaxHealth(20); p.sendMessage(ChatColor.GREEN + "Deletion Protection: Disabled"); } else { as.setMaxHealth(50); p.sendMessage(ChatColor.GREEN + "Deletion Protection: Enabled"); } break; default: cancel = tool == ArmorStandTool.SUMMON || tool == ArmorStandTool.SAVE || event.isCancelled(); } event.setCancelled(cancel); } } @SuppressWarnings("deprecation") @EventHandler public void onPlayerInteractEntity(PlayerInteractEntityEvent event) { if (event.getRightClicked() instanceof ItemFrame && ArmorStandTool.isTool(event.getPlayer().getItemInHand())) { event.setCancelled(true); event.getPlayer().updateInventory(); } else if(!(event.getRightClicked() instanceof ArmorStand) && ArmorStandTool.NAME.is(event.getPlayer().getItemInHand())) { event.setCancelled(true); } } private ArmorStand clone(ArmorStand as) { ArmorStand clone = (ArmorStand) as.getWorld().spawnEntity(as.getLocation().add(1, 0, 0), EntityType.ARMOR_STAND); clone.setGravity(as.hasGravity()); clone.setHelmet(as.getHelmet()); clone.setChestplate(as.getChestplate()); clone.setLeggings(as.getLeggings()); clone.setBoots(as.getBoots()); clone.setItemInHand(as.getItemInHand()); clone.setHeadPose(as.getHeadPose()); clone.setBodyPose(as.getBodyPose()); clone.setLeftArmPose(as.getLeftArmPose()); clone.setRightArmPose(as.getRightArmPose()); clone.setLeftLegPose(as.getLeftLegPose()); clone.setRightLegPose(as.getRightLegPose()); clone.setVisible(as.isVisible()); clone.setBasePlate(as.hasBasePlate()); clone.setArms(as.hasArms()); clone.setCustomName(as.getCustomName()); clone.setCustomNameVisible(as.isCustomNameVisible()); clone.setSmall(as.isSmall()); clone.setMaxHealth(as.getMaxHealth()); NBT.setSlotsDisabled(clone, NBT.getDisabledSlots(as) == 2039583); NBT.setInvulnerable(clone, NBT.isInvulnerable(as)); return clone; } @EventHandler public void onBlockPlace(BlockPlaceEvent event) { if(ArmorStandTool.isTool(event.getItemInHand())) { event.setCancelled(true); } } @SuppressWarnings("deprecation") @EventHandler public void onPlayerMove(PlayerMoveEvent event) { Player p = event.getPlayer(); if(plugin.carryingArmorStand.containsKey(p.getUniqueId())) { ArmorStand as = plugin.carryingArmorStand.get(p.getUniqueId()); if (as == null || as.isDead()) { plugin.carryingArmorStand.remove(p.getUniqueId()); Utils.actionBarMsg(p, Config.asDropped); return; } Location loc = Utils.getLocationFacingPlayer(p); Block block = loc.getBlock(); if (playerHasPermission(p, block, null)) { as.teleport(loc); Utils.actionBarMsg(p, ChatColor.GREEN + Config.carrying); } } } @EventHandler public void onPlayerDeath(PlayerDeathEvent event) { final Player p = event.getEntity(); if(p.getWorld().getGameRuleValue("keepInventory").equalsIgnoreCase("true")) return; List<ItemStack> drops = event.getDrops(); for(ArmorStandTool t : ArmorStandTool.values()) { drops.remove(t.getItem()); } if(plugin.savedInventories.containsKey(p.getUniqueId())) { drops.addAll(Arrays.asList(plugin.savedInventories.get(p.getUniqueId()))); plugin.savedInventories.remove(p.getUniqueId()); } } @SuppressWarnings("deprecation") @EventHandler public void onInventoryClick(InventoryClickEvent event) { if (event.isCancelled() || !(event.getWhoClicked() instanceof Player)) return; final Player p = (Player) event.getWhoClicked(); ItemStack item = event.getCurrentItem(); if(event.getInventory().getHolder() != p && ArmorStandTool.isTool(item)) { event.setCancelled(true); p.updateInventory(); return; } if(event.getAction() == InventoryAction.HOTBAR_SWAP || event.getAction() == InventoryAction.HOTBAR_MOVE_AND_READD) { if(Utils.hasItems(p)) { event.setCancelled(true); p.updateInventory(); } } } @SuppressWarnings("deprecation") @EventHandler public void onInventoryDrag(InventoryDragEvent event) { if (event.isCancelled() || !(event.getWhoClicked() instanceof Player)) return; final Player p = (Player) event.getWhoClicked(); if (event.getInventory().getHolder() != p && Utils.containsItems(event.getNewItems().values())) { event.setCancelled(true); p.updateInventory(); } } @EventHandler public void onPlayerDropItem(final PlayerDropItemEvent event) { if(ArmorStandTool.isTool(event.getItemDrop().getItemStack())) { event.getItemDrop().remove(); } } @EventHandler public void onPlayerQuit(PlayerQuitEvent event) { UUID uuid = event.getPlayer().getUniqueId(); if(plugin.carryingArmorStand.containsKey(uuid)) { plugin.returnArmorStand(plugin.carryingArmorStand.get(uuid)); plugin.carryingArmorStand.remove(uuid); } if(plugin.savedInventories.containsKey(uuid)) { event.getPlayer().getInventory().setContents(plugin.savedInventories.get(uuid)); plugin.savedInventories.remove(uuid); } } @SuppressWarnings("deprecation") @EventHandler public void onPlayerInteract(PlayerInteractEvent event) { Player p = event.getPlayer(); if(plugin.carryingArmorStand.containsKey(p.getUniqueId())) { boolean perm = playerHasPermission(p, plugin.carryingArmorStand.get(p.getUniqueId()).getLocation().getBlock(), null); if (perm) { plugin.carryingArmorStand.remove(p.getUniqueId()); Utils.actionBarMsg(p, Config.asDropped); event.setCancelled(true); } else { p.sendMessage(ChatColor.RED + Config.wgNoPerm); } return; } Action action = event.getAction(); ArmorStandTool tool = ArmorStandTool.get(event.getItem()); if(tool == null) return; if(action == Action.LEFT_CLICK_AIR || action == Action.LEFT_CLICK_BLOCK) { event.setCancelled(true); Utils.cycleInventory(p); return; } else if(action == Action.RIGHT_CLICK_BLOCK) { if (!playerHasPermission(p, event.getClickedBlock(), tool)) { p.sendMessage(ChatColor.RED + Config.wgNoPerm); return; } switch (tool) { case SUMMON: event.setCancelled(true); Location l = Utils.getLocationFacingPlayer(p); pickUpArmorStand(spawnArmorStand(l), p, true); Utils.actionBarMsg(p, ChatColor.GREEN + Config.carrying); p.updateInventory(); break; case NAME: event.setCancelled(true); break; } } } @EventHandler public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { if(event.getEntity() instanceof ArmorStand && event.getDamager() instanceof Player && ArmorStandTool.isTool(((Player) event.getDamager()).getItemInHand())) { event.setCancelled(true); Utils.cycleInventory((Player) event.getDamager()); } } private ArmorStand spawnArmorStand(Location l) { ArmorStand as = (ArmorStand) l.getWorld().spawnEntity(l, EntityType.ARMOR_STAND); as.setHelmet(Config.helmet); as.setChestplate(Config.chest); as.setLeggings(Config.pants); as.setBoots(Config.boots); as.setItemInHand(Config.itemInHand); as.setVisible(Config.isVisible); as.setSmall(Config.isSmall); as.setArms(Config.hasArms); as.setBasePlate(Config.hasBasePlate); as.setGravity(Config.hasGravity); if(Config.defaultName.length() > 0) { as.setCustomName(Config.defaultName); as.setCustomNameVisible(true); } NBT.setSlotsDisabled(as, Config.equipmentLock); NBT.setInvulnerable(as, Config.invulnerable); return as; } @SuppressWarnings({"deprecation", "ConstantConditions"}) private void generateCmdBlock(Location l, ArmorStand as) { Location loc = as.getLocation(); int dSlots = NBT.getDisabledSlots(as); int hand = as.getItemInHand() == null ? 0 : as.getItemInHand().getTypeId(); int handDmg = as.getItemInHand() == null ? 0 : as.getItemInHand().getDurability(); int boots = as.getBoots() == null ? 0 : as.getBoots().getTypeId(); int bootsDmg = as.getBoots() == null ? 0 : as.getBoots().getDurability(); int legs = as.getLeggings() == null ? 0 : as.getLeggings().getTypeId(); int legsDmg = as.getLeggings() == null ? 0 : as.getLeggings().getDurability(); int chest = as.getChestplate() == null ? 0 : as.getChestplate().getTypeId(); int chestDmg = as.getChestplate() == null ? 0 : as.getChestplate().getDurability(); int helm = as.getHelmet() == null ? 0 : as.getHelmet().getTypeId(); int helmDmg = as.getHelmet() == null ? 0 : as.getHelmet().getDurability(); EulerAngle he = as.getHeadPose(); EulerAngle ll = as.getLeftLegPose(); EulerAngle rl = as.getRightLegPose(); EulerAngle la = as.getLeftArmPose(); EulerAngle ra = as.getRightArmPose(); EulerAngle bo = as.getBodyPose(); String cmd = "summon ArmorStand " + Utils.twoDec(loc.getX()) + " " + Utils.twoDec(loc.getY()) + " " + Utils.twoDec(loc.getZ()) + " {" + (as.getMaxHealth() != 20 ? "Attributes:[{Name:\"generic.maxHealth\", Base:" + as.getMaxHealth() + "}]," : "") + (as.isVisible() ? "" : "Invisible:1,") + (as.hasBasePlate() ? "" : "NoBasePlate:1,") + (as.hasGravity() ? "" : "NoGravity:1,") + (as.hasArms() ? "ShowArms:1," : "") + (as.isSmall() ? "Small:1," : "") + (NBT.isInvulnerable(as) ? "Invulnerable:1," : "") + (dSlots == 0 ? "" : ("DisabledSlots:" + dSlots + ",")) + (as.isCustomNameVisible() ? "CustomNameVisible:1," : "") + (as.getCustomName() == null ? "" : ("CustomName:\"" + as.getCustomName() + "\",")) + (loc.getYaw() == 0F ? "" : ("Rotation:[" + Utils.twoDec(loc.getYaw()) + "f],")) + (hand == 0 && boots == 0 && legs == 0 && chest == 0 && helm == 0 ? "" : ( "Equipment:[" + "{id:" + hand + ",Damage:" + handDmg + NBT.getItemStackTags(as.getItemInHand()) + "}," + "{id:" + boots + ",Damage:" + bootsDmg + NBT.getItemStackTags(as.getBoots()) + "}," + "{id:" + legs + ",Damage:" + legsDmg + NBT.getItemStackTags(as.getLeggings()) + "}," + "{id:" + chest + ",Damage:" + chestDmg + NBT.getItemStackTags(as.getChestplate()) + "}," + "{id:" + helm + ",Damage:" + helmDmg + NBT.getItemStackTags(as.getHelmet()) + NBT.skullOwner(as.getHelmet()) + "}],")) + "Pose:{" + (bo.equals(zero) ? "" : ("Body:[" + Utils.angle(bo.getX()) + "f," + Utils.angle(bo.getY()) + "f," + Utils.angle(bo.getZ()) + "f],")) + (he.equals(zero) ? "" : ("Head:[" + Utils.angle(he.getX()) + "f," + Utils.angle(he.getY()) + "f," + Utils.angle(he.getZ()) + "f],")) + (ll.equals(zero) ? "" : ("LeftLeg:[" + Utils.angle(ll.getX()) + "f," + Utils.angle(ll.getY()) + "f," + Utils.angle(ll.getZ()) + "f],")) + (rl.equals(zero) ? "" : ("RightLeg:[" + Utils.angle(rl.getX()) + "f," + Utils.angle(rl.getY()) + "f," + Utils.angle(rl.getZ()) + "f],")) + (la.equals(zero) ? "" : ("LeftArm:[" + Utils.angle(la.getX()) + "f," + Utils.angle(la.getY()) + "f," + Utils.angle(la.getZ()) + "f],")) + "RightArm:[" + Utils.angle(ra.getX()) + "f," + Utils.angle(ra.getY()) + "f," + Utils.angle(ra.getZ()) + "f]}}"; Block b = l.getBlock(); b.setType(Material.COMMAND); b.setData((byte) 0); CommandBlock cb = (CommandBlock) b.getState(); cb.setCommand(cmd); cb.update(); } @SuppressWarnings("deprecation") @EventHandler public void onSignChange(final SignChangeEvent event) { if(event.getBlock().hasMetadata("armorStand")) { final Block b = event.getBlock(); final ArmorStand as = getArmorStand(b); boolean delete = true; if (as != null) { String input = ""; for (String line : event.getLines()) { if (line != null && line.length() > 0) { input += ChatColor.translateAlternateColorCodes('&', line); } } if(b.hasMetadata("setName")) { if (input.length() > 0) { as.setCustomName(input); as.setCustomNameVisible(true); } else { as.setCustomName(""); as.setCustomNameVisible(false); as.setCustomNameVisible(false); } } else if(b.hasMetadata("setSkull")) { if(MC_USERNAME_PATTERN.matcher(input).matches()) { final String name = input; b.setType(Material.SKULL); final Skull s = (Skull) b.getState(); s.setSkullType(SkullType.PLAYER); delete = false; event.getPlayer().sendMessage(ChatColor.GOLD + Config.pleaseWait); new BukkitRunnable() { @Override public void run() { final boolean ok = Utils.loadProfile(name); new BukkitRunnable() { @Override public void run() { if (ok) { s.setOwner(name); s.update(); as.setHelmet(b.getDrops().iterator().next()); event.getPlayer().sendMessage(ChatColor.GREEN + Config.appliedHead + ChatColor.GOLD + " " + name); } else { event.getPlayer().sendMessage(ChatColor.RED + Config.noHead + ChatColor.GOLD + " " + name); } b.setType(Material.AIR); b.setData((byte) 0); } }.runTask(plugin); } }.runTaskAsynchronously(plugin); } else { event.getPlayer().sendMessage(ChatColor.RED + input + " " + Config.invalidName); } } } event.setCancelled(true); b.removeMetadata("armorStand", plugin); b.removeMetadata("setName", plugin); b.removeMetadata("setSkull", plugin); if(delete) { b.setType(Material.AIR); b.setData((byte) 0); } } } @SuppressWarnings("deprecation") private void setName(Player p, ArmorStand as) { Block b = Utils.findAnAirBlock(p.getLocation()); if(b == null || !checkPermission(p, b)) { p.sendMessage(ChatColor.RED + Config.noAirError); return; } b.setData((byte) 0); b.setType(Material.SIGN_POST); Utils.openSign(p, b); b.setMetadata("armorStand", new FixedMetadataValue(plugin, as.getUniqueId())); b.setMetadata("setName", new FixedMetadataValue(plugin, true)); } @SuppressWarnings("deprecation") private void setPlayerSkull(Player p, ArmorStand as) { Block b = Utils.findAnAirBlock(p.getLocation()); if(b == null) { p.sendMessage(ChatColor.RED + Config.noAirError); return; } b.setData((byte) 0); b.setType(Material.SIGN_POST); Utils.openSign(p, b); b.setMetadata("armorStand", new FixedMetadataValue(plugin, as.getUniqueId())); b.setMetadata("setSkull", new FixedMetadataValue(plugin, true)); } private ArmorStand getArmorStand(Block b) { UUID uuid = null; for (MetadataValue value : b.getMetadata("armorStand")) { if (value.getOwningPlugin() == plugin) { uuid = (UUID) value.value(); } } b.removeMetadata("armorStand", plugin); if (uuid != null) { for(org.bukkit.entity.Entity e : b.getWorld().getEntities()) { if(e instanceof ArmorStand && e.getUniqueId().equals(uuid)) { return (ArmorStand) e; } } } return null; } public boolean checkPermission(Player player, Block block) { // Check PlotSquared Location loc = block.getLocation(); if (PlotSquaredHook.api != null) { if (PlotSquaredHook.isPlotWorld(loc)) { boolean result = PlotSquaredHook.checkPermission(player, loc); return result; } } // check WorldGuard if(Config.worldGuardPlugin != null) { boolean canBuild = Config.worldGuardPlugin.canBuild(player, block); return canBuild; } BlockBreakEvent mybreak = new BlockBreakEvent(block, player); Bukkit.getServer().getPluginManager().callEvent(mybreak); boolean hasperm; if (mybreak.isCancelled()) { hasperm = false; } else { hasperm = true; } BlockPlaceEvent place = new BlockPlaceEvent(block, block.getState(), block, null, player, true); Bukkit.getServer().getPluginManager().callEvent(place); if (place.isCancelled()) { hasperm = false; } return hasperm; } boolean playerHasPermission(Player p, Block b, ArmorStandTool tool) { if(tool != null && !p.isOp() && (!Utils.hasPermissionNode(p, "astools.use") || (ArmorStandTool.SAVE == tool && !Utils.hasPermissionNode(p, "astools.cmdblock")) || (ArmorStandTool.CLONE == tool && !Utils.hasPermissionNode(p, "astools.clone")))) { p.sendMessage(ChatColor.RED + Config.noPerm); return false; } return checkPermission(p, b); } void pickUpArmorStand(ArmorStand as, Player p, boolean newlySummoned) { plugin.carryingArmorStand.put(p.getUniqueId(), as); if(newlySummoned) return; as.setMetadata("startLoc", new FixedMetadataValue(plugin, as.getLocation())); } }
package com.vectrace.MercurialEclipse.team; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Observable; import java.util.Scanner; import java.util.Set; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IResourceChangeListener; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.team.core.RepositoryProvider; import org.eclipse.team.core.TeamException; import com.vectrace.MercurialEclipse.MercurialEclipsePlugin; import com.vectrace.MercurialEclipse.SafeUiJob; import com.vectrace.MercurialEclipse.commands.HgIncomingClient; import com.vectrace.MercurialEclipse.commands.HgLogClient; import com.vectrace.MercurialEclipse.commands.HgOutgoingClient; import com.vectrace.MercurialEclipse.commands.HgStatusClient; import com.vectrace.MercurialEclipse.exception.HgException; import com.vectrace.MercurialEclipse.model.ChangeSet; import com.vectrace.MercurialEclipse.model.ChangeSet.Direction; import com.vectrace.MercurialEclipse.storage.HgRepositoryLocation; import com.vectrace.MercurialEclipse.storage.HgRepositoryLocationManager; /** * Caches the Mercurial Status of each file and offers methods for retrieving, * clearing and refreshing repository state. * * @author Bastian Doetsch * */ public class MercurialStatusCache extends Observable implements IResourceChangeListener { private final class ChangeSetIndexComparator implements Comparator<ChangeSet> { public int compare(ChangeSet arg0, ChangeSet arg1) { return arg0.getChangesetIndex() - arg1.getChangesetIndex(); } } public final static int BIT_IGNORE = 0; public final static int BIT_CLEAN = 1; public final static int BIT_DELETED = 2; public final static int BIT_REMOVED = 3; public final static int BIT_UNKNOWN = 4; public final static int BIT_ADDED = 5; public final static int BIT_MODIFIED = 6; public final static int BIT_IMPOSSIBLE = 7; private static MercurialStatusCache instance; /** Used to store the last known status of a resource */ private static Map<IResource, BitSet> statusMap = new HashMap<IResource, BitSet>(); /** Used to store which projects have already been parsed */ private static Set<IProject> knownStatus; private static Map<IResource, SortedSet<ChangeSet>> localChangeSets; /** * The Map has the following structure: RepositoryLocation -> IResource -> * Changeset-Set */ private static Map<String, Map<IResource, SortedSet<ChangeSet>>> outgoingChangeSets; private static Map<String, ChangeSet> nodeMap = new TreeMap<String, ChangeSet>(); private static Map<IProject, Set<IResource>> projectResources; /** * The Map has the following structure: RepositoryLocation -> IResource -> * Changeset-Set */ private static Map<String, Map<IResource, SortedSet<ChangeSet>>> incomingChangeSets; private boolean localUpdateInProgress = false; private boolean incomingUpdateInProgress = false; private boolean statusUpdateInProgress = false; private boolean outgoingUpdateInProgress = false; private static Comparator<ChangeSet> changeSetIndexComparator; private MercurialStatusCache() { changeSetIndexComparator = new ChangeSetIndexComparator(); knownStatus = new HashSet<IProject>(); localChangeSets = new HashMap<IResource, SortedSet<ChangeSet>>(); projectResources = new HashMap<IProject, Set<IResource>>(); incomingChangeSets = new HashMap<String, Map<IResource, SortedSet<ChangeSet>>>(); outgoingChangeSets = new HashMap<String, Map<IResource, SortedSet<ChangeSet>>>(); ResourcesPlugin.getWorkspace().addResourceChangeListener(this); new SafeUiJob("Initializing Mercurial") { @Override protected IStatus runSafe(IProgressMonitor monitor) { try { monitor.beginTask( "Obtaining Mercurial Status information.", 5); refreshStatus(monitor); } catch (TeamException e) { MercurialEclipsePlugin.logError(e); } return super.runSafe(monitor); } }.schedule(); } public static MercurialStatusCache getInstance() { if (instance == null) { instance = new MercurialStatusCache(); } return instance; } /** * Clears the known status of all resources and projects. and calls for an * update of decoration */ public synchronized void clear() { /* * While this clearing of status is a "naive" implementation, it is * simple. */ statusMap.clear(); knownStatus.clear(); projectResources.clear(); incomingChangeSets.clear(); localChangeSets.clear(); setChanged(); notifyObservers(knownStatus.toArray(new IProject[knownStatus.size()])); } /** * Checks if status for given project is known. * * @param project * the project to be checked * @return true if known, false if not. */ public boolean isStatusKnown(IProject project) { if (statusUpdateInProgress) { synchronized (statusMap) { // wait... } } return knownStatus.contains(project); } /** * Checks if incoming status for given project is known for any location. * * @param project * the project to be checked * @return true if known, false if not. */ public boolean isIncomingStatusKnown(IProject project) { if (incomingUpdateInProgress) { synchronized (incomingChangeSets) { // wait... } } if (incomingChangeSets != null && incomingChangeSets.size() > 0) { for (Iterator<String> iterator = incomingChangeSets.keySet() .iterator(); iterator.hasNext();) { Map<IResource, SortedSet<ChangeSet>> currLocMap = incomingChangeSets .get(iterator.next()); if (currLocMap != null && currLocMap.get(project) != null) { return true; } } } return false; } /** * Gets the status of the given resource from cache. The returned BitSet * contains a BitSet of the status flags set. * * The flags correspond to the BIT_* constants in this class. * * @param objectResource * the resource to get status for. * @return the BitSet with status flags. */ public BitSet getStatus(IResource objectResource) { if (statusUpdateInProgress) { synchronized (statusMap) { // wait... } } return statusMap.get(objectResource); } /** * Checks whether version is known. * * @param objectResource * the resource to be checked. * @return true if known, false if not. */ public boolean isLocallyKnown(IResource objectResource) { if (localUpdateInProgress) { synchronized (localChangeSets) { // wait... } } return localChangeSets.containsKey(objectResource); } /** * Gets version for given resource. * * @param objectResource * the resource to get status for. * @return a String with version information. * @throws HgException */ public ChangeSet getNewestLocalChangeSet(IResource objectResource) throws HgException { if (localUpdateInProgress) { synchronized (localChangeSets) { // waiting for update... } } SortedSet<ChangeSet> revisions = getLocalChangeSets(objectResource); if (revisions != null && revisions.size() > 0) { return revisions.last(); } return null; } public boolean isSupervised(IResource resource) { BitSet status = getStatus(resource); if (status != null) { switch (status.length() - 1) { case MercurialStatusCache.BIT_IGNORE: case MercurialStatusCache.BIT_UNKNOWN: return false; } return true; } return false; } public SortedSet<ChangeSet> getLocalChangeSets(IResource objectResource) throws HgException { SortedSet<ChangeSet> revisions = localChangeSets.get(objectResource); if (revisions == null) { if (objectResource.getType() != IResource.FOLDER && isSupervised(objectResource)) { refreshAllLocalRevisions(objectResource.getProject()); revisions = localChangeSets.get(objectResource); } } if (revisions != null) { return Collections.unmodifiableSortedSet(revisions); } return null; } /** * Gets all incoming chnagesets of all known project locations for the given * IResource. * * @param objectResource * @return * @throws HgException */ public SortedSet<ChangeSet> getIncomingChangeSets(IResource objectResource) throws HgException { if (incomingUpdateInProgress) { synchronized (incomingChangeSets) { // wait } } Set<HgRepositoryLocation> repos = MercurialEclipsePlugin .getRepoManager().getAllProjectRepoLocations( objectResource.getProject()); SortedSet<ChangeSet> allChanges = new TreeSet<ChangeSet>(); for (Iterator<HgRepositoryLocation> iterator = repos.iterator(); iterator .hasNext();) { HgRepositoryLocation hgRepositoryLocation = iterator.next(); SortedSet<ChangeSet> repoChanges = getIncomingChangeSets( objectResource, hgRepositoryLocation.getUrl()); if (repoChanges != null) { allChanges.addAll(repoChanges); } } return Collections.unmodifiableSortedSet(allChanges); } /** * Gets all incoming changesets of the given location for the given * IResource. * * @param objectResource * @param repositoryLocation * @return * @throws HgException */ public SortedSet<ChangeSet> getIncomingChangeSets(IResource objectResource, String repositoryLocation) throws HgException { if (incomingUpdateInProgress) { synchronized (incomingChangeSets) { // wait... } } Map<IResource, SortedSet<ChangeSet>> repoIncoming = incomingChangeSets .get(repositoryLocation); SortedSet<ChangeSet> revisions = null; if (repoIncoming != null) { revisions = repoIncoming.get(objectResource); } if (revisions == null) { refreshIncomingChangeSets(objectResource.getProject(), repositoryLocation); repoIncoming = incomingChangeSets.get(repositoryLocation); if (repoIncoming != null) { revisions = repoIncoming.get(objectResource); } } if (revisions != null) { return Collections.unmodifiableSortedSet(incomingChangeSets.get( repositoryLocation).get(objectResource)); } return null; } /** * Gets all outgoing changesets of the given location for the given * IResource. * * @param objectResource * @param repositoryLocation * @return * @throws HgException */ public SortedSet<ChangeSet> getOutgoingChangeSets(IResource objectResource, String repositoryLocation) throws HgException { if (outgoingUpdateInProgress) { synchronized (outgoingChangeSets) { // wait... } } Map<IResource, SortedSet<ChangeSet>> repoOutgoing = outgoingChangeSets .get(repositoryLocation); SortedSet<ChangeSet> revisions = null; if (repoOutgoing != null) { revisions = repoOutgoing.get(objectResource); } if (revisions == null) { refreshOutgoingChangeSets(objectResource.getProject(), repositoryLocation); } if (revisions != null) { return Collections.unmodifiableSortedSet(outgoingChangeSets.get( repositoryLocation).get(objectResource)); } return null; } /** * Refreshes local repository status. No refresh of incoming changesets. * * @param project * @throws TeamException */ public void refresh(final IProject project) throws TeamException { refresh(project, null, null); } /** * Refreshes sync status of given project by questioning Mercurial. * * @param project * the project to refresh * @param monitor * the progress monitor * @param repositoryLocation * the remote repository to get the incoming changesets from. If * null, no incoming changesets will be retrieved. * @throws TeamException */ public void refresh(final IProject project, IProgressMonitor monitor, String repositoryLocation) throws TeamException { /* hg status on project (all files) instead of per file basis */ try { if (null != RepositoryProvider.getProvider(project, MercurialTeamProvider.ID) && project.isOpen()) { // set status refreshStatus(project, monitor); if (monitor != null) { monitor.subTask("Updating status and version cache..."); } try { if (monitor != null) { monitor.subTask("Loading local revisions..."); } refreshAllLocalRevisions(project); if (monitor != null) { monitor.worked(1); } // incoming if (repositoryLocation != null) { if (monitor != null) { monitor.subTask("Loading incoming revisions for " + repositoryLocation); } refreshIncomingChangeSets(project, repositoryLocation); if (monitor != null) { monitor.worked(1); } if (monitor != null) { monitor.subTask("Loading outgoing revisions for " + repositoryLocation); } refreshOutgoingChangeSets(project, repositoryLocation); if (monitor != null) { monitor.worked(1); } if (monitor != null) { monitor .subTask("Adding remote repository to project repositories..."); } try { MercurialEclipsePlugin.getRepoManager() .addRepoLocation( project, new HgRepositoryLocation( repositoryLocation)); } catch (MalformedURLException e) { MercurialEclipsePlugin .logWarning( "couldn't add repository to location manager", e); } if (monitor != null) { monitor.worked(1); } } setChanged(); notifyObservers(project); } catch (HgException e) { MercurialEclipsePlugin.logError(e); } } } catch (HgException e) { throw new TeamException(e.getMessage(), e); } } /** * @param project * @throws HgException */ public void refreshStatus(final IResource res, IProgressMonitor monitor) throws HgException { try { if (monitor != null) { monitor.beginTask("Refreshing " + res.getName(), 50); } if (null != RepositoryProvider.getProvider(res.getProject(), MercurialTeamProvider.ID) && res.getProject().isOpen()) { synchronized (statusMap) { statusUpdateInProgress = true; // members should contain folders and project, so we clear // status for files, folders and project IResource[] resources = getLocalMembers(res); for (IResource resource : resources) { statusMap.remove(resource); } statusMap.remove(res); String output = HgStatusClient.getStatus(res); parseStatus(res, output); } } } finally { statusUpdateInProgress = false; } setChanged(); notifyObservers(res); } /** * Gets all incoming changesets by querying Mercurial and adds them to the * caches. * * @param project * @param repositoryLocation * @throws HgException */ public void refreshIncomingChangeSets(IProject project, String repositoryLocation) throws HgException { // check if mercurial is team provider and if we're working on an // open project if (null != RepositoryProvider.getProvider(project, MercurialTeamProvider.ID) && project.isOpen()) { // lock the cache till update is complete synchronized (incomingChangeSets) { try { incomingUpdateInProgress = true; addResourcesToCache(project, repositoryLocation, incomingChangeSets, Direction.INCOMING); } finally { incomingUpdateInProgress = false; } } } } /** * Gets all outgoing changesets by querying Mercurial and adds them to the * caches. * * @param project * @param repositoryLocation * @throws HgException */ public void refreshOutgoingChangeSets(IProject project, String repositoryLocation) throws HgException { // check if mercurial is team provider and if we're working on an // open project if (null != RepositoryProvider.getProvider(project, MercurialTeamProvider.ID) && project.isOpen()) { // lock the cache till update is complete synchronized (outgoingChangeSets) { try { outgoingUpdateInProgress = true; addResourcesToCache(project, repositoryLocation, outgoingChangeSets, Direction.OUTGOING); } finally { outgoingUpdateInProgress = false; } } } } /** * @param repositoryLocation * @param outgoing * flag, which direction should be queried. * @param changeSetMap * @throws HgException */ private void addResourcesToCache(IProject project, String repositoryLocation, Map<String, Map<IResource, SortedSet<ChangeSet>>> changeSetMap, Direction direction) throws HgException { // load latest outgoing changesets from repository given in // parameter HgRepositoryLocationManager repoManager = MercurialEclipsePlugin .getRepoManager(); HgRepositoryLocation hgRepositoryLocation = repoManager .getRepoLocation(repositoryLocation); // clear cache of old members final Map<IResource, SortedSet<ChangeSet>> removeMap = changeSetMap .get(repositoryLocation); if (removeMap != null) { removeMap.clear(); changeSetMap.remove(repositoryLocation); } if (hgRepositoryLocation == null) { try { hgRepositoryLocation = new HgRepositoryLocation( repositoryLocation); repoManager.addRepoLocation(hgRepositoryLocation); } catch (MalformedURLException e) { MercurialEclipsePlugin.logError(e); throw new HgException(e.getLocalizedMessage(), e); } } // get changesets from hg Map<IResource, SortedSet<ChangeSet>> resources; if (direction == Direction.OUTGOING) { resources = HgOutgoingClient.getOutgoing(project, hgRepositoryLocation); } else { resources = HgIncomingClient.getHgIncoming(project, hgRepositoryLocation); } // add them to cache(s) if (resources != null && resources.size() > 0) { for (Iterator<IResource> iter = resources.keySet().iterator(); iter .hasNext();) { IResource res = iter.next(); SortedSet<ChangeSet> changes = resources.get(res); if (changes != null && changes.size() > 0) { SortedSet<ChangeSet> revisions = new TreeSet<ChangeSet>(); ChangeSet[] changeSets = changes .toArray(new ChangeSet[changes.size()]); if (changeSets != null) { for (ChangeSet changeSet : changeSets) { revisions.add(changeSet); if (direction == Direction.INCOMING) { synchronized (nodeMap) { nodeMap .put(changeSet.toString(), changeSet); } } } } Map<IResource, SortedSet<ChangeSet>> map = changeSetMap .get(repositoryLocation); if (map == null) { map = new HashMap<IResource, SortedSet<ChangeSet>>(); } map.put(res, revisions); changeSetMap.put(repositoryLocation, map); } } } } /** * @param res * @param output * @param ctrParent */ private void parseStatus(IResource res, String output) { if (res.getType() == IResource.PROJECT) { knownStatus.add(res.getProject()); } Scanner scanner = new Scanner(output); while (scanner.hasNext()) { String status = scanner.next(); String localName = scanner.nextLine(); IResource member = res.getProject().getFile(localName.trim()); BitSet bitSet = new BitSet(); bitSet.set(getBitIndex(status.charAt(0))); statusMap.put(member, bitSet); if (member.getType() == IResource.FILE && getBitIndex(status.charAt(0)) != BIT_IGNORE) { addToProjectResources(member); } // ancestors for (IResource parent = member.getParent(); parent != res .getParent(); parent = parent.getParent()) { BitSet parentBitSet = statusMap.get(parent); if (parentBitSet != null) { bitSet = (BitSet) bitSet.clone(); bitSet.or(parentBitSet); } statusMap.put(parent, bitSet); addToProjectResources(parent); } } } private void addToProjectResources(IResource member) { if (member.getType() == IResource.PROJECT) { return; } Set<IResource> set = projectResources.get(member.getProject()); if (set == null) { set = new HashSet<IResource>(); } set.add(member); projectResources.put(member.getProject(), set); } public int getBitIndex(char status) { switch (status) { case '!': return BIT_DELETED; case 'R': return BIT_REMOVED; case 'I': return BIT_IGNORE; case 'C': return BIT_CLEAN; case '?': return BIT_UNKNOWN; case 'A': return BIT_ADDED; case 'M': return BIT_MODIFIED; default: MercurialEclipsePlugin.logWarning("Unknown status: '" + status + "'", null); return BIT_IMPOSSIBLE; } } /** * Refreshes the sync status for each project in Workspace by questioning * Mercurial. No refresh of incoming changesets. * * @throws TeamException * if status check encountered problems. */ public void refresh() throws TeamException { IProject[] projects = ResourcesPlugin.getWorkspace().getRoot() .getProjects(); for (IProject project : projects) { refresh(project, null, null); } } /** * Refreshes the status for each project in Workspace by questioning * Mercurial. * * @throws TeamException * if status check encountered problems. */ public void refreshStatus(IProgressMonitor monitor) throws TeamException { IProject[] projects = ResourcesPlugin.getWorkspace().getRoot() .getProjects(); for (IProject project : projects) { refreshStatus(project, monitor); } } /** * Checks whether Status of given resource is known. * * @param resource * the resource to be checked * @return true if known, false if not */ public boolean isStatusKnown(IResource resource) { return getStatus(resource) != null; } /** * Gets all Projects managed by Mercurial whose status is known. * * @return an IProject[] of the projects */ public IProject[] getAllManagedProjects() { return knownStatus.toArray(new IProject[knownStatus.size()]); } /** * Determines Members of given resource without adding itself. * * @param resource * @return */ public IResource[] getLocalMembers(IResource resource) { if (statusUpdateInProgress) { synchronized (statusMap) { // wait... } } IContainer container = (IContainer) resource; Set<IResource> members = new HashSet<IResource>(); switch (resource.getType()) { case IResource.FILE: break; case IResource.PROJECT: Set<IResource> resources = projectResources.get(resource); if (resources != null) { members.addAll(resources); members.remove(resource); } break; case IResource.FOLDER: for (Iterator<IResource> iterator = new HashMap<IResource, BitSet>( statusMap).keySet().iterator(); iterator.hasNext();) { IResource member = iterator.next(); if (member.equals(resource)) { continue; } IResource foundMember = container.findMember(member.getName()); if (foundMember != null && foundMember.equals(member)) { members.add(member); } } } members.remove(resource); return members.toArray(new IResource[members.size()]); } /** * Gets all resources that are changed in incoming changesets of given * repository, even resources not known in local workspace. * * @param resource * @param repositoryLocation * @return */ public IResource[] getIncomingMembers(IResource resource, String repositoryLocation) { if (incomingUpdateInProgress) { synchronized (incomingChangeSets) { // wait... } } Map<IResource, SortedSet<ChangeSet>> changeSets = incomingChangeSets .get(repositoryLocation); if (changeSets != null) { return changeSets.keySet() .toArray(new IResource[changeSets.size()]); } return new IResource[0]; } /** * Gets all resources that are changed in incoming changesets of given * repository, even resources not known in local workspace. * * @param resource * @param repositoryLocation * @return */ public IResource[] getOutgoingMembers(IResource resource, String repositoryLocation) { if (outgoingUpdateInProgress) { synchronized (outgoingChangeSets) { // wait... } } Map<IResource, SortedSet<ChangeSet>> changeSets = outgoingChangeSets .get(repositoryLocation); if (changeSets != null) { return changeSets.keySet() .toArray(new IResource[changeSets.size()]); } return new IResource[0]; } public ChangeSet getNewestIncomingChangeSet(IResource resource, String repositoryLocation) throws HgException { if (incomingUpdateInProgress) { synchronized (incomingChangeSets) { // wait for update... } } if (isSupervised(resource)) { Map<IResource, SortedSet<ChangeSet>> repoMap = incomingChangeSets .get(repositoryLocation); SortedSet<ChangeSet> revisions = null; if (repoMap != null) { revisions = repoMap.get(resource); } if (revisions != null && revisions.size() > 0) { return revisions.last(); } } return null; } public ChangeSet getNewestOutgoingChangeSet(IResource resource, String repositoryLocation) throws HgException { if (outgoingUpdateInProgress) { synchronized (outgoingChangeSets) { // wait for update... } } if (isSupervised(resource)) { Map<IResource, SortedSet<ChangeSet>> repoMap = outgoingChangeSets .get(repositoryLocation); SortedSet<ChangeSet> revisions = null; if (repoMap != null) { revisions = repoMap.get(resource); } if (revisions != null && revisions.size() > 0) { return revisions.last(); } } return null; } /** * Refreshes all local revisions, uses default limit of revisions to get, * e.g. the top 50 revisions. * * If a resource version can't be found in the topmost revisions, the last * revisions of this file (10% of limit number) are obtained via additional * calls. * * @param project * @throws HgException */ public void refreshAllLocalRevisions(IProject project) throws HgException { this.refreshAllLocalRevisions(project, true); } /** * Refreshes all local revisions. If limit is set, it looks up the default * number of revisions to get and fetches the topmost till limit is reached. * * If a resource version can't be found in the topmost revisions, the last * revisions of this file (10% of limit number) are obtained via additional * calls. * * @param project * @param limit * whether to limit or to have full project log * @throws HgException */ public void refreshAllLocalRevisions(IProject project, boolean limit) throws HgException { if (null != RepositoryProvider.getProvider(project, MercurialTeamProvider.ID) && project.isOpen()) { int defaultLimit = 2000; try { String result = project .getPersistentProperty(MercurialTeamProvider.QUALIFIED_NAME_DEFAULT_REVISION_LIMIT); if (result != null) { defaultLimit = Integer.parseInt(result); } } catch (CoreException e) { MercurialEclipsePlugin.logError(e); } this.refreshAllLocalRevisions(project, limit, defaultLimit); } } /** * Refreshes all local revisions. If limit is set, it looks up the default * number of revisions to get and fetches the topmost till limit is reached. * * If a resource version can't be found in the topmost revisions, the last * revisions of this file (10% of limit number) are obtained via additional * calls. * * @param project * @param limit * whether to limit or to have full project log * @param limitNumber * if limit is set, how many revisions should be fetched * @throws HgException */ public void refreshAllLocalRevisions(IProject project, boolean limit, int limitNumber) throws HgException { if (null != RepositoryProvider.getProvider(project, MercurialTeamProvider.ID) && project.isOpen()) { synchronized (localChangeSets) { try { localUpdateInProgress = true; Map<IResource, SortedSet<ChangeSet>> revisions = null; if (limit) { revisions = HgLogClient.getRecentProjectLog(project, limitNumber); } else { revisions = HgLogClient.getCompleteProjectLog(project); } Set<IResource> resources = new HashSet<IResource>(Arrays .asList(getLocalMembers(project))); for (IResource resource : resources) { localChangeSets.remove(resource); } localChangeSets.remove(project); Set<IResource> concernedResources = new HashSet<IResource>(); concernedResources.add(project); concernedResources.addAll(resources); if (revisions != null && revisions.size() > 0) { concernedResources.addAll(revisions.keySet()); for (Iterator<IResource> iter = revisions.keySet() .iterator(); iter.hasNext();) { IResource res = iter.next(); SortedSet<ChangeSet> changes = revisions.get(res); // if changes for resource not in top 50, get at // least if (changes == null && limit) { changes = HgLogClient.getRecentProjectLog(res, limitNumber / 10).get(res); } // add changes to cache if (changes != null && changes.size() > 0) { if (isSupervised(res)) { localChangeSets.put(res, changes); addToNodeMap(changes); } } } } } finally { localUpdateInProgress = false; } } } } /** * @param changes */ private void addToNodeMap(SortedSet<ChangeSet> changes) { for (ChangeSet changeSet : changes) { synchronized (nodeMap) { nodeMap.put(changeSet.toString(), changeSet); } } } public void resourceChanged(IResourceChangeEvent event) { // only refresh after a change - we aren't interested in build outputs, // are we? if (event.getType() == IResourceChangeEvent.POST_CHANGE) { // workspace childs IResourceDelta[] wsChildren = event.getDelta() .getAffectedChildren(); for (IResourceDelta wsChild : wsChildren) { // update whole project :-(. else we'd have to walk the project // tree. final IResource res = wsChild.getResource(); if (null != RepositoryProvider.getProvider(res.getProject(), MercurialTeamProvider.ID) && res.getProject().isOpen()) { new SafeUiJob("Refreshing status of resource " + res.getName()) { @Override protected IStatus runSafe(IProgressMonitor monitor) { try { monitor.beginTask( "Starting to refresh status of " + res.getName(), 10); refreshStatus(res, monitor); return super.runSafe(monitor); } catch (HgException e) { MercurialEclipsePlugin.logError(e); return new Status(IStatus.ERROR, MercurialEclipsePlugin.ID, "Couldn't refresh status of " + res.getName() + ". E: " + e.getMessage()); } } }.schedule(); } } } } /** * Gets Changeset by its identifier * * @param changeSet * string in format rev:nodeshort * @return */ public ChangeSet getChangeSet(String changeSet) { if (localUpdateInProgress || incomingUpdateInProgress) { synchronized (nodeMap) { // wait } } return nodeMap.get(changeSet); } public ChangeSet getChangeSet(IResource res, int changesetIndex) throws HgException { if (localUpdateInProgress || incomingUpdateInProgress) { synchronized (nodeMap) { // wait } } SortedSet<ChangeSet> locals = getLocalChangeSets(res); List<ChangeSet> list = new ArrayList<ChangeSet>(locals); int index = Collections.binarySearch(list, new ChangeSet( changesetIndex, "", "", ""), changeSetIndexComparator); if (index >= 0) { return list.get(index); } return null; } @Deprecated public String[] getParentsChangeSet(IResource res, ChangeSet cs) throws HgException { SortedSet<ChangeSet> changeSets = getLocalChangeSets(res); String[] parents = cs.getParents(); if (parents == null || parents.length == 0) { ChangeSet candidate = cs; int currIndex = cs.getChangesetIndex() - 1; boolean found = false; do { candidate = getChangeSet(res, currIndex); if (candidate == null) { currIndex } else { found = changeSets.contains(candidate); } } while (currIndex >= 0 && !found); if (candidate != null && candidate != cs) { return new String[] { candidate.toString() }; } } return parents; } /** * Gets the newest incoming changeset of <b>all repositories</b>. * * @param resource * the resource to get the changeset for * @return * @throws HgException */ public ChangeSet getNewestIncomingChangeSet(IResource objectResource) throws HgException { Set<HgRepositoryLocation> locs = MercurialEclipsePlugin .getRepoManager().getAllProjectRepoLocations( objectResource.getProject()); SortedSet<ChangeSet> changeSets = new TreeSet<ChangeSet>(); for (HgRepositoryLocation hgRepositoryLocation : locs) { ChangeSet candidate = getNewestIncomingChangeSet(objectResource, hgRepositoryLocation.getUrl()); if (candidate != null) { changeSets.add(candidate); } } if (changeSets.size() > 0) { return changeSets.last(); } return null; } }
package codeine.db.mysql.connectors; import com.google.gson.JsonSyntaxException; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.inject.Inject; import org.apache.log4j.Logger; import codeine.db.IStatusDatabaseConnector; import codeine.db.mysql.DbUtils; import codeine.jsons.global.ExperimentalConfJsonStore; import codeine.jsons.peer_status.PeerStatusJsonV2; import codeine.jsons.peer_status.PeerStatusString; import codeine.jsons.peer_status.PeerType; import codeine.utils.ExceptionUtils; import com.google.common.base.Function; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.gson.Gson; public class StatusMysqlConnector implements IStatusDatabaseConnector { private static final Logger log = Logger.getLogger(StatusMysqlConnector.class); @Inject private DbUtils dbUtils; @Inject private Gson gson; @Inject private ExperimentalConfJsonStore webConfJsonStore; private static final String TABLE_NAME = "ProjectStatusList"; public StatusMysqlConnector() { super(); } public StatusMysqlConnector(DbUtils dbUtils, Gson gson, ExperimentalConfJsonStore webConfJsonStore) { super(); this.dbUtils = dbUtils; this.gson = gson; this.webConfJsonStore = webConfJsonStore; } public void createTables() { if (webConfJsonStore.get().readonly_web_server()) { log.info("read only mode"); return; } String colsDefinition = "peer_key VARCHAR(150) NOT NULL PRIMARY KEY, data text, update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, status VARCHAR(50) DEFAULT 'On' NOT NULL"; dbUtils.executeUpdate("create table if not exists " + TABLE_NAME + " (" + colsDefinition + ")"); } @Override public void putReplaceStatus(PeerStatusJsonV2 p) { String json = gson.toJson(p); log.info("will update status to " + dbUtils.server() + "\n" + json); dbUtils.executeUpdate("DELETE FROM " + TABLE_NAME + " WHERE peer_key = '" + p.peer_key() + "'"); dbUtils.executeUpdate( "REPLACE INTO " + TABLE_NAME + " (peer_key, data, update_time ) VALUES (?, ?, CURRENT_TIMESTAMP())", p.peer_key(), json); } @Override public Map<String, PeerStatusJsonV2> getPeersStatus() { log.info("getPeersStatus " + dbUtils.server()); final Map<String, PeerStatusJsonV2> $ = Maps.newHashMap(); Function<ResultSet, Void> function = rs -> { try { String key = rs.getString(1); log.debug("Checking key " + key); String value = rs.getString(2); PeerStatusJsonV2 peerStatus = gson.fromJson(value, PeerStatusJsonV2.class); peerStatus.status(PeerStatusString.valueOf(rs.getString("status"))); updateNodesWithPeer(peerStatus); $.put(key, peerStatus); return null; } catch (SQLException e) { throw ExceptionUtils.asUnchecked(e); } catch (JsonSyntaxException e) { log.error("Got json exception while trying to parse line, will skip this node", e); return null; } }; dbUtils.executeQueryCompressed("select * from " + TABLE_NAME, function); return $; } private void updateNodesWithPeer(PeerStatusJsonV2 peerStatus) { peerStatus.updateNodesWithPeer(); } @Override public void updatePeersStatus(final long timeToRemove, final long timeToDisc) { final List<String> idToRemove = Lists.newArrayList(); final List<String> idToDisc = Lists.newArrayList(); Function<ResultSet, Void> function = rs -> { try { String key = rs.getString("peer_key"); // PeerStatusString status = PeerStatusString.valueOf(rs.getString("status")); String value = rs.getString("data"); String status = rs.getString("status"); PeerStatusJsonV2 peerStatus = gson.fromJson(value, PeerStatusJsonV2.class); PeerType peerType = peerStatus.peer_type(); long timeToRemovePeer = peerType == PeerType.Reporter ? timeToRemove + TimeUnit.DAYS.toMinutes(7) : timeToRemove; long timeToDiscPeer = peerType == PeerType.Reporter ? timeToDisc + TimeUnit.DAYS.toMinutes(7) : timeToDisc; long timeDiff = rs.getLong("TIME_DIFF"); log.debug("time diff is " + timeDiff); if (timeDiff > timeToRemovePeer) { log.info("time diff is " + timeDiff); log.info("deleting " + peerStatus); // rs.deleteRow(); idToRemove.add(key); } else if (timeDiff > timeToDiscPeer && !status.equals(PeerStatusString.Disc.toString())) { log.info("time diff is " + timeDiff); log.info("update to disc " + peerStatus); idToDisc.add(key); // rs.updateString("status", "Disc"); // rs.updateRow(); } return null; } catch (SQLException e) { throw ExceptionUtils.asUnchecked(e); } }; dbUtils.executeUpdateableQuery( "select *,TIMESTAMPDIFF(MINUTE,update_time,CURRENT_TIMESTAMP()) as TIME_DIFF from " + TABLE_NAME, function); if (webConfJsonStore.get().readonly_web_server()) { log.info("read only mode"); return; } for (String key : idToRemove) { log.info("deleting " + key); dbUtils.executeUpdate("DELETE from " + TABLE_NAME + " WHERE peer_key = ?", key); } for (String key : idToDisc) { log.info("discing " + key); dbUtils.executeUpdate( "UPDATE " + TABLE_NAME + " SET status = '" + PeerStatusString.Disc.toString() + "' WHERE peer_key = ?", key); } } @Override public String server() { return dbUtils.toString(); } @Override public String toString() { return "StatusMysqlConnector [dbUtils=" + dbUtils + "]"; } }
package dyvil.tools.compiler.ast.generic; import dyvil.reflect.Modifiers; import dyvil.tools.asm.TypeAnnotatableVisitor; import dyvil.tools.asm.TypePath; import dyvil.tools.asm.TypeReference; import dyvil.tools.compiler.ast.annotation.AnnotationList; import dyvil.tools.compiler.ast.annotation.IAnnotation; import dyvil.tools.compiler.ast.classes.IClass; import dyvil.tools.compiler.ast.context.IContext; import dyvil.tools.compiler.ast.expression.IValue; import dyvil.tools.compiler.ast.field.IDataMember; import dyvil.tools.compiler.ast.generic.type.ParameterTypeVarType; import dyvil.tools.compiler.ast.method.IMethod; import dyvil.tools.compiler.ast.method.MethodMatchList; import dyvil.tools.compiler.ast.parameter.IArguments; import dyvil.tools.compiler.ast.structure.IClassCompilableList; import dyvil.tools.compiler.ast.type.IType; import dyvil.tools.compiler.ast.type.IType.TypePosition; import dyvil.tools.compiler.ast.type.Types; import dyvil.tools.compiler.config.Formatting; import dyvil.tools.parsing.Name; import dyvil.tools.parsing.marker.MarkerList; import dyvil.tools.parsing.position.ICodePosition; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.lang.annotation.ElementType; public final class TypeParameter implements ITypeParameter { protected ICodePosition position; protected Variance variance = Variance.INVARIANT; protected Name name; protected IType[] upperBounds = new IType[1]; protected int upperBoundCount; protected IType lowerBound; private int index; private ITypeParameterized generic; private AnnotationList annotations; private IType covariantType = new CovariantTypeVarType(this); public TypeParameter(ITypeParameterized generic) { this.generic = generic; } public TypeParameter(ITypeParameterized generic, Name name) { this.name = name; this.generic = generic; } public TypeParameter(ICodePosition position, ITypeParameterized generic) { this.position = position; this.generic = generic; } public TypeParameter(ICodePosition position, ITypeParameterized generic, Name name, Variance variance) { this.position = position; this.name = name; this.generic = generic; this.variance = variance; } @Override public ITypeParameterized getGeneric() { return this.generic; } @Override public void setIndex(int index) { this.index = index; } @Override public int getIndex() { return this.index; } @Override public void setVariance(Variance variance) { this.variance = variance; } @Override public Variance getVariance() { return this.variance; } @Override public void setName(Name name) { this.name = name; } @Override public Name getName() { return this.name; } @Override public void setPosition(ICodePosition position) { this.position = position; } @Override public ICodePosition getPosition() { return this.position; } @Override public AnnotationList getAnnotations() { return this.annotations; } @Override public void setAnnotations(AnnotationList annotations) { this.annotations = annotations; } @Override public void addAnnotation(IAnnotation annotation) { if (this.annotations == null) { this.annotations = new AnnotationList(); } this.annotations.addAnnotation(annotation); } @Override public boolean addRawAnnotation(String type, IAnnotation annotation) { switch (type) { case "Ldyvil/annotation/_internal/Covariant;": this.variance = Variance.COVARIANT; return false; case "Ldyvil/annotation/_internal/Contravariant;": this.variance = Variance.CONTRAVARIANT; return false; } return true; } @Override public IAnnotation getAnnotation(IClass type) { return this.annotations == null ? null : this.annotations.getAnnotation(type); } @Override public ElementType getElementType() { return ElementType.TYPE_PARAMETER; } @Override public void addBoundAnnotation(IAnnotation annotation, int index, TypePath typePath) { this.upperBounds[index] = IType .withAnnotation(this.upperBounds[index], annotation, typePath, 0, typePath.getLength()); } @Override public IType getDefaultType() { switch (this.upperBoundCount) { case 0: return Types.ANY; case 1: return this.upperBounds[0]; case 2: if (this.upperBounds[0].getTheClass() == Types.OBJECT_CLASS) { return this.upperBounds[1]; } } return Types.ANY; } @Override public IType getCovariantType() { return this.covariantType; } @Override public int upperBoundCount() { return this.upperBoundCount; } @Override public void setUpperBound(int index, IType bound) { this.upperBounds[index] = bound; } @Override public void addUpperBound(IType bound) { int index = this.upperBoundCount++; if (index >= this.upperBounds.length) { IType[] temp = new IType[this.upperBoundCount]; System.arraycopy(this.upperBounds, 0, temp, 0, index); this.upperBounds = temp; } this.upperBounds[index] = bound; } @Override public IType getUpperBound(int index) { return this.upperBounds[index]; } @Override public IType[] getUpperBounds() { return this.upperBounds; } @Override public void setLowerBound(IType bound) { this.lowerBound = bound; } @Override public IType getLowerBound() { return this.lowerBound; } @Override public IClass getTheClass() { if (this.lowerBound != null || this.upperBoundCount == 0) { return Types.OBJECT_CLASS; } return this.upperBounds[0].getTheClass(); } @Override public boolean isAssignableFrom(IType type) { if (this.upperBoundCount > 0) { for (int i = 0; i < this.upperBoundCount; i++) { if (!this.upperBounds[i].isSuperTypeOf(type)) { return false; } } } if (this.lowerBound != null) { if (!type.isSuperTypeOf(this.lowerBound)) { return false; } } return true; } @Override public boolean isSuperClassOf(IType type) { if (this.upperBoundCount > 0) { for (int i = 0; i < this.upperBoundCount; i++) { if (!this.upperBounds[i].isSuperClassOf(type)) { return false; } } } if (this.lowerBound != null) { if (!type.isSuperClassOf(this.lowerBound)) { return false; } } return true; } @Override public int getSuperTypeDistance(IType superType) { for (int i = 0; i < this.upperBoundCount; i++) { int m = superType.getSubClassDistance(this.upperBounds[i]); if (m > 0) { return m; } } return 2; } @Override public IDataMember resolveField(Name name) { IDataMember field; for (int i = 0; i < this.upperBoundCount; i++) { field = this.upperBounds[i].resolveField(name); if (field != null) { return field; } } return null; } @Override public void getMethodMatches(MethodMatchList list, IValue instance, Name name, IArguments arguments) { for (int i = 0; i < this.upperBoundCount; i++) { this.upperBounds[i].getMethodMatches(list, instance, name, arguments); } } @Override public void resolveTypes(MarkerList markers, IContext context) { if (this.lowerBound != null) { this.lowerBound = this.lowerBound.resolveType(markers, context); } if (this.upperBoundCount > 0) { // The first upper bound is meant to be a class bound. IType type = this.upperBounds[0] = this.upperBounds[0].resolveType(markers, context); IClass iclass = type.getTheClass(); if (iclass != null) { // If the first upper bound is an interface... if (iclass.hasModifier(Modifiers.INTERFACE_CLASS)) { // shift the entire array one to the right and insert // Type.OBJECT at index 0 if (++this.upperBoundCount > this.upperBounds.length) { IType[] temp = new IType[this.upperBoundCount]; temp[0] = Types.OBJECT; System.arraycopy(this.upperBounds, 0, temp, 1, this.upperBoundCount - 1); this.upperBounds = temp; } else { System.arraycopy(this.upperBounds, 0, this.upperBounds, 1, this.upperBoundCount - 1); this.upperBounds[0] = Types.OBJECT; } } } // Check if the remaining upper bounds are interfaces, and remove if // not. for (int i = 1; i < this.upperBoundCount; i++) { type = this.upperBounds[i] = this.upperBounds[i].resolveType(markers, context); iclass = type.getTheClass(); if (iclass != null && !iclass.hasModifier(Modifiers.INTERFACE_CLASS)) { System.arraycopy(this.upperBounds, i + 1, this.upperBounds, i, this.upperBoundCount - i - 1); this.upperBoundCount i } } } if (this.annotations != null) { this.annotations.resolveTypes(markers, context, this); } } @Override public void resolve(MarkerList markers, IContext context) { if (this.annotations != null) { this.annotations.resolve(markers, context); } if (this.lowerBound != null) { this.lowerBound.resolve(markers, context); } for (int i = 0; i < this.upperBoundCount; i++) { this.upperBounds[i].resolve(markers, context); } } @Override public void checkTypes(MarkerList markers, IContext context) { if (this.annotations != null) { this.annotations.checkTypes(markers, context); } if (this.lowerBound != null) { this.lowerBound.checkType(markers, context, TypePosition.SUPER_TYPE_ARGUMENT); } for (int i = 0; i < this.upperBoundCount; i++) { this.upperBounds[i].checkType(markers, context, TypePosition.SUPER_TYPE_ARGUMENT); } } @Override public void check(MarkerList markers, IContext context) { if (this.annotations != null) { this.annotations.check(markers, context, ElementType.TYPE_PARAMETER); } if (this.lowerBound != null) { this.lowerBound.check(markers, context); } for (int i = 0; i < this.upperBoundCount; i++) { this.upperBounds[i].check(markers, context); } } @Override public void foldConstants() { if (this.annotations != null) { this.annotations.foldConstants(); } if (this.lowerBound != null) { this.lowerBound.foldConstants(); } for (int i = 0; i < this.upperBoundCount; i++) { this.upperBounds[i].foldConstants(); } } @Override public void cleanup(IContext context, IClassCompilableList compilableList) { if (this.annotations != null) { this.annotations.cleanup(context, compilableList); } if (this.lowerBound != null) { this.lowerBound.cleanup(context, compilableList); } for (int i = 0; i < this.upperBoundCount; i++) { this.upperBounds[i].cleanup(context, compilableList); } } @Override public void appendSignature(StringBuilder buffer) { buffer.append(this.name).append(':'); if (this.upperBoundCount > 0) { if (this.upperBounds[0] != Types.OBJECT || this.upperBoundCount == 1) { this.upperBounds[0].appendSignature(buffer); } for (int i = 1; i < this.upperBoundCount; i++) { buffer.append(':'); this.upperBounds[i].appendSignature(buffer); } } else { buffer.append("Ljava/lang/Object;"); } } @Override public void write(TypeAnnotatableVisitor visitor) { boolean method = this.generic instanceof IMethod; int typeRef = TypeReference.newTypeParameterReference( method ? TypeReference.METHOD_TYPE_PARAMETER : TypeReference.CLASS_TYPE_PARAMETER, this.index); if (this.variance != Variance.INVARIANT) { String type = this.variance == Variance.CONTRAVARIANT ? "Ldyvil/annotation/_internal/Contravariant;" : "Ldyvil/annotation/_internal/Covariant;"; visitor.visitTypeAnnotation(typeRef, null, type, true); } for (int i = 0; i < this.upperBoundCount; i++) { typeRef = TypeReference.newTypeParameterBoundReference( method ? TypeReference.METHOD_TYPE_PARAMETER_BOUND : TypeReference.CLASS_TYPE_PARAMETER_BOUND, this.index, i); this.upperBounds[i].writeAnnotations(visitor, typeRef, ""); } } @Override public void write(DataOutput out) throws IOException { out.writeUTF(this.name.qualified); Variance.write(this.variance, out); IType.writeType(this.lowerBound, out); out.writeShort(this.upperBoundCount); for (int i = 0; i < this.upperBoundCount; i++) { IType.writeType(this.upperBounds[i], out); } } @Override public void read(DataInput in) throws IOException { this.name = Name.getQualified(in.readUTF()); this.variance = Variance.read(in); this.lowerBound = IType.readType(in); this.upperBoundCount = in.readShort(); for (int i = 0; i < this.upperBoundCount; i++) { this.upperBounds[i] = IType.readType(in); } } @Override public String toString() { StringBuilder builder = new StringBuilder(); this.toString("", builder); return builder.toString(); } @Override public void toString(String prefix, StringBuilder buffer) { if (this.annotations != null) { int count = this.annotations.annotationCount(); for (int i = 0; i < count; i++) { this.annotations.getAnnotation(i).toString(prefix, buffer); buffer.append(' '); } } this.variance.appendPrefix(buffer); buffer.append(this.name); if (this.lowerBound != null) { Formatting.appendSeparator(buffer, "type.bound", ">:"); this.lowerBound.toString(prefix, buffer); } if (this.upperBoundCount > 0) { Formatting.appendSeparator(buffer, "type.bound", "<:"); this.upperBounds[0].toString(prefix, buffer); for (int i = 1; i < this.upperBoundCount; i++) { Formatting.appendSeparator(buffer, "type.bound.separator", '&'); this.upperBounds[i].toString(prefix, buffer); } } } }
package de.matthiasmann.twlthemeeditor.fontgen.gui; import de.matthiasmann.twl.Button; import de.matthiasmann.twl.DialogLayout; import de.matthiasmann.twl.Label; import de.matthiasmann.twl.ValueAdjuster; import de.matthiasmann.twl.Widget; import de.matthiasmann.twl.model.BooleanModel; import de.matthiasmann.twl.utils.CallbackSupport; import de.matthiasmann.twlthemeeditor.fontgen.Effect; import de.matthiasmann.twlthemeeditor.gui.CollapsiblePanel; import de.matthiasmann.twlthemeeditor.gui.PropertyFactories; import java.util.ArrayList; import java.util.Properties; /** * * @author Matthias Mann */ public class EffectsPanel extends DialogLayout { private final DialogLayout.Group hLabels; private final DialogLayout.Group hControls; private final DialogLayout.Group vRows; private final PropertyFactories factories; private final ArrayList<EffectPropertyPanel> effectPanels; private Runnable[] callbacks; public EffectsPanel() { hLabels = createParallelGroup(); hControls = createParallelGroup(); vRows = createSequentialGroup(); factories = new PropertyFactories(); effectPanels = new ArrayList<EffectPropertyPanel>(); setHorizontalGroup(createParallelGroup() .addGroup(createSequentialGroup(hLabels, hControls))); setVerticalGroup(vRows); } public void addEffect(String name, Effect effect) { EffectPropertyPanel epp = new EffectPropertyPanel(factories, name, effect); epp.addCallback(new Runnable() { public void run() { fireCallback(); } }); addCollapsible(name, epp, epp.getEffectActive()); effectPanels.add(epp); } public CollapsiblePanel addCollapsible(String name, Widget content, BooleanModel active) { CollapsiblePanel panel = new CollapsiblePanel(CollapsiblePanel.Direction.VERTICAL, name, content, active); getHorizontalGroup().addWidget(panel); getVerticalGroup().addWidget(panel); return panel; } public CollapsiblePanel addCollapsible(String name, final ValueAdjuster[] adjuster, final BooleanModel active) { DialogLayout l = new DialogLayout(); l.setHorizontalGroup(l.createParallelGroup(adjuster)); l.setVerticalGroup(l.createSequentialGroup().addWidgetsWithGap("adjuster", adjuster)); if(active != null) { active.addCallback(new Runnable() { public void run() { boolean enabled = active.getValue(); for(ValueAdjuster va : adjuster) { va.setEnabled(enabled); } } }); } return addCollapsible(name, l, active); } public void addControl(String labelText, Widget control) { Label label = new Label(labelText); label.setLabelFor(control); hLabels.addWidget(label); hControls.addWidget(control); vRows.addGroup(createParallelGroup().addWidget(label).addWidget(control)); } public void addControl(String labelText, Widget control, Button btn) { Label label = new Label(labelText); label.setLabelFor(control); hLabels.addWidget(label); hControls.addGroup(createSequentialGroup().addWidget(control).addWidget(btn)); vRows.addGroup(createParallelGroup().addWidget(label).addWidget(control).addWidget(btn)); } public void addCallback(Runnable cb) { callbacks = CallbackSupport.addCallbackToList(callbacks, cb, Runnable.class); } public void removeCallback(Runnable cb) { callbacks = CallbackSupport.removeCallbackFromList(callbacks, cb); } void fireCallback() { CallbackSupport.fireCallbacks(callbacks); } public void save(Properties prop) { for(EffectPropertyPanel epp : effectPanels) { epp.save(prop); } } public void load(Properties prop) { for(EffectPropertyPanel epp : effectPanels) { epp.load(prop); } } public Effect[] getActiveEffects() { ArrayList<Effect> result = new ArrayList<Effect>(); for(EffectPropertyPanel epp : effectPanels) { if(epp.getEffectActive().getValue()) { result.add(epp.getEffect()); } } return result.toArray(new Effect[result.size()]); } }
package de.mrapp.android.view.drawable; import android.animation.Animator; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.animation.Animator.AnimatorListener; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.Animatable; import android.graphics.drawable.Drawable; import android.util.Property; import android.view.animation.DecelerateInterpolator; import android.view.animation.LinearInterpolator; import static de.mrapp.android.view.util.Condition.ensureAtLeast; /** * An animated drawable, which is used by the view {@link CircularProgressBar}. * * @author Michael Rapp * * @since 1.0.0 */ public class CircularProgressDrawable extends Drawable implements Animatable { /** * The duration of the angle animation in milliseconds. */ private static final long ANGLE_ANIMATION_DURATION = 2000L; /** * The duration of the sweep animation in milliseconds. */ private static final long SWEEP_ANIMATION_DURATION = 600L; /** * The minimum angle of the sweep animation. */ private static final int MIN_SWEEP_ANGLE = 30; /** * The number of degrees in a circle. */ private static final int MAX_DEGREES = 360; /** * The color of the progress drawable. */ private final int color; /** * The thickness of the progress drawable. */ private final int thickness; /** * The paint, which is used for drawing. */ private Paint paint; /** * The bounds of the drawable. */ private RectF bounds; /** * The sweep animator. */ private ObjectAnimator sweepAnimator; /** * The angle animator. */ private ObjectAnimator angleAnimator; /** * The current angle of the sweep animation. */ private float currentSweepAngle; /** * The current angle of the angle animation. */ private float currentGlobalAngle; /** * The current offset of the angle animation. */ private float currentGlobalAngleOffset; /** * True, if the progress bar is currently animated to be appearing, false. * This value will toggle each time the animation is repeated. */ private boolean appearing; /** * Initializes the paint, which is used for drawing. */ private void initializePaint() { paint = new Paint(); paint.setAntiAlias(true); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(getThickness()); paint.setColor(getColor()); } /** * Initializes the animators. */ private void initializeAnimators() { initializeAngleAnimator(); initializeSweepAnimator(); } /** * Initializes the angle animator. */ private void initializeAngleAnimator() { angleAnimator = ObjectAnimator.ofFloat(this, createAngleProperty(), MAX_DEGREES); angleAnimator.setInterpolator(new LinearInterpolator()); angleAnimator.setDuration(ANGLE_ANIMATION_DURATION); angleAnimator.setRepeatMode(ValueAnimator.RESTART); angleAnimator.setRepeatCount(ValueAnimator.INFINITE); } /** * Creates and returns a property, which allows to animate the global angle * of the progress drawable. * * @return The property, which has been created, as an instance of the class * {@link Property} */ private Property<CircularProgressDrawable, Float> createAngleProperty() { return new Property<CircularProgressDrawable, Float>(Float.class, "angle") { @Override public Float get(final CircularProgressDrawable object) { return currentGlobalAngle; } @Override public void set(final CircularProgressDrawable object, final Float value) { currentGlobalAngle = value; invalidateSelf(); } }; } /** * Initializes the sweep animator. */ private void initializeSweepAnimator() { sweepAnimator = ObjectAnimator.ofFloat(this, createSweepProperty(), MAX_DEGREES - MIN_SWEEP_ANGLE * 2); sweepAnimator.setInterpolator(new DecelerateInterpolator()); sweepAnimator.setDuration(SWEEP_ANIMATION_DURATION); sweepAnimator.setRepeatMode(ValueAnimator.RESTART); sweepAnimator.setRepeatCount(ValueAnimator.INFINITE); sweepAnimator.addListener(createSweepAnimatorListener()); } /** * Creates and returns a property, which allows to animate the sweep angle * of the progress drawable. * * @return The property, which has been created, as an instance of the class * {@link Property} */ private Property<CircularProgressDrawable, Float> createSweepProperty() { return new Property<CircularProgressDrawable, Float>(Float.class, "arc") { @Override public Float get(final CircularProgressDrawable object) { return currentSweepAngle; } @Override public void set(final CircularProgressDrawable object, final Float value) { currentSweepAngle = value; invalidateSelf(); } }; } /** * Creates and returns a listener, which allows to restart the progress * drawable's animation, when it has been finished. * * @return The listener, which has been created, as an instance of the type * {@link AnimatorListener} */ private AnimatorListener createSweepAnimatorListener() { return new AnimatorListener() { @Override public void onAnimationStart(final Animator animation) { } @Override public void onAnimationEnd(final Animator animation) { } @Override public void onAnimationCancel(final Animator animation) { } @Override public void onAnimationRepeat(final Animator animation) { appearing = !appearing; if (appearing) { currentGlobalAngleOffset = (currentGlobalAngleOffset + MIN_SWEEP_ANGLE * 2) % MAX_DEGREES; } } }; } /** * Creates a new animated drawable, which is used by the view * {@link CircularProgressBar}. * * @param color * The color of the progress drawable as an {@link Integer} value * @param thickness * The thickness of the progress drawable as an {@link Integer} * value in pixels */ public CircularProgressDrawable(final int color, final int thickness) { ensureAtLeast(thickness, 1, "The thickness must be at least 1"); this.color = color; this.thickness = thickness; this.bounds = new RectF(); initializePaint(); initializeAnimators(); } /** * Returns the color of the progress drawable. * * @return The color of the progress drawable as an {@link Integer} value */ public final int getColor() { return color; } /** * Returns the thickness of the progress drawable. * * @return The thickness of the progress drawable in pixels as an * {@link Integer} */ public final int getThickness() { return thickness; } @Override public final void setAlpha(final int alpha) { paint.setAlpha(alpha); } @Override public final void setColorFilter(final ColorFilter cf) { paint.setColorFilter(cf); } @Override public final int getOpacity() { return PixelFormat.TRANSPARENT; } @Override public final void draw(final Canvas canvas) { float startAngle = currentGlobalAngle - currentGlobalAngleOffset; float sweepAngle = currentSweepAngle; if (!appearing) { startAngle = startAngle + sweepAngle; sweepAngle = MAX_DEGREES - sweepAngle - MIN_SWEEP_ANGLE; } else { sweepAngle += MIN_SWEEP_ANGLE; } canvas.drawArc(bounds, startAngle, sweepAngle, false, paint); } @Override public final void start() { if (!isRunning()) { angleAnimator.start(); sweepAnimator.start(); invalidateSelf(); } } @Override public final void stop() { if (isRunning()) { angleAnimator.cancel(); sweepAnimator.cancel(); invalidateSelf(); } } @Override public final boolean isRunning() { return angleAnimator.isRunning(); } @Override protected final void onBoundsChange(final Rect bounds) { super.onBoundsChange(bounds); int width = bounds.right - bounds.left; int height = bounds.bottom - bounds.top; if (width < height) { int diff = height - width; this.bounds.left = bounds.left + thickness / 2.0f + 0.5f; this.bounds.right = bounds.right - thickness / 2.0f - 0.5f; this.bounds.top = bounds.top + diff / 2.0f + thickness / 2.0f + 0.5f; this.bounds.bottom = bounds.bottom - diff / 2.0f - thickness / 2.0f - 0.5f; } else { int diff = width - height; this.bounds.left = bounds.left + diff / 2.0f + thickness / 2.0f + 0.5f; this.bounds.right = bounds.right - diff / 2.0f - thickness / 2.0f - 0.5f; this.bounds.top = bounds.top + thickness / 2.0f + 0.5f; this.bounds.bottom = bounds.bottom - thickness / 2.0f - 0.5f; } } }
package dr.app.beauti.generator; import dr.app.beauti.XMLWriter; import dr.app.beauti.components.ComponentFactory; import dr.app.beauti.options.BeautiOptions; import dr.app.beauti.options.PartitionModel; import dr.evolution.util.Taxon; import dr.evolution.util.TaxonList; import dr.evomodel.speciation.SpeciationLikelihood; import dr.evomodel.speciation.SpeciesBindings; import dr.evomodel.speciation.SpeciesTreeBMPrior; import dr.evomodel.speciation.SpeciesTreeModel; import dr.evomodel.speciation.TreePartitionCoalescent; import dr.evomodel.tree.TreeModel; import dr.evomodelxml.BirthDeathModelParser; import dr.evoxml.TaxonParser; import dr.inference.distribution.ExponentialDistributionModel; import dr.inference.model.ParameterParser; import dr.util.Attribute; import dr.xml.AttributeParser; import dr.xml.XMLParser; import java.util.ArrayList; import java.util.List; /** * @author Alexei Drummond * @author Walter Xie */ public class MultiSpeciesCoalescentGenerator extends Generator { public MultiSpeciesCoalescentGenerator(BeautiOptions options, ComponentFactory[] components) { super(options, components); } /** * write tag <sp> * @param taxonList * @param writer */ public void writeMultiSpecies(TaxonList taxonList, XMLWriter writer) { List<String> species = new ArrayList<String>(); // hard code String sp; for (int i = 0; i < taxonList.getTaxonCount(); i++) { Taxon taxon = taxonList.getTaxon(i); sp = taxon.getAttribute(options.TRAIT_SPECIES).toString(); if (!species.contains(sp)) { species.add(sp); } } for (String eachSp : species) { writer.writeOpenTag(SpeciesBindings.SP, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, eachSp)}); for (int i = 0; i < taxonList.getTaxonCount(); i++) { Taxon taxon = taxonList.getTaxon(i); sp = taxon.getAttribute(options.TRAIT_SPECIES).toString(); if (sp.equals(eachSp)) { writer.writeIDref(TaxonParser.TAXON, taxon.getId()); } } writer.writeCloseTag(SpeciesBindings.SP); } writeGeneTrees (writer); } /** * write the species tree, species tree model, likelihood, etc. * @param writer */ public void writeMultiSpeciesCoalescent(XMLWriter writer) { writeSpeciesTree(writer); writeSpeciesTreeModel(writer); writeSpeciesTreeLikelihood(writer); writeGeneUnderSpecies(writer); } private void writeGeneTrees(XMLWriter writer) { writer.writeComment("Collection of Gene Trees"); writer.writeOpenTag(SpeciesBindings.GENE_TREES, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, SpeciesBindings.GENE_TREES)}); // generate gene trees regarding each data partition for (PartitionModel partitionModel : options.getActivePartitionModels()) { writer.writeIDref(TreeModel.TREE_MODEL, partitionModel.getName() + "." + TreeModel.TREE_MODEL); } writer.writeCloseTag(SpeciesBindings.GENE_TREES); } private void writeSpeciesTree(XMLWriter writer) { writer.writeComment("Species Tree: Provides Per branch demographic function"); writer.writeOpenTag(SpeciesTreeModel.SPECIES_TREE, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, SP_TREE), new Attribute.Default<String>(SpeciesTreeModel.BMPRIOR, "true")}); writer.writeIDref(options.TRAIT_SPECIES, options.TRAIT_SPECIES); //TODO: take sppSplitPopulations value from partionModel(?).constant.popSize // hard code get(0) double popSizeValue = options.getParameter("constant.popSize", options.getActivePartitionModels().get(0)).initial; // "initial" is "value" writer.writeOpenTag(SpeciesTreeModel.SPP_SPLIT_POPULATIONS, new Attribute[]{ new Attribute.Default<String>(AttributeParser.VALUE, Double.toString(popSizeValue))}); writer.writeTag(ParameterParser.PARAMETER, new Attribute[]{ new Attribute.Default<String>(XMLParser.ID, SpeciesTreeModel.SPECIES_TREE + "." + SPLIT_POPS)}, true); writer.writeCloseTag(SpeciesTreeModel.SPP_SPLIT_POPULATIONS); writer.writeCloseTag(SpeciesTreeModel.SPECIES_TREE); } private void writeSpeciesTreeModel(XMLWriter writer) { //TODO: let user choose different model. writer.writeComment("Species Tree: Generic Birth Death model"); writer.writeOpenTag(BirthDeathModelParser.BIRTH_DEATH_MODEL, new Attribute[]{ new Attribute.Default<String>(XMLParser.ID, BirthDeathModelParser.BIRTH_DEATH), new Attribute.Default<String>(XMLParser.Utils.UNITS, XMLParser.Utils.SUBSTITUTIONS)}); writer.writeOpenTag(BirthDeathModelParser.BIRTHDIFF_RATE); writer.writeTag(ParameterParser.PARAMETER, new Attribute[]{ new Attribute.Default<String>(XMLParser.ID, BirthDeathModelParser.BIRTHDIFF_RATE_PARAM_NAME), new Attribute.Default<String>(AttributeParser.VALUE, "1"), new Attribute.Default<String>(ParameterParser.LOWER, "0"), new Attribute.Default<String>(ParameterParser.UPPER, "1000000")}, true); writer.writeCloseTag(BirthDeathModelParser.BIRTHDIFF_RATE); writer.writeOpenTag(BirthDeathModelParser.RELATIVE_DEATH_RATE); writer.writeTag(ParameterParser.PARAMETER, new Attribute[]{ new Attribute.Default<String>(XMLParser.ID, BirthDeathModelParser.RELATIVE_DEATH_RATE_PARAM_NAME), new Attribute.Default<String>(AttributeParser.VALUE, "0.5"), new Attribute.Default<String>(ParameterParser.LOWER, "0"), new Attribute.Default<String>(ParameterParser.UPPER, "1")}, true); writer.writeCloseTag(BirthDeathModelParser.RELATIVE_DEATH_RATE); writer.writeCloseTag(BirthDeathModelParser.BIRTH_DEATH_MODEL); } private void writeSpeciesTreeLikelihood(XMLWriter writer) { //TODO: let user choose different model. writer.writeComment("Species Tree: Likelihood of species tree"); writer.writeOpenTag(SpeciationLikelihood.SPECIATION_LIKELIHOOD, new Attribute[]{ new Attribute.Default<String>(XMLParser.ID, SPECIATION_LIKE)}); writer.writeOpenTag(SpeciationLikelihood.MODEL); writer.writeIDref(BirthDeathModelParser.BIRTH_DEATH_MODEL, BirthDeathModelParser.BIRTH_DEATH); writer.writeCloseTag(SpeciationLikelihood.MODEL); writer.writeOpenTag(SpeciesTreeModel.SPECIES_TREE); writer.writeIDref(SpeciesTreeModel.SPECIES_TREE, SP_TREE); writer.writeCloseTag(SpeciesTreeModel.SPECIES_TREE); writer.writeCloseTag(SpeciationLikelihood.SPECIATION_LIKELIHOOD); } private void writeGeneUnderSpecies(XMLWriter writer) { writer.writeComment("Species Tree: Coalescent likelihood for gene trees under species tree"); // speciesCoalescent id="coalescent" writer.writeOpenTag(TreePartitionCoalescent.SPECIES_COALESCENT, new Attribute[]{ new Attribute.Default<String>(XMLParser.ID, COALESCENT)}); writer.writeIDref(options.TRAIT_SPECIES, options.TRAIT_SPECIES); writer.writeIDref(SpeciesTreeModel.SPECIES_TREE, SP_TREE); writer.writeCloseTag(TreePartitionCoalescent.SPECIES_COALESCENT); // exponentialDistributionModel id="pdist" writer.writeOpenTag(ExponentialDistributionModel.EXPONENTIAL_DISTRIBUTION_MODEL, new Attribute[]{ new Attribute.Default<String>(XMLParser.ID, PDIST)}); writer.writeOpenTag(ExponentialDistributionModel.MEAN); writer.writeTag(ParameterParser.PARAMETER, new Attribute[]{ new Attribute.Default<String>(XMLParser.ID, options.POP_MEAN), new Attribute.Default<String>(AttributeParser.VALUE, "0.001")}, true); writer.writeCloseTag(ExponentialDistributionModel.MEAN); writer.writeCloseTag(ExponentialDistributionModel.EXPONENTIAL_DISTRIBUTION_MODEL); // STPopulationPrior id="stp" log_root="true" writer.writeOpenTag(SpeciesTreeBMPrior.STPRIOR, new Attribute[]{ new Attribute.Default<String>(XMLParser.ID, STP), new Attribute.Default<String>(SpeciesTreeBMPrior.LOG_ROOT, "true")}); writer.writeIDref(SpeciesTreeModel.SPECIES_TREE, SP_TREE); writer.writeOpenTag(SpeciesTreeBMPrior.TIPS); writer.writeIDref(ExponentialDistributionModel.EXPONENTIAL_DISTRIBUTION_MODEL, PDIST); writer.writeCloseTag(SpeciesTreeBMPrior.TIPS); writer.writeOpenTag(SpeciesTreeBMPrior.STSIGMA); writer.writeTag(ParameterParser.PARAMETER, new Attribute[]{ // <parameter id="stsigma" value="1" /> new Attribute.Default<String>(XMLParser.ID, SpeciesTreeBMPrior.STSIGMA.toLowerCase()), new Attribute.Default<String>(AttributeParser.VALUE, "1")}, true); writer.writeCloseTag(SpeciesTreeBMPrior.STSIGMA); writer.writeCloseTag(SpeciesTreeBMPrior.STPRIOR); } }
package org.rstudio.core.client.theme; import java.util.ArrayList; import org.rstudio.core.client.Debug; import org.rstudio.core.client.StringUtil; import org.rstudio.core.client.dom.DomUtils; import org.rstudio.core.client.dom.DomUtils.NodePredicate; import org.rstudio.core.client.events.HasTabCloseHandlers; import org.rstudio.core.client.events.HasTabClosedHandlers; import org.rstudio.core.client.events.HasTabClosingHandlers; import org.rstudio.core.client.events.HasTabReorderHandlers; import org.rstudio.core.client.events.TabCloseEvent; import org.rstudio.core.client.events.TabCloseHandler; import org.rstudio.core.client.events.TabClosedEvent; import org.rstudio.core.client.events.TabClosedHandler; import org.rstudio.core.client.events.TabClosingEvent; import org.rstudio.core.client.events.TabClosingHandler; import org.rstudio.core.client.events.TabReorderEvent; import org.rstudio.core.client.events.TabReorderHandler; import org.rstudio.core.client.theme.res.ThemeResources; import org.rstudio.core.client.theme.res.ThemeStyles; import org.rstudio.studio.client.RStudioGinjector; import org.rstudio.studio.client.application.events.EventBus; import org.rstudio.studio.client.workbench.views.source.events.DocTabDragStartedEvent; import org.rstudio.studio.client.workbench.views.source.events.DocWindowChangedEvent; import com.google.gwt.animation.client.Animation; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.RepeatingCommand; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Node; import com.google.gwt.dom.client.Style; import com.google.gwt.dom.client.Style.BorderStyle; import com.google.gwt.dom.client.Style.Display; import com.google.gwt.dom.client.Style.Float; import com.google.gwt.dom.client.Style.Position; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.DragStartEvent; import com.google.gwt.event.dom.client.DragStartHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.EventListener; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HasVerticalAlignment; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.TabLayoutPanel; import com.google.gwt.user.client.ui.Widget; /** * A tab panel that is styled for document tabs. */ public class DocTabLayoutPanel extends TabLayoutPanel implements HasTabClosingHandlers, HasTabCloseHandlers, HasTabClosedHandlers, HasTabReorderHandlers { public interface TabCloseObserver { public void onTabClose(); } public interface TabMoveObserver { public void onTabMove(Widget tab, int oldPos, int newPos); } public DocTabLayoutPanel(boolean closeableTabs, int padding, int rightMargin) { super(BAR_HEIGHT, Style.Unit.PX); closeableTabs_ = closeableTabs; padding_ = padding; rightMargin_ = rightMargin; styles_ = ThemeResources.INSTANCE.themeStyles(); addStyleName(styles_.docTabPanel()); addStyleName(styles_.moduleTabPanel()); dragManager_ = new DragManager(); // listen for global drag events (these are broadcasted from other windows // to notify us of incoming drags) EventBus events = RStudioGinjector.INSTANCE.getEventBus(); events.addHandler(DocTabDragStartedEvent.TYPE, dragManager_); // sink drag-related events on the tab bar element; unfortunately // GWT does not provide bits for the drag-related events, and Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { Element tabBar = getTabBarElement(); DOM.sinkBitlessEvent(tabBar, "drag"); DOM.sinkBitlessEvent(tabBar, "dragstart"); DOM.sinkBitlessEvent(tabBar, "dragenter"); DOM.sinkBitlessEvent(tabBar, "dragover"); DOM.sinkBitlessEvent(tabBar, "dragend"); DOM.sinkBitlessEvent(tabBar, "dragleave"); DOM.sinkBitlessEvent(tabBar, "drop"); Event.setEventListener(tabBar, dragManager_); } }); } @Override public void add(final Widget child, String text) { add(child, null, null, text, null); } public void add(final Widget child, String docId, String text) { add(child, null, docId, text, null); } public void add(final Widget child, ImageResource icon, String docId, final String text, String tooltip) { if (closeableTabs_) { DocTab tab = new DocTab(icon, docId, text, tooltip, new TabCloseObserver() { public void onTabClose() { int index = getWidgetIndex(child); if (index >= 0) { tryCloseTab(index, null); } } }); docTabs_.add(tab); super.add(child, tab); } else { super.add(child, text); } } public boolean tryCloseTab(int index, Command onClosed) { TabClosingEvent event = new TabClosingEvent(index); fireEvent(event); if (event.isCancelled()) return false; closeTab(index, onClosed); return true; } public void closeTab(int index, Command onClosed) { if (remove(index)) { if (onClosed != null) onClosed.execute(); } } @Override public void selectTab(int index) { super.selectTab(index); ensureSelectedTabIsVisible(true); } public void ensureSelectedTabIsVisible(boolean animate) { if (currentAnimation_ != null) { currentAnimation_.cancel(); currentAnimation_ = null; } Element selectedTab = (Element) DomUtils.findNode( getElement(), true, false, new NodePredicate() { public boolean test(Node n) { if (n.getNodeType() != Node.ELEMENT_NODE) return false; return ((Element) n).getClassName() .contains("gwt-TabLayoutPanelTab-selected"); } }); if (selectedTab == null) { return; } selectedTab = selectedTab.getFirstChildElement() .getFirstChildElement(); Element tabBar = getTabBarElement(); if (!isVisible() || !isAttached() || tabBar.getOffsetWidth() == 0) return; // not yet loaded final Element tabBarParent = tabBar.getParentElement(); final int start = tabBarParent.getScrollLeft(); int end = DomUtils.ensureVisibleHoriz(tabBarParent, selectedTab, padding_, padding_ + rightMargin_, true); // When tabs are closed, the overall width shrinks, and this can lead // to cases where there's too much empty space on the screen Node lastTab = getLastChildElement(tabBar); if (lastTab == null || lastTab.getNodeType() != Node.ELEMENT_NODE) return; int edge = DomUtils.getRelativePosition(tabBarParent, Element.as(lastTab)).x + Element.as(lastTab).getOffsetWidth(); end = Math.min(end, Math.max(0, edge - (tabBarParent.getOffsetWidth() - rightMargin_))); if (edge <= tabBarParent.getOffsetWidth() - rightMargin_) end = 0; if (start != end) { if (!animate) { tabBarParent.setScrollLeft(end); } else { final int finalEnd = end; currentAnimation_ = new Animation() { @Override protected void onUpdate(double progress) { double delta = (finalEnd - start) * progress; tabBarParent.setScrollLeft((int) (start + delta)); } @Override protected void onComplete() { if (this == currentAnimation_) { tabBarParent.setScrollLeft(finalEnd); currentAnimation_ = null; } } }; currentAnimation_.run(Math.max(200, Math.min(1500, Math.abs(end - start)*2))); } } } @Override public void onResize() { super.onResize(); ensureSelectedTabIsVisible(false); } @Override public boolean remove(int index) { if ((index < 0) || (index >= getWidgetCount())) { return false; } fireEvent(new TabCloseEvent(index)); if (getSelectedIndex() == index) { boolean closingLastTab = index == getWidgetCount() - 1; int indexToSelect = closingLastTab ? index - 1 : index + 1; if (indexToSelect >= 0) selectTab(indexToSelect); } if (!super.remove(index)) return false; docTabs_.remove(index); fireEvent(new TabClosedEvent(index)); ensureSelectedTabIsVisible(true); return true; } @Override public void add(Widget child, String text, boolean asHtml) { if (asHtml) throw new UnsupportedOperationException("HTML tab names not supported"); add(child, text); } @Override public void add(Widget child, Widget tab) { throw new UnsupportedOperationException("Not supported"); } public void cancelTabDrag() { dragManager_.endDrag(null, true); } private class DragManager implements EventListener, DocTabDragStartedEvent.Handler { @Override public void onBrowserEvent(Event event) { if (event.getType() == "drag") { if (dragging_) drag(event); } else if (event.getType() == "dragstart") { } else if (event.getType() == "dragenter") { if (!dragging_) beginDrag(event); event.preventDefault(); } else if (event.getType() == "dragover") { event.preventDefault(); } else if (event.getType() == "drop") { endDrag(event, false); event.preventDefault(); } else if (event.getType() == "dragend") { if (dragging_) endDrag(event, true); } else if (event.getType() == "dragleave") { if (!dragging_) return; // look at where the cursor is now--if it's inside the tab panel, // do nothing, but if it's outside the tab panel, treat that as // a cancel Element ele = DomUtils.elementFromPoint(event.getClientX(), event.getClientY()); do { Debug.devlog(ele.getClassName()); if (ele.getClassName().contains("gwt-TabLayoutPanelTabs")) { return; } ele = ele.getParentElement(); } while (ele != null && ele != Document.get().getBody()); // cursor moved outside tab panel endDrag(event, true); } } @Override public void onDocTabDragStarted(DocTabDragStartedEvent event) { initDragWidth_ = event.getWidth(); initDragDocId_ = event.getDocId(); } public void beginDrag(Event evt) { String docId = initDragDocId_; int dragTabWidth = initDragWidth_; // set drag element state dragging_ = true; dragTabsHost_ = getTabBarElement(); dragScrollHost_ = dragTabsHost_.getParentElement(); outOfBounds_ = 0; candidatePos_ = null; // figure out which tab the cursor is over so we can use this as the // start position in the drag Element ele = DomUtils.elementFromPoint(evt.getClientX(), evt.getClientY()); do { if (ele.getClassName().contains("gwt-TabLayoutPanelTabs")) { // the cursor is over the tab panel itself--append to end candidatePos_ = docTabs_.size() - 1; break; } else if (ele.getClassName().contains("gwt-TabLayoutPanelTab ")) { // the cursor is inside a tab--figure out which one for (int i = 0; i < dragTabsHost_.getChildCount(); i++) { Node node = dragTabsHost_.getChild(i); if (node.getNodeType() == Node.ELEMENT_NODE && Element.as(node) == ele) { candidatePos_ = i; break; } } break; } ele = ele.getParentElement(); } while (ele != null && ele != Document.get().getBody()); // couldn't figure out where to drop tab if (candidatePos_ == null) return; startPos_ = candidatePos_; // the relative position of the last node determines how far we // can drag--add 10px so it stretches a little dragMax_ = DomUtils.leftRelativeTo(dragTabsHost_, getLastChildElement(dragTabsHost_)) + getLastChildElement(dragTabsHost_).getClientWidth() + 10; lastCursorX_= evt.getClientX(); lastElementX_ = DomUtils.leftRelativeTo( dragTabsHost_, Element.as(dragTabsHost_.getChild(candidatePos_))); // attempt to ascertain whether the element being dragged is one of // our own documents for (DocTab tab: docTabs_) { if (tab.getDocId() == docId) { dragElement_ = tab.getElement().getParentElement().getParentElement(); break; } } // if we're dragging one of our own tabs, snap it out of the // tabset if (dragElement_ != null) { dragElement_.getStyle().setPosition(Position.ABSOLUTE); dragElement_.getStyle().setLeft(lastElementX_, Unit.PX); dragElement_.getStyle().setZIndex(100); Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { dragElement_.getStyle().setDisplay(Display.NONE); } }); } // create the placeholder that shows where this tab will go when the // mouse is released dragPlaceholder_ = Document.get().createDivElement(); dragPlaceholder_.getStyle().setWidth(dragTabWidth, Unit.PX); dragPlaceholder_.getStyle().setHeight(100, Unit.PCT); dragPlaceholder_.getStyle().setDisplay(Display.INLINE_BLOCK); dragPlaceholder_.getStyle().setPosition(Position.RELATIVE); dragPlaceholder_.getStyle().setFloat(Float.LEFT); dragPlaceholder_.getStyle().setBorderStyle(BorderStyle.DOTTED); dragPlaceholder_.getStyle().setBorderColor("#414243"); dragPlaceholder_.getStyle().setBorderWidth(2, Unit.PX); dragPlaceholder_.getStyle().setProperty("boxSizing", "border-box"); dragPlaceholder_.getStyle().setProperty("borderRadius", "3px"); dragPlaceholder_.getStyle().setProperty("borderBottom", "0px"); dragTabsHost_.insertAfter(dragPlaceholder_, dragTabsHost_.getChild(candidatePos_)); } private void drag(Event evt) { int offset = evt.getClientX() - lastCursorX_; lastCursorX_ = evt.getClientX(); // cursor is outside the tab area if (outOfBounds_ != 0) { // did the cursor move back in bounds? if (outOfBounds_ + offset > 0 != outOfBounds_ > 0) { outOfBounds_ = 0; offset = outOfBounds_ + offset; } else { // cursor is still out of bounds outOfBounds_ += offset; return; } } int targetLeft = lastElementX_ + offset; int targetRight = targetLeft + initDragWidth_; int scrollLeft = dragScrollHost_.getScrollLeft(); if (targetLeft < 0) { // dragged past the beginning - lock to beginning targetLeft = 0; outOfBounds_ += offset; } else if (targetLeft > dragMax_) { // dragged past the end - lock to the end targetLeft = dragMax_; outOfBounds_ += offset; } if (targetLeft - scrollLeft < SCROLL_THRESHOLD && scrollLeft > 0) { // dragged past scroll threshold, to the left--autoscroll outOfBounds_ = (targetLeft - scrollLeft) - SCROLL_THRESHOLD; targetLeft = scrollLeft + SCROLL_THRESHOLD; Scheduler.get().scheduleFixedPeriod(new RepeatingCommand() { @Override public boolean execute() { return autoScroll(-1); } }, 5); } else if (targetRight + SCROLL_THRESHOLD > scrollLeft + dragScrollHost_.getClientWidth() && scrollLeft < dragScrollHost_.getScrollWidth() - dragScrollHost_.getClientWidth()) { // dragged past scroll threshold, to the right--autoscroll outOfBounds_ = (targetRight + SCROLL_THRESHOLD) - (scrollLeft + dragScrollHost_.getClientWidth()); targetLeft = scrollLeft + dragScrollHost_.getClientWidth() - (initDragWidth_ + SCROLL_THRESHOLD); Scheduler.get().scheduleFixedPeriod(new RepeatingCommand() { @Override public boolean execute() { return autoScroll(1); } }, 5); } commitPosition(targetLeft); } private void commitPosition(int pos) { lastElementX_ = pos; // check to see if we're overlapping with another tab for (int i = 0; i < dragTabsHost_.getChildCount(); i++) { // skip non-element DOM nodes Node node = dragTabsHost_.getChild(i); if (node.getNodeType() != Node.ELEMENT_NODE) { continue; } // skip the element we're dragging and elements that are not tabs Element ele = (Element)node; if (ele == dragElement_ || ele.getClassName().indexOf("gwt-TabLayoutPanelTab") < 0) { continue; } int left = DomUtils.leftRelativeTo(dragTabsHost_, ele); int right = left + ele.getClientWidth(); int minOverlap = Math.min(initDragWidth_ / 2, ele.getClientWidth() / 2); // a little complicated: compute the number of overlapping pixels // with this element; if the overlap is more than half of our width // (or the width of the candidate), it's swapping time if (Math.min(lastElementX_ + initDragWidth_, right) - Math.max(lastElementX_, left) >= minOverlap) { dragTabsHost_.removeChild(dragPlaceholder_); if (candidatePos_ > i) { dragTabsHost_.insertBefore(dragPlaceholder_, ele); } else { dragTabsHost_.insertAfter(dragPlaceholder_, ele); } candidatePos_ = i; Debug.devlog(lastElementX_ + " - " + candidatePos_); // account for the extra element when moving to the right of the // original location destPos_ = startPos_ <= candidatePos_ ? candidatePos_ - 1 : candidatePos_; } } } private boolean autoScroll(int dir) { // move while the mouse is still out of bounds if (dragging_ && outOfBounds_ != 0) { // if mouse is far out of bounds, use it to accelerate movement if (Math.abs(outOfBounds_) > 100) { dir *= 1 + Math.round(Math.abs(outOfBounds_) / 75); } // move if there's moving to be done if (dir < 0 && lastElementX_ > 0 || dir > 0 && lastElementX_ < dragMax_) { commitPosition(lastElementX_ + dir); // scroll if there's scrolling to be done int left = dragScrollHost_.getScrollLeft(); if ((dir < 0 && left > 0) || (dir > 0 && left < dragScrollHost_.getScrollWidth() - dragScrollHost_.getClientWidth())) { dragScrollHost_.setScrollLeft(left + dir); } } return true; } return false; } public void endDrag(final Event evt, boolean cancel) { if (!dragging_) return; // remove the properties used to position for dragging if (dragElement_ != null) { dragElement_.getStyle().clearLeft(); dragElement_.getStyle().clearPosition(); dragElement_.getStyle().clearZIndex(); dragElement_.getStyle().clearDisplay(); // insert this tab where the placeholder landed if we're not // cancelling if (!cancel) { dragTabsHost_.removeChild(dragElement_); dragTabsHost_.insertAfter(dragElement_, dragPlaceholder_); } } if (dragPlaceholder_ != null) { dragTabsHost_.removeChild(dragPlaceholder_); dragPlaceholder_ = null; } // finish dragging DOM.releaseCapture(getElement()); dragging_ = false; if (dragElement_ != null && !cancel) { // unsink mousedown/mouseup and simulate a click to activate the tab if (evt != null) simulateClick(evt); // let observer know we moved; adjust the destination position one to // the left if we're right of the start position to account for the // position of the tab prior to movement if (startPos_ != destPos_) { TabReorderEvent event = new TabReorderEvent(startPos_, destPos_); fireEvent(event); } } // this is the case when we adopt someone else's doc if (dragElement_ == null && evt != null && !cancel) { // pull the document ID and source window out String data = evt.getDataTransfer().getData("text"); if (StringUtil.isNullOrEmpty(data)) return; // the data format is docID|windowID; windowID can be omitted if // the main window is the origin String pieces[] = data.split("\\|"); if (pieces.length < 1) return; RStudioGinjector.INSTANCE.getEventBus().fireEvent(new DocWindowChangedEvent(pieces[0], pieces.length > 1 ? pieces[1] : "", destPos_)); } dragElement_ = null; } private void simulateClick(Event evt) { /* DomEvent.fireNativeEvent(Document.get().createClickEvent(0, evt.getScreenX(), evt.getScreenY(), evt.getClientX(), evt.getClientY(), evt.getCtrlKey(), evt.getAltKey(), evt.getShiftKey(), evt.getMetaKey()), this.getParent()); */ } private boolean dragging_ = false; private int lastCursorX_ = 0; private int lastElementX_ = 0; private int startPos_ = 0; private Integer candidatePos_ = null; private int destPos_ = 0; private int dragMax_ = 0; private int outOfBounds_ = 0; private int initDragWidth_; private Element dragElement_; private Element dragTabsHost_; private Element dragScrollHost_; private Element dragPlaceholder_; private final static int SCROLL_THRESHOLD = 25; private String initDragDocId_; } private class DocTab extends Composite { private DocTab(ImageResource icon, String docId, String title, String tooltip, TabCloseObserver closeHandler) { docId_ = docId; final HorizontalPanel layoutPanel = new HorizontalPanel(); layoutPanel.setStylePrimaryName(styles_.tabLayout()); layoutPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_BOTTOM); layoutPanel.getElement().setDraggable("true"); layoutPanel.addDomHandler(new DragStartHandler() { @Override public void onDragStart(DragStartEvent evt) { evt.getDataTransfer().setData("text", docId_ + "|" + RStudioGinjector.INSTANCE.getSourceWindowManager() .getSourceWindowId()); RStudioGinjector.INSTANCE.getEventBus().fireEvent(new DocTabDragStartedEvent(docId_, getElement().getClientWidth())); } }, DragStartEvent.getType()); HTML left = new HTML(); left.setStylePrimaryName(styles_.tabLayoutLeft()); layoutPanel.add(left); contentPanel_ = new HorizontalPanel(); contentPanel_.setTitle(tooltip); contentPanel_.setStylePrimaryName(styles_.tabLayoutCenter()); contentPanel_.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE); if (icon != null) contentPanel_.add(imageForIcon(icon)); label_ = new Label(title, false); label_.addStyleName(styles_.docTabLabel()); contentPanel_.add(label_); appendDirtyMarker(); Image img = new Image(ThemeResources.INSTANCE.closeTab()); img.setStylePrimaryName(styles_.closeTabButton()); img.addStyleName(ThemeStyles.INSTANCE.handCursor()); contentPanel_.add(img); layoutPanel.add(contentPanel_); HTML right = new HTML(); right.setStylePrimaryName(styles_.tabLayoutRight()); layoutPanel.add(right); initWidget(layoutPanel); this.sinkEvents(Event.ONMOUSEMOVE | Event.ONMOUSEUP | Event.ONLOSECAPTURE); closeHandler_ = closeHandler; closeElement_ = img.getElement(); } private void appendDirtyMarker() { Label marker = new Label("*"); marker.setStyleName(styles_.dirtyTabIndicator()); contentPanel_.insert(marker, 2); } public void replaceTitle(String title) { label_.setText(title); } public void replaceTooltip(String tooltip) { contentPanel_.setTitle(tooltip); } public void replaceIcon(ImageResource icon) { if (contentPanel_.getWidget(0) instanceof Image) contentPanel_.remove(0); contentPanel_.insert(imageForIcon(icon), 0); } public String getDocId() { return docId_; } private Image imageForIcon(ImageResource icon) { Image image = new Image(icon); image.setStylePrimaryName(styles_.docTabIcon()); return image; } @Override public void onBrowserEvent(Event event) { switch(DOM.eventGetType(event)) { case Event.ONMOUSEUP: { // middlemouse should close a tab if (event.getButton() == Event.BUTTON_MIDDLE) { event.stopPropagation(); event.preventDefault(); closeHandler_.onTabClose(); break; } // note: fallthrough } case Event.ONLOSECAPTURE: { if (Element.as(event.getEventTarget()) == closeElement_) { // handle click on close button closeHandler_.onTabClose(); } event.preventDefault(); event.stopPropagation(); break; } } super.onBrowserEvent(event); } private TabCloseObserver closeHandler_; private Element closeElement_; private final Label label_; private final String docId_; private final HorizontalPanel contentPanel_; } public void replaceDocName(int index, ImageResource icon, String title, String tooltip) { DocTab tab = (DocTab) getTabWidget(index); tab.replaceIcon(icon); tab.replaceTitle(title); tab.replaceTooltip(tooltip); } public HandlerRegistration addTabClosingHandler(TabClosingHandler handler) { return addHandler(handler, TabClosingEvent.TYPE); } @Override public HandlerRegistration addTabCloseHandler( TabCloseHandler handler) { return addHandler(handler, TabCloseEvent.TYPE); } public HandlerRegistration addTabClosedHandler(TabClosedHandler handler) { return addHandler(handler, TabClosedEvent.TYPE); } @Override public HandlerRegistration addTabReorderHandler(TabReorderHandler handler) { return addHandler(handler, TabReorderEvent.TYPE); } public int getTabsEffectiveWidth() { if (getWidgetCount() == 0) return 0; Element parent = getTabBarElement(); if (parent == null) { return 0; } Element lastChild = getLastChildElement(parent); if (lastChild == null) { return 0; } return lastChild.getOffsetLeft() + lastChild.getOffsetWidth(); } @Override public void onBrowserEvent(Event event) { super.onBrowserEvent(event); } private Element getTabBarElement() { return (Element) DomUtils.findNode( getElement(), true, false, new NodePredicate() { public boolean test(Node n) { if (n.getNodeType() != Node.ELEMENT_NODE) return false; return ((Element) n).getClassName() .contains("gwt-TabLayoutPanelTabs"); } }); } private Element getLastChildElement(Element parent) { Node lastTab = parent.getLastChild(); while (lastTab.getNodeType() != Node.ELEMENT_NODE) { lastTab = lastTab.getPreviousSibling(); } return Element.as(lastTab); } public static final int BAR_HEIGHT = 24; private final boolean closeableTabs_; private int padding_; private int rightMargin_; private final ThemeStyles styles_; private Animation currentAnimation_; private DragManager dragManager_; private ArrayList<DocTab> docTabs_ = new ArrayList<DocTab>(); }
package org.dellroad.stuff.vaadin; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.concurrent.atomic.AtomicLong; import javax.servlet.ServletContext; import org.springframework.beans.factory.annotation.AnnotationBeanWiringInfoResolver; import org.springframework.beans.factory.wiring.BeanConfigurerSupport; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.event.SourceFilteringListener; import org.springframework.web.context.ConfigurableWebApplicationContext; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.context.support.XmlWebApplicationContext; @SuppressWarnings("serial") public abstract class SpringContextApplication extends ContextApplication { private static final AtomicLong UNIQUE_INDEX = new AtomicLong(); private transient ConfigurableWebApplicationContext context; /** * Get this instance's associated Spring application context. */ public ConfigurableWebApplicationContext getApplicationContext() { return this.context; } /** * Configure a bean using this instance's associated application context. * Intended for use by aspects. */ protected void configureBean(Object bean) { BeanConfigurerSupport beanConfigurerSupport = new BeanConfigurerSupport(); beanConfigurerSupport.setBeanFactory(this.context.getBeanFactory()); beanConfigurerSupport.setBeanWiringInfoResolver(new AnnotationBeanWiringInfoResolver()); beanConfigurerSupport.afterPropertiesSet(); beanConfigurerSupport.configureBean(bean); beanConfigurerSupport.destroy(); } public static SpringContextApplication get() { return ContextApplication.get(SpringContextApplication.class); } /** * Initializes the associated {@link ConfigurableWebApplicationContext}. */ protected final void initApplication() { // Load the context this.loadContext(); // Initialize subclass this.initSpringApplication(context); } /** * Initialize the application. Sub-classes of {@link SpringContextApplication} must implement this method. * * @param context the associated {@link WebApplicationContext} just created and refreshed */ protected abstract void initSpringApplication(ConfigurableWebApplicationContext context); /** * Post-process the given {@link WebApplicationContext} after initial creation but before the initial * {@link org.springframework.context.ConfigurableApplicationContext#refresh refresh()}. * * <p> * The implementation in {@link SpringContextApplication} does nothing. Subclasses may override as necessary. * </p> * * @param context the associated {@link WebApplicationContext} just refreshed * @see #onRefresh * @see ConfigurableWebApplicationContext#refresh() */ protected void postProcessWebApplicationContext(ConfigurableWebApplicationContext context) { } /** * Perform any application-specific work after a successful application context refresh. * * <p> * The implementation in {@link SpringContextApplication} does nothing. Subclasses may override as necessary. * </p> * * @param context the associated {@link WebApplicationContext} just refreshed * @see #postProcessWebApplicationContext * @see org.springframework.context.ConfigurableApplicationContext#refresh */ protected void onRefresh(ApplicationContext context) { } /** * Get the name for this application. This is used as the name of the XML file in {@code WEB-INF/} that * defines the Spring application context associated with this instance. * * <p> * The implementation in {@link SpringContextApplication} returns this instance's class' * {@linkplain Class#getSimpleName simple name}. * </p> */ protected String getApplicationName() { return this.getClass().getSimpleName(); } // ApplicationContext setup private void loadContext() { // Logging this.log.info("loading application context for Vaadin application " + this.getApplicationName()); // Sanity check if (this.context != null) throw new IllegalStateException("context already loaded"); // Find the application context associated with the servlet; it will be the parent ServletContext servletContext = ContextApplication.currentRequest().getServletContext(); WebApplicationContext parent = WebApplicationContextUtils.getWebApplicationContext(servletContext); // Create and configure a new application context for this Application instance this.context = new XmlWebApplicationContext(); this.context.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + servletContext.getContextPath() + "/" + this.getApplicationName() + "-" + SpringContextApplication.UNIQUE_INDEX.incrementAndGet()); this.context.setParent(parent); this.context.setServletContext(servletContext); //context.setServletConfig(??); this.context.setNamespace(this.getApplicationName()); // Register listener so we can notify subclass on refresh events this.context.addApplicationListener(new SourceFilteringListener(this.context, new RefreshListener())); // Invoke any subclass setup this.postProcessWebApplicationContext(context); // Refresh context this.context.refresh(); // Get notified of application shutdown so we can shut down the context as well this.addListener(new ContextCloseListener()); } // Serialization private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { input.defaultReadObject(); this.loadContext(); } // Nested classes // My refresh listener private class RefreshListener implements ApplicationListener<ContextRefreshedEvent>, Serializable { @Override public void onApplicationEvent(ContextRefreshedEvent event) { SpringContextApplication.this.onRefresh(event.getApplicationContext()); } } // My close listener private class ContextCloseListener implements CloseListener, Serializable { @Override public void applicationClosed(CloseEvent closeEvent) { SpringContextApplication.this.log.info("closing application context associated with Vaadin application " + SpringContextApplication.this.getApplicationName()); SpringContextApplication.this.context.close(); } } }
package hudson.util; import com.thoughtworks.xstream.converters.Converter; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.converters.collections.AbstractCollectionConverter; import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import com.thoughtworks.xstream.mapper.Mapper; import hudson.model.AbstractProject; import hudson.model.DependecyDeclarer; import hudson.model.DependencyGraph; import hudson.model.Describable; import hudson.model.Descriptor; import hudson.model.Descriptor.FormException; import hudson.model.Saveable; import net.sf.json.JSONObject; import org.kohsuke.stapler.StaplerRequest; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Persisted list of {@link Describable}s with some operations specific * to {@link Descriptor}s. * * <p> * This class allows multiple instances of the same descriptor. Some clients * use this semantics, while other clients use it as "up to one instance per * one descriptor" model. * * Some of the methods defined in this class only makes sense in the latter model, * such as {@link #remove(Descriptor)}. * * @author Kohsuke Kawaguchi */ public class DescribableList<T extends Describable<T>, D extends Descriptor<T>> implements Iterable<T> { private final CopyOnWriteList<T> data = new CopyOnWriteList<T>(); private Saveable owner; private DescribableList() { } /** * @deprecated * Use {@link #DescribableList(Saveable)} */ public DescribableList(Owner owner) { setOwner(owner); } public DescribableList(Saveable owner) { setOwner(owner); } /** * @deprecated * Use {@link #setOwner(Saveable)} */ public void setOwner(Owner owner) { this.owner = owner; } public void setOwner(Saveable owner) { this.owner = owner; } public void add(T item) throws IOException { data.add(item); onModified(); } public T get(D descriptor) { for (T t : data) if(t.getDescriptor()==descriptor) return t; return null; } public boolean contains(D d) { return get(d)!=null; } public void remove(D descriptor) throws IOException { for (T t : data) { if(t.getDescriptor()==descriptor) { data.remove(t); onModified(); return; } } } public Iterator<T> iterator() { return data.iterator(); } /** * Called when a list is mutated. */ protected void onModified() throws IOException { owner.save(); } @SuppressWarnings("unchecked") public Map<D,T> toMap() { return (Map)Descriptor.toMap(data); } /** * Returns the snapshot view of instances as list. */ public List<T> toList() { return data.getView(); } /** * Gets all the {@link Describable}s in an array. */ public T[] toArray(T[] array) { return data.toArray(array); } public void addAllTo(Collection<? super T> dst) { data.addAllTo(dst); } /** * Rebuilds the list by creating a fresh instances from the submitted form. * * <p> * This method is almost always used by the owner. * This method does not invoke the save method. * * @param json * Structured form data that includes the data for nested descriptor list. */ public void rebuild(StaplerRequest req, JSONObject json, List<? extends Descriptor<T>> descriptors) throws FormException { List<T> newList = new ArrayList<T>(); for (Descriptor<T> d : descriptors) { String name = d.getJsonSafeClassName(); if (json.has(name)) { T instance = d.newInstance(req, json.getJSONObject(name)); newList.add(instance); } } data.replaceBy(newList); } /** * @deprecated as of 1.271 * Use {@link #rebuild(StaplerRequest, JSONObject, List)} instead. */ public void rebuild(StaplerRequest req, JSONObject json, List<? extends Descriptor<T>> descriptors, String prefix) throws FormException { rebuild(req,json,descriptors); } /** * Rebuilds the list by creating a fresh instances from the submitted form. * * <p> * This version works with the the &lt;f:hetero-list> UI tag, where the user * is allowed to create multiple instances of the same descriptor. Order is also * significant. */ public void rebuildHetero(StaplerRequest req, JSONObject formData, Collection<Descriptor<T>> descriptors, String key) throws FormException { data.replaceBy(Descriptor.newInstancesFromHeteroList(req,formData,key,descriptors)); } /** * Picks up {@link DependecyDeclarer}s and allow it to build dependencies. */ public void buildDependencyGraph(AbstractProject owner,DependencyGraph graph) { for (Object o : this) { if (o instanceof DependecyDeclarer) { DependecyDeclarer dd = (DependecyDeclarer) o; dd.buildDependencyGraph(owner,graph); } } } /** * @deprecated * Just implement {@link Saveable}. */ public interface Owner extends Saveable { } /** * {@link Converter} implementation for XStream. * * Serializaion form is compatible with plain {@link List}. */ public static class ConverterImpl extends AbstractCollectionConverter { CopyOnWriteList.ConverterImpl copyOnWriteListConverter; public ConverterImpl(Mapper mapper) { super(mapper); copyOnWriteListConverter = new CopyOnWriteList.ConverterImpl(mapper()); } public boolean canConvert(Class type) { // handle subtypes in case the onModified method is overridden. return DescribableList.class.isAssignableFrom(type); } public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) { for (Object o : (DescribableList) source) writeItem(o, context, writer); } public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { CopyOnWriteList core = copyOnWriteListConverter.unmarshal(reader, context); DescribableList r = new DescribableList(); r.data.replaceBy(core); return r; } } }
package org.jivesoftware.messenger.container; import org.jivesoftware.messenger.JiveGlobals; import org.jivesoftware.util.Log; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletException; import javax.servlet.ServletConfig; import javax.servlet.ServletOutputStream; import java.io.*; import java.util.Map; import java.util.List; import java.util.HashMap; import java.util.Arrays; import java.util.concurrent.ConcurrentHashMap; * the form <tt>/plugins/[pluginName]/images/*.png|gif</tt> (e.g. * <tt>/plugins/foo/images/example.gif</tt>).<p> * * JSP files must be compiled and available via the plugin's class loader. The mapping * between JSP name and servlet class files is defined in [pluginName]/web/web.xml. * Typically, this file is auto-generated by the JSP compiler when packaging the plugin. * * @author Matt Tucker */ public class PluginServlet extends HttpServlet { private static Map<String,HttpServlet> servlets; private static File pluginDirectory; private static ServletConfig servletConfig; public void init(ServletConfig config) throws ServletException { super.init(config); servletConfig = config; servlets = new ConcurrentHashMap<String,HttpServlet>(); pluginDirectory = new File(JiveGlobals.getMessengerHome(), "plugins"); } public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pathInfo = request.getPathInfo(); if (pathInfo == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } else { // Handle JSP requests. if (pathInfo.endsWith(".jsp")) { handleJSP(pathInfo, request, response); return; } // Handle image requests. else if (pathInfo.endsWith(".gif") || pathInfo.endsWith(".png")) { handleImage(pathInfo, response); return; } // Anything else results in a 404. else { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } } } public static void registerServlets(Plugin plugin, File webXML) { if (!webXML.exists()) { Log.error("Could not register plugin servlets, file " + webXML.getAbsolutePath() + " does not exist."); return; } // Find the name of the plugin directory given that the webXML file // lives in plugins/[pluginName]/web/web.xml String pluginName = webXML.getParentFile().getParent(); try { SAXReader saxReader = new SAXReader(); Document doc = saxReader.read(webXML); // Find all <servlet> entries to discover name to class mapping. List classes = doc.selectNodes("//servlet"); Map<String,Class> classMap = new HashMap<String,Class>(); for (int i=0; i<classes.size(); i++) { Element servletElement = (Element)classes.get(i); String name = servletElement.element("servlet-name").getTextTrim(); String className = servletElement.element("servlet-class").getTextTrim(); classMap.put(name, plugin.getClass().getClassLoader().loadClass(className)); } // Find all <servelt-mapping> entries to discover name to URL mapping. List names = doc.selectNodes("//servlet-mapping"); for (int i=0; i<names.size(); i++) { Element nameElement = (Element)names.get(i); String name = nameElement.element("servlet-name").getTextTrim(); String url = nameElement.element("url-pattern").getTextTrim(); // Register the servlet for the URL. Class servletClass = classMap.get(name); Object instance = servletClass.newInstance(); if (instance instanceof HttpServlet) { // Initialize the servlet then add it to the map.. ((HttpServlet)instance).init(servletConfig); servlets.put(pluginName + url, (HttpServlet)instance); } else { Log.warn("Could not load " + (pluginName + url) + ": not a servlet."); } } } catch (Throwable e) { e.printStackTrace(); } } /** * Handles a request for a JSP page. It checks to see if a servlet is mapped * for the JSP URL. If one is found, request handling is passed to it. If no * servlet is found, a 404 error is returned. * * @param pathInfo the extra path info. * @param request the request object. * @param response the response object. * @throws ServletException if a servlet exception occurs while handling the * request. * @throws IOException if an IOException occurs while handling the request. */ private void handleJSP(String pathInfo, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Strip the starting "/" from the path to find the JSP URL. String jspURL = pathInfo.substring(1); HttpServlet servlet = servlets.get(jspURL); if (servlet != null) { servlet.service(request, response); return; } else { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } } /** * Handles a request for an image. * * @param pathInfo the extra path info. * @param response the response object. * @throws IOException if an IOException occurs while handling the request. */ private void handleImage(String pathInfo, HttpServletResponse response) throws IOException { String [] parts = pathInfo.split("/"); // Image request must be in correct format. if (parts.length != 4) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } File image = new File(pluginDirectory, parts[1] + File.separator + "web" + File.separator + "images" + File.separator + parts[3]); if (!image.exists()) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } else { // Content type will be GIF or PNG. String contentType = "image/gif"; if (pathInfo.endsWith(".png")) { contentType = "image/png"; } response.setHeader("Content-disposition", "filename=\"" + image + "\";"); response.setContentType(contentType); // Write out the image to the user. InputStream in = null; ServletOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(image)); out = response.getOutputStream(); // Set the size of the file. response.setContentLength((int)image.length()); // Use a 1K buffer. byte[] buf = new byte[1024]; int len; while ((len=in.read(buf)) != -1) { out.write(buf, 0, len); } } finally { try { in.close(); } catch (Exception ignored) {} try { out.close(); } catch (Exception ignored) {} } } } }
package jenkins.util.io; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import hudson.Functions; import hudson.Util; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import javax.annotation.Nonnull; import java.io.IOException; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.attribute.PosixFileAttributes; import java.nio.file.attribute.PosixFilePermission; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; @Restricted(NoExternalUse.class) public class PathRemover { public static PathRemover newSimpleRemover() { return new PathRemover(ignored -> false); } public static PathRemover newRemoverWithStrategy(@Nonnull RetryStrategy retryStrategy) { return new PathRemover(retryStrategy); } public static PathRemover newRobustRemover(int maxRetries, boolean gcAfterFailedRemove, long waitBetweenRetries) { return new PathRemover(new PausingGCRetryStrategy(maxRetries < 1 ? 1 : maxRetries, gcAfterFailedRemove, waitBetweenRetries)); } private final RetryStrategy retryStrategy; private PathRemover(@Nonnull RetryStrategy retryStrategy) { this.retryStrategy = retryStrategy; } public void forceRemoveFile(@Nonnull Path path) throws IOException { for (int retryAttempts = 0; ; retryAttempts++) { Optional<IOException> maybeError = tryRemoveFile(path); if (!maybeError.isPresent()) return; if (retryStrategy.shouldRetry(retryAttempts)) continue; IOException error = maybeError.get(); throw new IOException(retryStrategy.failureMessage(path, retryAttempts), error); } } public void forceRemoveDirectoryContents(@Nonnull Path path) throws IOException { for (int retryAttempt = 0; ; retryAttempt++) { List<IOException> errors = tryRemoveDirectoryContents(path); if (errors.isEmpty()) return; if (retryStrategy.shouldRetry(retryAttempt)) continue; throw new CompositeIOException(retryStrategy.failureMessage(path, retryAttempt), errors); } } public void forceRemoveRecursive(@Nonnull Path path) throws IOException { for (int retryAttempt = 0; ; retryAttempt++) { List<IOException> errors = tryRemoveRecursive(path); if (errors.isEmpty()) return; if (retryStrategy.shouldRetry(retryAttempt)) continue; throw new CompositeIOException(retryStrategy.failureMessage(path, retryAttempt), errors); } } @Restricted(NoExternalUse.class) @FunctionalInterface public interface RetryStrategy { boolean shouldRetry(int retriesAttempted); default String failureMessage(@Nonnull Path fileToRemove, int retryCount) { StringBuilder sb = new StringBuilder() .append("Unable to delete '") .append(fileToRemove) .append("'. Tried ") .append(retryCount) .append(" time"); if (retryCount != 1) sb.append('s'); sb.append('.'); return sb.toString(); } } private static class PausingGCRetryStrategy implements RetryStrategy { private final int maxRetries; private final boolean gcAfterFailedRemove; private final long waitBetweenRetries; private final ThreadLocal<Boolean> interrupted = ThreadLocal.withInitial(() -> false); private PausingGCRetryStrategy(int maxRetries, boolean gcAfterFailedRemove, long waitBetweenRetries) { this.maxRetries = maxRetries; this.gcAfterFailedRemove = gcAfterFailedRemove; this.waitBetweenRetries = waitBetweenRetries; } @SuppressFBWarnings(value = "DM_GC", justification = "Garbage collection happens only when " + "GC_AFTER_FAILED_DELETE is true. It's an experimental feature in Jenkins.") private void gcIfEnabled() { /* If the Jenkins process had the file open earlier, and it has not * closed it then Windows won't let us delete it until the Java object * with the open stream is Garbage Collected, which can result in builds * failing due to "file in use" on Windows despite working perfectly * well on other OSs. */ if (gcAfterFailedRemove) System.gc(); } @Override public boolean shouldRetry(int retriesAttempted) { if (retriesAttempted >= maxRetries) return false; gcIfEnabled(); long delayMillis = waitBetweenRetries >= 0 ? waitBetweenRetries : -(retriesAttempted + 1) * waitBetweenRetries; if (delayMillis <= 0) return !Thread.interrupted(); try { Thread.sleep(delayMillis); return true; } catch (InterruptedException e) { interrupted.set(true); return false; } } @Override public String failureMessage(@Nonnull Path fileToRemove, int retryCount) { StringBuilder sb = new StringBuilder(); sb.append("Unable to delete '"); sb.append(fileToRemove); sb.append("'. Tried "); sb.append(retryCount + 1); sb.append(" time"); if (retryCount != 1) sb.append('s'); if (maxRetries > 0) { sb.append(" (of a maximum of "); sb.append(maxRetries + 1); sb.append(')'); if (gcAfterFailedRemove) sb.append(" garbage-collecting"); if (waitBetweenRetries != 0 && gcAfterFailedRemove) sb.append(" and"); if (waitBetweenRetries != 0) { sb.append(" waiting "); sb.append(Util.getTimeSpanString(Math.abs(waitBetweenRetries))); if (waitBetweenRetries < 0) { sb.append("-"); sb.append(Util.getTimeSpanString(Math.abs(waitBetweenRetries) * (maxRetries + 1))); } } if (waitBetweenRetries != 0 || gcAfterFailedRemove) sb.append(" between attempts"); } if (interrupted.get()) sb.append(". The delete operation was interrupted before it completed successfully"); sb.append('.'); interrupted.set(false); return sb.toString(); } } private static Optional<IOException> tryRemoveFile(@Nonnull Path path) { try { removeOrMakeRemovableThenRemove(path); return Optional.empty(); } catch (IOException e) { return Optional.of(e); } } private static List<IOException> tryRemoveRecursive(@Nonnull Path path) { List<IOException> accumulatedErrors = Files.isSymbolicLink(path) ? new ArrayList<>() : tryRemoveDirectoryContents(path); tryRemoveFile(path).ifPresent(accumulatedErrors::add); return accumulatedErrors; } private static List<IOException> tryRemoveDirectoryContents(@Nonnull Path path) { if (!Files.isDirectory(path)) return Collections.emptyList(); List<IOException> accumulatedErrors = new ArrayList<>(); try (DirectoryStream<Path> children = Files.newDirectoryStream(path)) { for (Path child : children) { accumulatedErrors.addAll(tryRemoveRecursive(child)); } } catch (IOException e) { accumulatedErrors.add(e); } return accumulatedErrors; } private static void removeOrMakeRemovableThenRemove(@Nonnull Path path) throws IOException { try { Files.deleteIfExists(path); } catch (IOException e) { makeRemovable(path); try { Files.deleteIfExists(path); } catch (IOException e2) { // I suspect other processes putting files in this directory if (Files.isDirectory(path)) { List<String> entries; try (Stream<Path> children = Files.list(path)) { entries = children.map(Path::toString).collect(Collectors.toList()); } throw new CompositeIOException("Unable to remove directory " + path + " with directory contents: " + entries, e, e2); } } } } private static void makeRemovable(@Nonnull Path path) throws IOException { if (!Files.isWritable(path)) { makeWritable(path); } Path parent = path.getParent(); if (parent != null && !Files.isWritable(parent)) { makeWritable(parent); } } private static void makeWritable(@Nonnull Path path) throws IOException { if (!Functions.isWindows()) { try { PosixFileAttributes attrs = Files.readAttributes(path, PosixFileAttributes.class); Set<PosixFilePermission> newPermissions = attrs.permissions(); newPermissions.add(PosixFilePermission.OWNER_WRITE); Files.setPosixFilePermissions(path, newPermissions); } catch (NoSuchFileException ignored) { return; } catch (UnsupportedOperationException ignored) { // PosixFileAttributes not supported, fall back to old IO. } } /* * We intentionally do not check the return code of setWritable, because if it * is false we prefer to rethrow the exception thrown by Files.deleteIfExists, * which will have a more useful message than something we make up here. */ path.toFile().setWritable(true); } }
package org.helioviewer.gl3d.model.image; import java.awt.Component; import java.awt.Point; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.ArrayList; import javax.media.opengl.GL2; import org.helioviewer.base.Pair; import org.helioviewer.base.math.Vector2dDouble; import org.helioviewer.base.physics.Constants; import org.helioviewer.gl3d.camera.GL3DCamera; import org.helioviewer.gl3d.math.GL3DMat4d; import org.helioviewer.gl3d.math.GL3DQuatd; import org.helioviewer.gl3d.math.GL3DVec3d; import org.helioviewer.gl3d.scenegraph.GL3DState; import org.helioviewer.jhv.display.Displayer; import org.helioviewer.jhv.gui.ImageViewerGui; import org.helioviewer.jhv.plugin.renderable.Renderable; import org.helioviewer.jhv.plugin.renderable.RenderableType; import org.helioviewer.jhv.renderable.RenderableImageType; import org.helioviewer.viewmodel.imagedata.ImageData; import org.helioviewer.viewmodel.metadata.HelioviewerMetaData; import org.helioviewer.viewmodel.metadata.MetaData; import org.helioviewer.viewmodel.region.Region; import org.helioviewer.viewmodel.region.StaticRegion; import org.helioviewer.viewmodel.view.jp2view.JHVJP2View; import org.helioviewer.viewmodel.view.opengl.GLInfo; import org.helioviewer.viewmodel.view.opengl.shader.GLSLShader; import org.helioviewer.viewmodel.viewport.StaticViewport; import org.helioviewer.viewmodel.viewport.Viewport; import org.helioviewer.viewmodel.viewport.ViewportAdapter; import com.jogamp.common.nio.Buffers; /** * This is the scene graph equivalent of an image layer sub view chain attached * to the GL3DLayeredView. It represents exactly one image layer in the view * chain * * @author Simon Spoerri (simon.spoerri@fhnw.ch) * */ public class GL3DImageLayer implements Renderable { private static int nextLayerId = 0; private final int layerId; public int getLayerId() { return layerId; } public double minZ = -Constants.SunRadius; public double maxZ = Constants.SunRadius; private final int resolution = 6; private final double[][] pointlist = new double[(resolution + 1) * 2 * 2][2]; private final boolean showSphere; private boolean showCorona; private int positionBufferID; private int indexBufferID; private int indexBufferSize; private int positionBufferSize; private final JHVJP2View mainLayerView; private final RenderableType type; private boolean isVisible = true; public GL3DImageLayer(String name, JHVJP2View mainLayerView, boolean showSphere, boolean showCorona, boolean restoreColorMask) { this.type = new RenderableImageType(mainLayerView.getName()); layerId = nextLayerId++; this.mainLayerView = mainLayerView; int count = 0; for (int i = 0; i <= this.resolution; i++) { for (int j = 0; j <= 1; j++) { this.pointlist[count][0] = 1. * i / this.resolution; this.pointlist[count][1] = j; count++; } } for (int i = 0; i <= 1; i++) { for (int j = 0; j <= this.resolution; j++) { this.pointlist[count][0] = i / 1.; this.pointlist[count][1] = 1. * j / this.resolution; count++; } } this.showSphere = showSphere; this.showCorona = showCorona; Displayer.getRenderablecontainer().addBeforeRenderable(this); } @Override public void init(GL3DState state) { Pair<FloatBuffer, IntBuffer> bufferPair = this.makeIcosphere(3); FloatBuffer positionBuffer = bufferPair.a; IntBuffer indexBuffer = bufferPair.b; this.positionBufferSize = positionBuffer.capacity(); positionBufferID = generate(state); state.gl.glBindBuffer(GL2.GL_ARRAY_BUFFER, positionBufferID); state.gl.glBufferData(GL2.GL_ARRAY_BUFFER, this.positionBufferSize * Buffers.SIZEOF_FLOAT, positionBuffer, GL2.GL_STATIC_DRAW); indexBufferID = generate(state); indexBufferSize = indexBuffer.capacity(); state.gl.glBindBuffer(GL2.GL_ELEMENT_ARRAY_BUFFER, indexBufferID); state.gl.glBufferData(GL2.GL_ELEMENT_ARRAY_BUFFER, indexBuffer.capacity() * Buffers.SIZEOF_INT, indexBuffer, GL2.GL_STATIC_DRAW); state.getActiveCamera().updateCameraTransformation(); } private void updateROI(GL3DState state) { MetaData metaData = getMainLayerView().getMetaData(); GL3DCamera activeCamera = state.getActiveCamera(); if (metaData == null || activeCamera == null) { return; } int width = state.getViewportWidth(); int height = state.getViewportHeight(); double minPhysicalX = Double.MAX_VALUE; double minPhysicalY = Double.MAX_VALUE; double maxPhysicalX = -Double.MAX_VALUE; double maxPhysicalY = -Double.MAX_VALUE; GL3DMat4d camdiff = this.getCameraDifferenceRotation(activeCamera, this.getMainLayerView().getImageData()); for (int i = 0; i < pointlist.length; i++) { GL3DVec3d hitPoint; hitPoint = activeCamera.getVectorFromSphereOrPlane(new Point((int) (pointlist[i][0] * width), (int) (pointlist[i][1] * height)), camdiff); if (hitPoint != null) { minPhysicalX = Math.min(minPhysicalX, hitPoint.x); minPhysicalY = Math.min(minPhysicalY, hitPoint.y); maxPhysicalX = Math.max(maxPhysicalX, hitPoint.x); maxPhysicalY = Math.max(maxPhysicalY, hitPoint.y); } } double widthxAdd = Math.abs((maxPhysicalX - minPhysicalX) * 0.0); double widthyAdd = Math.abs((maxPhysicalY - minPhysicalY) * 0.0); minPhysicalX = minPhysicalX - widthxAdd; maxPhysicalX = maxPhysicalX + widthxAdd; minPhysicalY = minPhysicalY - widthyAdd; maxPhysicalY = maxPhysicalY + widthyAdd; double metLLX = metaData.getPhysicalLowerLeft().getX(); double metLLY = metaData.getPhysicalLowerLeft().getY(); double metURX = metaData.getPhysicalUpperRight().getX(); double metURY = metaData.getPhysicalUpperRight().getY(); if (minPhysicalX < metLLX) minPhysicalX = metLLX; if (minPhysicalY < metLLY) minPhysicalY = metLLY; if (maxPhysicalX > metURX) maxPhysicalX = metURX; if (maxPhysicalY > metURY) maxPhysicalY = metURY; double regionWidth = maxPhysicalX - minPhysicalX; double regionHeight = maxPhysicalY - minPhysicalY; Region newRegion; if (regionWidth > 0 && regionHeight > 0) { newRegion = StaticRegion.createAdaptedRegion(minPhysicalX, -(minPhysicalY + regionHeight), regionWidth, regionHeight); } else { newRegion = StaticRegion.createAdaptedRegion(metLLX, metLLY, metURX - metLLX, metURY - metLLY); } this.getMainLayerView().setRegion(newRegion, null); Viewport layerViewport = new ViewportAdapter(new StaticViewport(state.getViewportWidth(), state.getViewportHeight())); this.getMainLayerView().setViewport(layerViewport, null); } public GL3DMat4d getCameraDifferenceRotation(GL3DCamera camera, ImageData imageData) { if (imageData == null) return GL3DMat4d.identity(); HelioviewerMetaData md = (HelioviewerMetaData) (imageData.getMETADATA()); double phi = md.getPhi(); double theta = md.getTheta(); GL3DQuatd layerLocalRotation = GL3DQuatd.createRotation(theta, GL3DVec3d.XAxis); layerLocalRotation.rotate(GL3DQuatd.createRotation(phi, GL3DVec3d.YAxis)); GL3DMat4d cameraDifferenceRotation = camera.getCurrentDragRotation().toMatrix().multiply(camera.getLocalRotation().toMatrix()).multiply(layerLocalRotation.toMatrix().transpose()); return cameraDifferenceRotation; } @Override public void render(GL3DState state) { if (!this.isVisible) return; GL2 gl = state.gl; gl.glEnable(GL2.GL_BLEND); gl.glBlendFunc(GL2.GL_SRC_ALPHA, GL2.GL_ONE_MINUS_SRC_ALPHA); GLSLShader.bind(gl); { gl.glEnable(GL2.GL_CULL_FACE); { gl.glCullFace(GL2.GL_BACK); gl.glEnable(GL2.GL_BLEND); JHVJP2View jp2view = this.getMainLayerView(); if (jp2view != null) { jp2view.applyFilters(gl); } GLSLShader.setViewport(GLInfo.pixelScale[0] * state.getViewportWidth(), GLInfo.pixelScale[1] * state.getViewportHeight()); GLSLShader.filter(gl); GL3DCamera camera = state.getActiveCamera(); GL3DMat4d vpmi = camera.orthoMatrixInverse.copy(); vpmi.translate(new GL3DVec3d(-camera.getTranslation().x, -camera.getTranslation().y, 0.)); GLSLShader.bindMatrix(gl, vpmi.getFloatArray(), "cameraTransformationInverse"); GLSLShader.bindMatrix(gl, camera.getLocalRotation().toMatrix().getFloatArray(), "layerLocalRotation"); GLSLShader.bindMatrix(gl, getCameraDifferenceRotation(camera, this.mainLayerView.getImageData()).getFloatArray(), "cameraDifferenceRotation"); if (this.mainLayerView.getBaseDifferenceMode()) { GLSLShader.bindMatrix(gl, getCameraDifferenceRotation(camera, this.mainLayerView.getBaseDifferenceImageData()).getFloatArray(), "diffcameraDifferenceRotation"); } else { GLSLShader.bindMatrix(gl, getCameraDifferenceRotation(camera, this.mainLayerView.getPreviousImageData()).getFloatArray(), "diffcameraDifferenceRotation"); } Vector2dDouble ll = jp2view.getMetaData().getPhysicalLowerLeft(); ll.getX(); ll.getY(); enablePositionVBO(state); enableIndexVBO(state); { gl.glVertexPointer(3, GL2.GL_FLOAT, 3 * Buffers.SIZEOF_FLOAT, 0); if (this.showCorona) { gl.glDepthRange(1.f, 1.f); gl.glDrawElements(GL2.GL_TRIANGLES, 6, GL2.GL_UNSIGNED_INT, (this.indexBufferSize - 6) * Buffers.SIZEOF_INT); gl.glDepthRange(0.f, 1.f); } if (this.showSphere) { gl.glDrawElements(GL2.GL_TRIANGLES, this.indexBufferSize - 6, GL2.GL_UNSIGNED_INT, 0); } } disableIndexVBO(state); disablePositionVBO(state); GLSLShader.unbind(gl); gl.glColorMask(true, true, true, true); } gl.glDisable(GL2.GL_CULL_FACE); } GLSLShader.unbind(gl); gl.glDisable(GL2.GL_TEXTURE_2D); gl.glDisable(GL2.GL_BLEND); updateROI(state); } private int generate(GL3DState state) { int[] tmpId = new int[1]; state.gl.glGenBuffers(1, tmpId, 0); return tmpId[0]; } private void enableIndexVBO(GL3DState state) { state.gl.glBindBuffer(GL2.GL_ELEMENT_ARRAY_BUFFER, indexBufferID); } private void disableIndexVBO(GL3DState state) { state.gl.glBindBuffer(GL2.GL_ELEMENT_ARRAY_BUFFER, 0); } private void enablePositionVBO(GL3DState state) { state.gl.glEnableClientState(GL2.GL_VERTEX_ARRAY); state.gl.glBindBuffer(GL2.GL_ARRAY_BUFFER, positionBufferID); } private void disablePositionVBO(GL3DState state) { state.gl.glDisableClientState(GL2.GL_VERTEX_ARRAY); state.gl.glBindBuffer(GL2.GL_ARRAY_BUFFER, 0); } private void deletePositionVBO(GL3DState state) { state.gl.glDeleteBuffers(1, new int[] { this.positionBufferID }, 0); } private void deleteIndexVBO(GL3DState state) { state.gl.glDeleteBuffers(1, new int[] { this.indexBufferID }, 0); } @Override public void remove(GL3DState state) { disablePositionVBO(state); disableIndexVBO(state); deletePositionVBO(state); deleteIndexVBO(state); Displayer.getLayersModel().removeLayer(getMainLayerView()); } private Pair<FloatBuffer, IntBuffer> makeIcosphere(int level) { float t = (float) ((Math.sqrt(5) - 1) / 2); float[][] icosahedronVertexList = new float[][] { new float[] { -1, -t, 0 }, new float[] { 0, 1, t }, new float[] { 0, 1, -t }, new float[] { 1, t, 0 }, new float[] { 1, -t, 0 }, new float[] { 0, -1, -t }, new float[] { 0, -1, t }, new float[] { t, 0, 1 }, new float[] { -t, 0, 1 }, new float[] { t, 0, -1 }, new float[] { -t, 0, -1 }, new float[] { -1, t, 0 }, }; for (float[] v : icosahedronVertexList) { float length = (float) Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); v[0] /= length; v[1] /= length; v[2] /= length; } int[][] icosahedronFaceList = new int[][] { { 3, 7, 1 }, { 4, 7, 3 }, { 6, 7, 4 }, { 8, 7, 6 }, { 7, 8, 1 }, { 9, 4, 3 }, { 2, 9, 3 }, { 2, 3, 1 }, { 11, 2, 1 }, { 10, 2, 11 }, { 10, 9, 2 }, { 9, 5, 4 }, { 6, 4, 5 }, { 0, 6, 5 }, { 0, 11, 8 }, { 11, 1, 8 }, { 10, 0, 5 }, { 10, 5, 9 }, { 0, 8, 6 }, { 0, 10, 11 }, }; ArrayList<Float> vertices = new ArrayList<Float>(); ArrayList<Integer> faceIndices = new ArrayList<Integer>(); for (float[] v : icosahedronVertexList) { vertices.add(v[0]); vertices.add(v[2]); vertices.add(v[1]); } for (int[] f : icosahedronFaceList) { subdivide(f[0], f[1], f[2], vertices, faceIndices, level); } int beginPositionNumberCorona = vertices.size() / 3; vertices.add(-40f); vertices.add(40f); vertices.add(0f); vertices.add(40f); vertices.add(40f); vertices.add(0f); vertices.add(40f); vertices.add(-40f); vertices.add(0f); vertices.add(-40f); vertices.add(-40f); vertices.add(0f); faceIndices.add(beginPositionNumberCorona + 0); faceIndices.add(beginPositionNumberCorona + 2); faceIndices.add(beginPositionNumberCorona + 1); faceIndices.add(beginPositionNumberCorona + 2); faceIndices.add(beginPositionNumberCorona + 0); faceIndices.add(beginPositionNumberCorona + 3); FloatBuffer positionBuffer = FloatBuffer.allocate(vertices.size()); for (Float vert : vertices) { positionBuffer.put(vert); } positionBuffer.flip(); IntBuffer indexBuffer = IntBuffer.allocate(faceIndices.size()); for (int i : faceIndices) { indexBuffer.put(i); } indexBuffer.flip(); return new Pair<FloatBuffer, IntBuffer>(positionBuffer, indexBuffer); } private void subdivide(int vx, int vy, int vz, ArrayList<Float> vertexList, ArrayList<Integer> faceList, int level) { if (level != 0) { float x1 = (vertexList.get(3 * vx) + vertexList.get(3 * vy)); float y1 = (vertexList.get(3 * vx + 1) + vertexList.get(3 * vy + 1)); float z1 = (vertexList.get(3 * vx + 2) + vertexList.get(3 * vy + 2)); float length = (float) Math.sqrt(x1 * x1 + y1 * y1 + z1 * z1); x1 /= length; y1 /= length; z1 /= length; int firstIndex = vertexList.size() / 3; vertexList.add(x1); vertexList.add(y1); vertexList.add(z1); float x2 = (vertexList.get(3 * vz) + vertexList.get(3 * vy)); float y2 = (vertexList.get(3 * vz + 1) + vertexList.get(3 * vy + 1)); float z2 = (vertexList.get(3 * vz + 2) + vertexList.get(3 * vy + 2)); length = (float) Math.sqrt(x2 * x2 + y2 * y2 + z2 * z2); x2 /= length; y2 /= length; z2 /= length; int secondIndex = vertexList.size() / 3; vertexList.add(x2); vertexList.add(y2); vertexList.add(z2); float x3 = (vertexList.get(3 * vx) + vertexList.get(3 * vz)); float y3 = (vertexList.get(3 * vx + 1) + vertexList.get(3 * vz + 1)); float z3 = (vertexList.get(3 * vx + 2) + vertexList.get(3 * vz + 2)); length = (float) Math.sqrt(x3 * x3 + y3 * y3 + z3 * z3); x3 /= length; y3 /= length; z3 /= length; int thirdIndex = vertexList.size() / 3; vertexList.add(x3); vertexList.add(y3); vertexList.add(z3); subdivide(vx, firstIndex, thirdIndex, vertexList, faceList, level - 1); subdivide(firstIndex, vy, secondIndex, vertexList, faceList, level - 1); subdivide(thirdIndex, secondIndex, vz, vertexList, faceList, level - 1); subdivide(firstIndex, secondIndex, thirdIndex, vertexList, faceList, level - 1); } else { faceList.add(vx); faceList.add(vy); faceList.add(vz); } } public void setCoronaVisibility(boolean visible) { this.showCorona = visible; } @Override public RenderableType getType() { return this.type; } @Override public Component getOptionsPanel() { ImageViewerGui ivg = ImageViewerGui.getSingletonInstance(); ivg.getFilterTabPanelManager().setActivejp2(getMainLayerView()); return ivg.getFilterPanelContainer(); } @Override public boolean isVisible() { return isVisible; } @Override public void setVisible(boolean isVisible) { this.isVisible = isVisible; } @Override public String getName() { return getMainLayerView().getName(); } @Override public String getTimeString() { return getMainLayerView().getMetaData().getDateTime().getCachedDate(); } public JHVJP2View getMainLayerView() { return mainLayerView; } }
package jp.gr.java_conf.neko_daisuki.anaudioplayer; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.database.Cursor; import android.media.MediaMetadataRetriever; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.Messenger; import android.os.RemoteException; import android.provider.MediaStore; import android.util.Log; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.animation.Interpolator; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.ViewFlipper; import jp.gr.java_conf.neko_daisuki.android.widget.RotatingUzumakiSlider; import jp.gr.java_conf.neko_daisuki.android.widget.UzumakiHead; import jp.gr.java_conf.neko_daisuki.android.widget.UzumakiSlider; public class MainActivity extends Activity { private static class ActivityHolder { protected MainActivity activity; public ActivityHolder(MainActivity activity) { this.activity = activity; } } private abstract class Adapter extends ArrayAdapter<String> { protected LayoutInflater inflater; protected MainActivity activity; public Adapter(MainActivity activity, List<String> objects) { super(activity, 0, objects); this.initialize(activity); } public Adapter(MainActivity activity, String[] objects) { super(activity, 0, objects); this.initialize(activity); } @Override public View getView(int position, View convertView, ViewGroup parent) { return convertView == null ? this.getView(position, this.makeConvertView(parent), parent) : this.makeView(position, convertView); } protected abstract View makeConvertView(ViewGroup parent); protected abstract View makeView(int position, View convertView); private void initialize(MainActivity activity) { this.activity = activity; String service = Context.LAYOUT_INFLATER_SERVICE; this.inflater = (LayoutInflater)activity.getSystemService(service); } } private class FileAdapter extends Adapter { private class Row { public ImageView playingIcon; public TextView name; } public FileAdapter(MainActivity activity, String[] objects) { super(activity, objects); } protected View makeView(int position, View convertView) { Row row = (Row)convertView.getTag(); String name = this.getItem(position); String selectedFile = this.activity.getSelectedFile(); int src = name != selectedFile ? R.drawable.ic_blank : R.drawable.ic_playing; row.playingIcon.setImageResource(src); row.name.setText(name); return convertView; } protected View makeConvertView(ViewGroup parent) { View view = this.inflater.inflate(R.layout.file_row, parent, false); Row row = new Row(); row.playingIcon = (ImageView)view.findViewById(R.id.playing_icon); row.name = (TextView)view.findViewById(R.id.name); view.setTag(row); return view; } } private class DirectoryAdapter extends Adapter { private class Row { public ImageView playingIcon; public TextView path; } public DirectoryAdapter(MainActivity activity, List<String> objects) { super(activity, objects); } protected View makeView(int position, View convertView) { Row row = (Row)convertView.getTag(); String path = this.getItem(position); int src = path != this.activity.selectedDir ? R.drawable.ic_blank : R.drawable.ic_playing; row.playingIcon.setImageResource(src); row.path.setText(path); return convertView; } protected View makeConvertView(ViewGroup parent) { View view = this.inflater.inflate(R.layout.dir_row, parent, false); Row row = new Row(); row.playingIcon = (ImageView)view.findViewById(R.id.playing_icon); row.path = (TextView)view.findViewById(R.id.path); view.setTag(row); return view; } } private class PlayProcedureOnConnected extends ActivityHolder implements Runnable { public PlayProcedureOnConnected(MainActivity activity) { super(activity); } public void run() { this.activity.sendPlay(); this.activity.startTimer(); } } private class ResumeProcedureOnConnected extends ActivityHolder implements Runnable { public ResumeProcedureOnConnected(MainActivity activity) { super(activity); } public void run() { this.activity.startTimer(); } } private interface ServiceUnbinder { public void unbind(); } private class TrueServiceUnbinder extends ActivityHolder implements ServiceUnbinder { public TrueServiceUnbinder(MainActivity activity) { super(activity); } public void unbind() { this.activity.unbindService(this.activity.connection); } } private class FakeServiceUnbinder implements ServiceUnbinder { public void unbind() { } } private interface ServiceStarter { public void start(); } private class TrueServiceStarter extends ActivityHolder implements ServiceStarter { public TrueServiceStarter(MainActivity activity) { super(activity); } public void start() { Intent intent = new Intent(this.activity, AudioService.class); this.activity.startService(intent); } } private class FakeServiceStarter implements ServiceStarter { public void start() { } } private interface ServiceStopper { public void stop(); } private class TrueServiceStopper extends ActivityHolder implements ServiceStopper { public TrueServiceStopper(MainActivity activity) { super(activity); } public void stop() { this.activity.unbindAudioService(); Intent intent = new Intent(this.activity, AudioService.class); this.activity.stopService(intent); } } private class FakeServiceStopper implements ServiceStopper { public void stop() { } } private class Connection extends ActivityHolder implements ServiceConnection { private Runnable procedureOnConnected; public Connection(MainActivity activity, Runnable procedureOnConnected) { super(activity); this.procedureOnConnected = procedureOnConnected; } public void onServiceConnected(ComponentName className, IBinder service) { this.activity.outgoingMessenger = new Messenger(service); this.procedureOnConnected.run(); Log.i(LOG_TAG, "MainActivity conneted to AudioService."); } public void onServiceDisconnected(ComponentName className) { Log.i(LOG_TAG, "MainActivity disconnected from AudioService."); } } private class Mp3Comparator implements Comparator<String> { private String dir; public Mp3Comparator(String dir) { this.dir = dir; } public int compare(String name1, String name2) { String path1 = this.dir + File.separator + name1; String path2 = this.dir + File.separator + name2; int trackNo1 = this.extractTrackNumber(path1); int trackNo2 = this.extractTrackNumber(path2); return trackNo1 != trackNo2 ? trackNo1 - trackNo2 : path1.compareTo(path2); } private int extractTrackNumber(String path) { MediaMetadataRetriever meta = new MediaMetadataRetriever(); meta.setDataSource(path); int key = MediaMetadataRetriever.METADATA_KEY_CD_TRACK_NUMBER; String datum = meta.extractMetadata(key); return datum != null ? this.getTrackNumber(datum) : 0; } private int getTrackNumber(String datum) { // Track number is stored in format of "Num/Total". int pos = datum.indexOf('/'); String s = pos < 0 ? datum : datum.substring(0, pos); try { return Integer.parseInt(s); } catch (NumberFormatException e) { e.printStackTrace(); } return 0; } } private class OnStartRotatingListener extends ActivityHolder implements RotatingUzumakiSlider.OnStartRotatingListener { public OnStartRotatingListener(MainActivity activity) { super(activity); } public void onStartRotating(RotatingUzumakiSlider slider) { this.activity.onStartSliding(); } } private class OnStopRotatingListener extends ActivityHolder implements RotatingUzumakiSlider.OnStopRotatingListener { public OnStopRotatingListener(MainActivity activity) { super(activity); } public void onStopRotating(RotatingUzumakiSlider slider) { this.activity.procAfterSeeking.run(); } } private class PlayAfterSeeking extends ActivityHolder implements Runnable { public PlayAfterSeeking(MainActivity activity) { super(activity); } public void run() { this.activity.startTimer(); this.activity.sendPlay(); } } private class StayAfterSeeking implements Runnable { public void run() { } } private class SliderLogger implements UzumakiSlider.Logger { private MainActivity activity; public SliderLogger(MainActivity activity) { this.activity = activity; } public void log(String msg) { this.activity.log(msg); } } private class OnStartHeadMovingListener implements UzumakiSlider.OnStartHeadMovingListener { private MainActivity activity; public OnStartHeadMovingListener(MainActivity activity) { this.activity = activity; } public void onStartHeadMoving(UzumakiSlider slider, UzumakiHead head) { this.activity.onStartSliding(); } } private class OnStopHeadMovingListener extends ActivityHolder implements UzumakiSlider.OnStopHeadMovingListener { public OnStopHeadMovingListener(MainActivity activity) { super(activity); } public void onStopHeadMoving(UzumakiSlider slider, UzumakiHead head) { this.activity.procAfterSeeking.run(); } } private abstract class MenuDispatcher { protected MainActivity activity; public MenuDispatcher(MainActivity activity) { this.activity = activity; } public boolean dispatch() { this.callback(); return true; } protected abstract void callback(); } private class AboutDispatcher extends MenuDispatcher { public AboutDispatcher(MainActivity activity) { super(activity); } protected void callback() { this.activity.showAbout(); } } private static class IncomingHandler extends Handler { private abstract class MessageHandler extends ActivityHolder { public MessageHandler(MainActivity activity) { super(activity); } public abstract void handle(Message msg); } private class WhatTimeHandler extends MessageHandler { public WhatTimeHandler(MainActivity activity) { super(activity); } public void handle(Message msg) { this.activity.updateCurrentTime(msg.arg1); } } private SparseArray<MessageHandler> handlers; public IncomingHandler(MainActivity activity) { this.handlers = new SparseArray<MessageHandler>(); this.handlers.put(AudioService.MSG_WHAT_TIME, new WhatTimeHandler(activity)); } @Override public void handleMessage(Message msg) { this.handlers.get(msg.what).handle(msg); } } private static class DatabaseTask extends AsyncTask<Void, Void, List<String>> { private MainActivity activity; public DatabaseTask(MainActivity activity) { super(); this.activity = activity; } @Override protected void onPostExecute(List<String> directories) { this.activity.showDirectories(directories); } @Override protected List<String> doInBackground(Void... voids) { Log.i(LOG_TAG, "DatabaseTask started."); List<String> files = this.selectFiles(this.queryFiles()); List<String> directories = this.listDirectories(files); Log.i(LOG_TAG, "DatabaseTask ended."); return directories; } private List<String> listDirectories(List<String> files) { Set<String> set = new HashSet<String>(); for (String path: files) { File file = new File(path); set.add(file.getParent()); } List<String> directories = new ArrayList<String>(); for (String path: set) { directories.add(path); } return directories; } private void addExistingFile(List<String> l, String path) { File file = new File(path); if (!file.exists()) { return; } l.add(path); } private List<String> selectFiles(List<String> files) { List<String> list = new ArrayList<String>(); for (String path: files) { /* * TODO: The content provider includes non-mp3 files. They must * be dropped. */ this.addExistingFile(list, path); } return list; } private List<String> queryFiles() { List<String> l = new ArrayList<String>(); String[] cols = { MediaStore.MediaColumns.DATA }; Cursor c = this.activity.getContentResolver().query( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, cols, null, // selection null, // selection arguments null); // order try { int index = c.getColumnIndex(MediaStore.MediaColumns.DATA); while (c.moveToNext()) { l.add(c.getString(index)); } } finally { c.close(); } return l; } } public static final String LOG_TAG = "anaudioplayer"; private static final int NO_FILES_SELECTED = -1; private ViewFlipper flipper; /* * pageIndex is needed for save/restore instance state. I tried some ways * to get current page index on runtime, but I did not find the way useful * in any cases. Counting manually is easiest. */ private int pageIndex; private ListView dirList; private ImageButton nextButton0; private View prevButton1; private ListView fileList; private ImageButton nextButton1; private View prevButton2; private ImageButton playButton; private RotatingUzumakiSlider slider; private TextView title; private TextView currentTime; private TextView totalTime; private File mediaDir; private List<String> dirs = null; private String selectedDir = null; private String[] files = new String[0]; private int filePosition = NO_FILES_SELECTED; private Animation leftInAnimation; private Animation leftOutAnimation; private Animation rightInAnimation; private Animation rightOutAnimation; private View.OnClickListener pauseListener; private View.OnClickListener playListener; private TimerInterface timer; private FakeTimer fakeTimer; private Runnable procAfterSeeking; private SparseArray<MenuDispatcher> menuDispatchers = new SparseArray<MenuDispatcher>(); private ServiceStarter serviceStarter; private ServiceStopper serviceStopper; private ServiceUnbinder serviceUnbinder; private ServiceConnection connection; private Messenger outgoingMessenger; private Messenger incomingMessenger; @Override public void onStart() { super.onStart(); new DatabaseTask(this).execute(); } @Override public Object onRetainNonConfigurationInstance() { return this.connection; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.main); this.mediaDir = Environment.getExternalStorageDirectory(); this.findViews(); this.initializeFlipButtonListener(); this.initializeDirList(); this.initializeFileList(); this.initializeAnimation(); this.initializePlayButton(); this.initializeTimer(); this.initializeSlider(); this.initializeMenu(); this.pageIndex = 0; this.incomingMessenger = new Messenger(new IncomingHandler(this)); Log.i(LOG_TAG, "Created."); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.action_bar, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { MenuDispatcher dispatcher = this.menuDispatchers.get(item.getItemId()); return dispatcher != null ? dispatcher.dispatch() : super.onOptionsItemSelected(item); } private void showAbout() { Intent i = new Intent(this, AboutActivity.class); this.startActivity(i); } private void initializeMenu() { this.menuDispatchers.put(R.id.about, new AboutDispatcher(this)); } private void initializeSlider() { this.slider.addOnStartHeadMovingListener(new OnStartHeadMovingListener(this)); this.slider.addOnStopHeadMovingListener(new OnStopHeadMovingListener(this)); this.slider.addOnStartRotatingListener(new OnStartRotatingListener(this)); this.slider.addOnStopRotatingListener(new OnStopRotatingListener(this)); this.slider.setLogger(new SliderLogger(this)); } private void initializeTimer() { this.timer = this.fakeTimer = new FakeTimer(); } private void findViews() { this.flipper = (ViewFlipper)this.findViewById(R.id.flipper); this.dirList = (ListView)this.findViewById(R.id.dir_list); this.nextButton0 = (ImageButton)this.findViewById(R.id.next0); this.prevButton1 = (View)this.findViewById(R.id.prev1); this.fileList = (ListView)this.findViewById(R.id.file_list); this.nextButton1 = (ImageButton)this.findViewById(R.id.next1); this.prevButton2 = (View)this.findViewById(R.id.prev2); this.playButton = (ImageButton)this.findViewById(R.id.play); this.slider = (RotatingUzumakiSlider)this.findViewById(R.id.slider); this.title = (TextView)this.findViewById(R.id.title); this.currentTime = (TextView)this.findViewById(R.id.current_time); this.totalTime = (TextView)this.findViewById(R.id.total_time); } private void initializePlayButton() { this.pauseListener = new PauseButtonListener(this); this.playButton.setOnClickListener(this.pauseListener); this.playListener = new PlayButtonListener(this); } private class PauseButtonListener extends ActivityHolder implements View.OnClickListener { public PauseButtonListener(MainActivity activity) { super(activity); } @Override public void onClick(View view) { this.activity.procAfterSeeking = new StayAfterSeeking(); this.activity.pause(); } } private class PlayButtonListener extends ActivityHolder implements View.OnClickListener { public PlayButtonListener(MainActivity activity) { super(activity); } @Override public void onClick(View view) { this.activity.procAfterSeeking = new PlayAfterSeeking(this.activity); this.activity.play(); } } private static final long ANIMATION_DURATION = 250; //private static final int INTERPOLATOR = android.R.anim.decelerate_interpolator; private static final int INTERPOLATOR = android.R.anim.linear_interpolator; private Animation loadAnimation(int id, Interpolator interp) { Animation anim = AnimationUtils.loadAnimation(this, id); anim.setDuration(ANIMATION_DURATION); anim.setInterpolator(interp); return anim; } private void initializeAnimation() { Interpolator interp = AnimationUtils.loadInterpolator(this, INTERPOLATOR); this.leftInAnimation = this.loadAnimation(R.anim.anim_left_in, interp); this.leftOutAnimation = this.loadAnimation(R.anim.anim_left_out, interp); this.rightInAnimation = this.loadAnimation(R.anim.anim_right_in, interp); this.rightOutAnimation = this.loadAnimation(R.anim.anim_right_out, interp); } private void initializeDirList() { /* List<String> dirs = this.listMp3Dir(this.mediaDir); Collections.sort(dirs); this.showDirectories(dirs); */ this.dirList.setOnItemClickListener(new DirectoryListListener(this)); } private void showDirectories(List<String> dirs) { this.dirs = dirs; this.dirList.setAdapter(new DirectoryAdapter(this, dirs)); } private File[] listFiles(File dir, FilenameFilter filter) { File[] files; try { files = dir.listFiles(filter); } catch (SecurityException _) { files = null; } return files != null ? files : (new File[0]); } private List<String> listMp3Dir(File dir) { List<String> list = new ArrayList<String>(); for (File d: this.listFiles(dir, new DirectoryFilter())) { list.addAll(this.listMp3Dir(d)); } if (0 < this.listFiles(dir, new Mp3Filter()).length) { try { list.add(dir.getCanonicalPath()); } catch (IOException _) { } } return list; } private class Mp3Filter implements FilenameFilter { public boolean accept(File dir, String name) { return name.endsWith(".mp3"); } } private class DirectoryFilter implements FilenameFilter { public boolean accept(File dir, String name) { String path; try { path = dir.getCanonicalPath() + File.separator + name; } catch (IOException _) { return false; } return (new File(path)).isDirectory(); } } private void initializeFlipButtonListener() { ImageButton[] nextButtons = { this.nextButton0, this.nextButton1 }; this.setClickListener(nextButtons, new NextButtonListener(this)); for (ImageButton button: nextButtons) { this.enableButton(button, false); } View[] previousButtons = { this.prevButton1, this.prevButton2 }; this.setClickListener(previousButtons, new PreviousButtonListener(this)); } private void selectDir(int position) { this.selectedDir = this.dirs.get(position); File dir = new File(this.selectedDir); String dirPath; try { dirPath = dir.getCanonicalPath(); } catch (IOException _) { dirPath = ""; } String[] files = dir.list(new Mp3Filter()); Arrays.sort(files, new Mp3Comparator(dirPath)); this.showFiles(files); this.filePosition = NO_FILES_SELECTED; this.dirList.invalidateViews(); this.enableButton(this.nextButton0, true); this.showNext(); } private void showFiles(String[] files) { this.files = files; this.fileList.setAdapter(new FileAdapter(this, files)); } private void stopTimer() { this.timer.cancel(); this.timer = this.fakeTimer; } private void pause() { this.stopTimer(); this.stopAudioService(); this.playButton.setOnClickListener(this.playListener); this.playButton.setImageResource(R.drawable.ic_play); } private class PlayerTask extends TimerTask { public PlayerTask(MainActivity activity) { this.handler = new Handler(); this.proc = new Proc(activity); } private class Proc extends ActivityHolder implements Runnable { public Proc(MainActivity activity) { super(activity); } public void run() { this.activity.sendMessage(AudioService.MSG_WHAT_TIME); } } @Override public void run() { this.handler.post(this.proc); } private Handler handler; private Runnable proc; } private void updateCurrentTime(int position) { this.slider.setProgress(position); this.showTime(this.currentTime, position); } private void startTimer() { this.timer = new TrueTimer(); // Each Timer requests new TimerTask object (Timers cannot share one task). this.timer.scheduleAtFixedRate(new PlayerTask(this), 0, 10); } private void play() { this.stopTimer(); this.startAudioService(); this.bindAudioService(new PlayProcedureOnConnected(this)); this.playButton.setOnClickListener(this.pauseListener); this.playButton.setImageResource(R.drawable.ic_pause); } private void sendPlay() { String path = this.getSelectedPath(); int offset = this.slider.getProgress(); Object a = AudioService.makePlayArgument(path, offset); this.sendMessage(AudioService.MSG_PLAY, a); } private String getSelectedFile() { int pos = this.filePosition; // Returning "" must be harmless. return pos == NO_FILES_SELECTED ? "" : this.files[pos]; } private String getSelectedPath() { return this.selectedDir + File.separator + this.getSelectedFile(); } private int getDuration(String path) { // MediaMetadataRetriever is not reusable. MediaMetadataRetriever meta = new MediaMetadataRetriever(); meta.setDataSource(path); int key = MediaMetadataRetriever.METADATA_KEY_DURATION; String datum; try { datum = meta.extractMetadata(key); } finally { meta.release(); } return Integer.parseInt(datum); } private void showTime(TextView view, int time_msec) { int time_sec = time_msec / 1000; int min = (time_sec / 60) % 100; int sec = time_sec % 60; view.setText(String.format("%02d:%02d", min, sec)); } private void enableButton(ImageButton button, boolean enabled) { button.setClickable(enabled); int resourceId = enabled ? R.drawable.nav_right : R.drawable.ic_blank; button.setImageResource(resourceId); } private void selectFile(int position) { this.pause(); this.filePosition = position; this.procAfterSeeking = new PlayAfterSeeking(this); this.fileList.invalidateViews(); this.enableButton(this.nextButton1, true); String path = this.getSelectedPath(); int duration = this.getDuration(path); this.slider.setMax(duration); this.slider.setProgress(0); this.showPlayingFile(); this.showNext(); this.play(); } private void showPlayingFile() { this.title.setText(this.getSelectedFile()); this.showTime(this.currentTime, this.slider.getProgress()); this.showTime(this.totalTime, this.slider.getMax()); } private void showPrevious() { this.flipper.setInAnimation(this.leftInAnimation); this.flipper.setOutAnimation(this.rightOutAnimation); this.flipper.showPrevious(); this.pageIndex -= 1; } private void showNext() { this.flipper.setInAnimation(this.rightInAnimation); this.flipper.setOutAnimation(this.leftOutAnimation); this.flipper.showNext(); this.pageIndex += 1; } private abstract class ListListener implements AdapterView.OnItemClickListener { public ListListener(MainActivity activity) { this.activity = activity; } protected MainActivity activity; } private class DirectoryListListener extends ListListener { public DirectoryListListener(MainActivity activity) { super(activity); } public void onItemClick(AdapterView<?> adapter, View view, int position, long id) { this.activity.selectDir(position); } } private class FileListListener extends ListListener { public FileListListener(MainActivity activity) { super(activity); } public void onItemClick(AdapterView<?> adapter, View view, int position, long id) { this.activity.selectFile(position); } } private void setClickListener(View[] buttons, View.OnClickListener listener) { for (View button: buttons) { button.setOnClickListener(listener); } } private abstract class FlipButtonListener implements View.OnClickListener { public FlipButtonListener(MainActivity activity) { this.activity = activity; } protected MainActivity activity; } private class NextButtonListener extends FlipButtonListener { public NextButtonListener(MainActivity activity) { super(activity); } @Override public void onClick(View view) { this.activity.showNext(); } } private class PreviousButtonListener extends FlipButtonListener { public PreviousButtonListener(MainActivity activity) { super(activity); } @Override public void onClick(View view) { this.activity.showPrevious(); } } private interface TimerInterface { public void scheduleAtFixedRate(TimerTask task, long deley, long period); public void cancel(); } private class TrueTimer implements TimerInterface { public TrueTimer() { this.timer = new Timer(true); } public void scheduleAtFixedRate(TimerTask task, long deley, long period) { this.timer.scheduleAtFixedRate(task, deley, period); } public void cancel() { this.timer.cancel(); } private Timer timer; } private class FakeTimer implements TimerInterface { public void scheduleAtFixedRate(TimerTask task, long deley, long period) { } public void cancel() { } } @Override protected void onResume() { super.onResume(); Intent intent = this.makeAudioServiceIntent(); Connection conn = new Connection(this, new ResumeProcedureOnConnected(this)); if (this.bindService(intent, conn, 0)) { this.serviceStarter = new FakeServiceStarter(); this.serviceStopper = new TrueServiceStopper(this); this.serviceUnbinder = new TrueServiceUnbinder(this); this.connection = conn; } else { this.serviceStarter = new TrueServiceStarter(this); this.serviceStopper = new FakeServiceStopper(); this.serviceUnbinder = new FakeServiceUnbinder(); this.connection = null; } Log.i(LOG_TAG, "Resumed."); } @Override protected void onPause() { super.onPause(); this.stopTimer(); this.unbindAudioService(); Log.i(LOG_TAG, "Paused."); } private enum Key { PAGE_INDEX, NEXT_BUTTON0_ENABLED, NEXT_BUTTON1_ENABLED, SELECTED_DIR, FILES, FILE_POSITION, PROGRESS, DURATION; public String getKey() { return this.name(); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(Key.PAGE_INDEX.getKey(), this.pageIndex); this.saveButton(outState, Key.NEXT_BUTTON0_ENABLED, this.nextButton0); this.saveButton(outState, Key.NEXT_BUTTON1_ENABLED, this.nextButton1); outState.putString(Key.SELECTED_DIR.getKey(), this.selectedDir); outState.putStringArray(Key.FILES.getKey(), this.files); outState.putInt(Key.FILE_POSITION.getKey(), this.filePosition); outState.putInt(Key.PROGRESS.getKey(), this.slider.getProgress()); outState.putInt(Key.DURATION.getKey(), this.slider.getMax()); Log.i(LOG_TAG, "Instance state was saved."); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); this.pageIndex = savedInstanceState.getInt(Key.PAGE_INDEX.getKey()); for (int i = 0; i < this.pageIndex; i++) { this.flipper.showNext(); } this.restoreButton(savedInstanceState, Key.NEXT_BUTTON0_ENABLED, this.nextButton0); this.restoreButton(savedInstanceState, Key.NEXT_BUTTON1_ENABLED, this.nextButton1); this.selectedDir = savedInstanceState.getString(Key.SELECTED_DIR.getKey()); this.showFiles(savedInstanceState.getStringArray(Key.FILES.getKey())); this.filePosition = savedInstanceState.getInt(Key.FILE_POSITION.getKey()); this.slider.setProgress(savedInstanceState.getInt(Key.PROGRESS.getKey())); this.slider.setMax(savedInstanceState.getInt(Key.DURATION.getKey())); this.showPlayingFile(); Log.i(LOG_TAG, "Instance state was restored."); } private void restoreButton(Bundle savedInstanceState, Key key, ImageButton button) { boolean enabled = savedInstanceState.getBoolean(key.getKey()); this.enableButton(button, enabled); } private void saveButton(Bundle outState, Key key, ImageButton button) { outState.putBoolean(key.getKey(), button.isClickable()); } private void sendMessage(int what, Object o) { Message msg = Message.obtain(null, what, 0, 0, o); msg.replyTo = this.incomingMessenger; try { this.outgoingMessenger.send(msg); } catch (RemoteException e) { // TODO: MainActivity must show error to users. e.printStackTrace(); } } private void sendMessage(int what) { this.sendMessage(what, null); } private void log(String msg) { this.title.setText(msg); } private void startAudioService() { this.serviceStarter.start(); this.serviceStarter = new FakeServiceStarter(); this.serviceStopper = new TrueServiceStopper(this); } private void stopAudioService() { this.serviceStopper.stop(); this.serviceStarter = new TrueServiceStarter(this); this.serviceStopper = new FakeServiceStopper(); } private void unbindAudioService() { this.serviceUnbinder.unbind(); this.serviceUnbinder = new FakeServiceUnbinder(); } private Intent makeAudioServiceIntent() { return new Intent(this, AudioService.class); } private void bindAudioService(Runnable procedureOnConnected) { Intent intent = this.makeAudioServiceIntent(); this.connection = new Connection(this, procedureOnConnected); this.bindService(intent, this.connection, 0); this.serviceUnbinder = new TrueServiceUnbinder(this); } private void onStartSliding() { this.stopTimer(); this.sendMessage(AudioService.MSG_PAUSE); } private void initializeFileList() { this.fileList.setOnItemClickListener(new FileListListener(this)); } } // vim: tabstop=4 shiftwidth=4 expandtab softtabstop=4
package com.xinra.growthlectures.frontend; import com.xinra.growthlectures.service.LectureSummaryDto; import com.xinra.growthlectures.service.NamedDto; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Component @Scope("singleton") public class Formatter { public String duration(Integer duration) { int hour = duration / 60 / 60; int minute = (duration / 60) % 60; int second = duration % 60; return String.format("%02d:%02d:%02d", hour, minute, second); } public String date(LocalDate date) { return date.format(DateTimeFormatter.ofPattern("dd.MM.yyyy")); } public String lectureUrl(LectureSummaryDto dto) { return String.format("/lectures/%s/%s", dto.getCategory().getSlug(), dto.getSlug()); } public String categoryUrl(NamedDto dto) { return "/lectures/" + dto.getSlug(); } public String lecturerUrl(NamedDto dto) { return "/lecturers/" + dto.getSlug(); } }
package StevenDimDoors.mod_pocketDimClient; import static org.lwjgl.opengl.GL11.*; import java.awt.Point; import java.util.HashMap; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.tileentity.TileEntity; import org.lwjgl.opengl.GL11; import StevenDimDoors.mod_pocketDim.tileentities.TileEntityRift; import StevenDimDoors.mod_pocketDim.util.l_systems.LSystem; import StevenDimDoors.mod_pocketDim.util.l_systems.LSystem.PolygonStorage; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class RenderRift extends TileEntitySpecialRenderer { @Override public void renderTileEntityAt(TileEntity te, double xWorld, double yWorld, double zWorld, float f) { // prepare fb for drawing GL11.glPushMatrix(); // make the rift render on both sides, disable texture mapping and // lighting GL11.glDisable(GL11.GL_CULL_FACE); GL11.glDisable(GL_TEXTURE_2D); GL11.glDisable(GL_LIGHTING); GL11.glEnable(GL_BLEND); /** * GL11.glLogicOp(GL11.GL_INVERT); * GL11.glEnable(GL11.GL_COLOR_LOGIC_OP); */ TileEntityRift rift = (TileEntityRift) te; // draws the verticies corresponding to the passed it this.drawCrack(rift.riftRotation, rift.getCurve(), Math.log(2+rift.growth)/5D, xWorld, yWorld, zWorld); GL11.glDisable(GL_BLEND); // reenable all the stuff we disabled GL11.glEnable(GL11.GL_CULL_FACE); GL11.glEnable(GL11.GL_LIGHTING); GL11.glEnable(GL_TEXTURE_2D); GL11.glPopMatrix(); } /** * method that draws the fractal and applies animations/effects * * f * * @param riftRotation * @param poly * @param size * @param xWorld * @param yWorld * @param zWorld */ public void drawCrack(int riftRotation, PolygonStorage poly, double size, double xWorld, double yWorld, double zWorld) { // calculate the proper size for the rift render double scale = size / (poly.maxX - poly.minX); // calculate the midpoint of the fractal bounding box double offsetX = ((poly.maxX + poly.minX)) / 2; double offsetY = ((poly.maxY + poly.minY)) / 2; double offsetZ = 0; // changes how far the triangles move float motionMagnitude = 3.0F; // changes how quickly the triangles move float motionSpeed = 2000.0F; // number of individual jitter waveforms to generate // changes how "together" the overall motions are int jCount = 5; // Calculate jitter like for monoliths float time = (float) (((Minecraft.getSystemTime() + 0xF1234568 * this.hashCode()) % 2000000) / motionSpeed); double[] jitters = new double[jCount]; // generate a series of waveforms for (int i = 0; i < jCount-1; i += 1) { jitters[i] = Math.sin((1F + i / 10F) * time) * Math.cos(1F - (i / 10F) * time) / motionMagnitude; jitters[i + 1] = Math.cos((1F + i / 10F) * time) * Math.sin(1F - (i / 10F) * time) / motionMagnitude; } // determines which jitter waveform we select. Modulo so the same point // gets the same jitter waveform over multiple frames int jIndex = 0; // set the color for the render GL11.glColor4f(.02F, .02F, .02F, 1F); //set the blending mode GL11.glEnable(GL_BLEND); glBlendFunc(GL_ONE_MINUS_SRC_COLOR, GL_ONE); GL11.glBegin(GL11.GL_TRIANGLES); for (Point p : poly.points) { jIndex = Math.abs(((p.x + p.y)*(p.x + p.y + 1)/2) + p.y); //jIndex++; // calculate the rotation for the fractal, apply offset, and apply // jitter double x = (((p.x + jitters[(jIndex + 1) % jCount]) - offsetX) * Math.cos(Math.toRadians(riftRotation)) - (jitters[(jIndex + 2) % jCount]) * Math.sin(Math.toRadians(riftRotation))); double y = p.y + (jitters[jIndex % jCount]); double z = (((p.x + jitters[(jIndex + 2) % jCount]) - offsetX) * Math.sin(Math.toRadians(riftRotation)) + (jitters[(jIndex + 2) % jCount]) * Math .cos(Math.toRadians(riftRotation))); // apply scaling x *= scale; y *= scale; z *= scale; // apply transform to center the offset origin into the middle of a // block x += .5; y += .5; z += .5; // draw the vertex and apply the world (screenspace) relative // coordinates GL11.glVertex3d(xWorld + x, yWorld + y, zWorld + z); } GL11.glEnd(); glBlendFunc(GL_ONE, GL_ONE_MINUS_DST_COLOR); // draw the next set of triangles to form a background and change their // color slightly over time GL11.glBegin(GL11.GL_TRIANGLES); for (Point p : poly.points) { jIndex++; double x = (((p.x) - offsetX) * Math.cos(Math.toRadians(riftRotation)) - 0 * Math.sin(Math.toRadians(riftRotation))); double y = p.y; double z = (((p.x) - offsetX) * Math.sin(Math.toRadians(riftRotation)) + 0 * Math.cos(Math.toRadians(riftRotation))); x *= scale; y *= scale; z *= scale; x += .5; y += .5; z += .5; if (jIndex % 3 == 0) { GL11.glColor4d(jitters[(jIndex + 5) % jCount] / 11, jitters[(jIndex + 4) % jCount] / 8, jitters[(jIndex+3) % jCount] / 8, 1); } GL11.glVertex3d(xWorld + x, yWorld + y, zWorld + z); } // stop drawing triangles GL11.glEnd(); } }
package ch.liquidmind.inflection.proxy; import java.io.File; import java.io.OutputStream; import java.io.PrintWriter; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import __java.io.__FileOutputStream; import __java.io.__OutputStream; import __org.apache.commons.io.__FileUtils; import ch.liquidmind.inflection.loader.TaxonomyLoader; import ch.liquidmind.inflection.model.external.Field; import ch.liquidmind.inflection.model.external.Member; import ch.liquidmind.inflection.model.external.Property; import ch.liquidmind.inflection.model.external.Taxonomy; import ch.liquidmind.inflection.model.external.View; import ch.liquidmind.inflection.model.linked.NamedElementLinked; import ch.liquidmind.inflection.model.linked.UnparsedAnnotation; // TODO Proxies of abstract classes should be abstract themselves (since it doesn't // make sense to be able to instantiate a view of an un-instantiable class). // TODO Make ProxyGenerator work like InflectionCompiler, i.e., introduce a ProxyGeneratorJob, etc. // TODO Make the taxonomy a class and proxies public static inner classes thereof. This has // the advantage of being syntactically more intuitive (dot notation) and also references to the // taxonomy can be refactored more easily. public class ProxyGenerator { private File baseDir; private Taxonomy taxonomy; private PrintWriter printWriter; // TODO Introduce apache commons cli, analogous to deflector. public static void main( String[] args ) { File baseDir = new File( args[ 0 ] ); String[] taxonomyNames = new String[ args.length - 1 ]; for ( int i = 0 ; i < taxonomyNames.length ; ++i ) taxonomyNames[ i ] = args[ i + 1 ]; for ( String taxonomyName : taxonomyNames ) { Taxonomy taxonomy = TaxonomyLoader.getContextTaxonomyLoader().loadTaxonomy( taxonomyName ); new ProxyGenerator( baseDir, taxonomy ).generateTaxonomy(); } } public ProxyGenerator( File baseDir, Taxonomy taxonomy ) { super(); this.baseDir = baseDir; this.taxonomy = taxonomy; } public void generateTaxonomy() { if ( !baseDir.exists() ) __FileUtils.forceMkdir( null, baseDir ); generateProxyCollections(); for ( View view : taxonomy.getViews() ) generateView( view ); } private void generateProxyCollections() { generateProxyCollection( ListProxy.class ); generateProxyCollection( SetProxy.class ); generateProxyCollection( MapProxy.class ); generateProxyCollection( IteratorProxy.class ); } private void generateProxyCollection( Class< ? > proxyCollection ) { String fqCollectionName = getFullyQualifiedCollectionName( taxonomy, proxyCollection ); String collectionFileName = fqCollectionName.replace( ".", "/" ) + ".java"; File collectionFile = new File( baseDir, collectionFileName ); if ( !collectionFile.getParentFile().exists() ) __FileUtils.forceMkdir( null, collectionFile.getParentFile() ); OutputStream outputStream = __FileOutputStream.__new( collectionFile ); printWriter = new PrintWriter( outputStream ); try { generateProxyCollection( proxyCollection, fqCollectionName ); } finally { printWriter.close(); __OutputStream.close( outputStream ); } } private void generateProxyCollection( Class< ? > proxyCollection, String fqCollectionName ) { int lastIndexOfDot = fqCollectionName.lastIndexOf( "." ); String packageName = fqCollectionName.substring( 0, lastIndexOfDot ); String simpleName = fqCollectionName.substring( lastIndexOfDot + 1 ); String genericType = ( Map.class.isAssignableFrom( proxyCollection ) ? "< K, V >" : "< E >" ); printWriter.println( "package " + packageName + ";" ); printWriter.println(); printWriter.println( "public class " + simpleName + genericType + " extends " + proxyCollection.getName() + genericType ); printWriter.println( "{" ); printWriter.println( " public " + simpleName + "()"); printWriter.println( " {" ); printWriter.println( " super( \"" + taxonomy.getName() + "\" );" ); printWriter.println( " }" ); printWriter.println( "}" ); } private void generateView( View view ) { String fqViewName = getFullyQualifiedViewName( taxonomy, view ); String viewFileName = fqViewName.replace( ".", "/" ) + ".java"; File viewFile = new File( baseDir, viewFileName ); if ( !viewFile.getParentFile().exists() ) __FileUtils.forceMkdir( null, viewFile.getParentFile() ); OutputStream outputStream = __FileOutputStream.__new( viewFile ); printWriter = new PrintWriter( outputStream ); try { generateView( view, fqViewName ); } finally { printWriter.close(); __OutputStream.close( outputStream ); } } // TODO: move this to common location (also used by ProxyRegistry). public static String getFullyQualifiedViewName( Taxonomy taxonomy, View view ) { String fqViewName = taxonomy.getName() + "." + view.getPackageName() + "." + taxonomy.getSimpleName() + "_" + view.getSimpleNameOrAlias(); return fqViewName; } public static String getFullyQualifiedCollectionName( Taxonomy taxonomy, Class< ? > collectionType ) { String fqCollectionName = taxonomy.getName() + "." + collectionType.getPackage().getName() + "." + taxonomy.getSimpleName() + "_" + collectionType.getSimpleName(); return fqCollectionName; } private void generateView( View view, String fqViewName ) { printWriter.println( "package " + NamedElementLinked.getPackageName( fqViewName ) + ";" ); printWriter.println(); printWriter.println( String.join( " ", getAnnotations( view.getAnnotations() ) ) ); printWriter.println( "public class " + NamedElementLinked.getSimpleName( fqViewName ) + " extends " + getSuperClassName( view ) ); printWriter.println( "{" ); generateConstructors( view, fqViewName ); generateMembers( view.getDeclaredMembers() ); printWriter.println( "}" ); } private String getSuperClassName( View view ) { String superClassName; View superView = taxonomy.getSuperview( view ); if ( superView != null ) superClassName = getFullyQualifiedViewName( taxonomy, superView ); else superClassName = Proxy.class.getName(); return superClassName; } private void generateConstructors( View view, String fqViewName ) { printWriter.println( " public " + NamedElementLinked.getSimpleName( fqViewName ) + "()" ); printWriter.println( " {" ); printWriter.println( " super( \"" + taxonomy.getName() + "\", \"" + view.getName() + "\" );" ); printWriter.println( " }" ); printWriter.println(); printWriter.println( " protected " + NamedElementLinked.getSimpleName( fqViewName ) + "( String taxonomyName, String viewName )" ); printWriter.println( " {" ); printWriter.println( " super( taxonomyName, viewName );" ); printWriter.println( " }" ); printWriter.println(); } private void generateMembers( List< Member > members ) { for ( int i = 0 ; i < members.size() ; ++i ) { Member member = members.get( i ); String nameOrAlias = member.getNameOrAlias(); String capName = nameOrAlias.substring( 0, 1 ).toUpperCase() + nameOrAlias.substring( 1 ); String proxyGetMethodName = "get" + capName; String proxySetMethodName = "set" + capName; generateMember( proxyGetMethodName, proxySetMethodName, member ); if ( i + 1 != members.size() ) printWriter.println(); } } private void generateMember( String proxyGetMethodName, String proxySetMethodName, Member member ) { if ( member instanceof Property ) generateProperty( proxyGetMethodName, proxySetMethodName, (Property)member ); else if ( member instanceof Field ) generateField( proxyGetMethodName, proxySetMethodName, (Field)member ); } private void generateProperty( String proxyGetMethodName, String proxySetMethodName, Property property ) { generateProperty( proxyGetMethodName, property.getReadMethod(), property.getAnnotations() ); printWriter.println(); generateProperty( proxySetMethodName, property.getWriteMethod(), new ArrayList< Annotation >() ); } private void generateProperty( String proxyMethodName, Method targetMethod, List< Annotation > annotations ) { if ( targetMethod == null ) return; List< Type > targetParamTypes = Arrays.asList( targetMethod.getGenericParameterTypes() ); List< Type > proxyParamTypes = targetParamTypes; if ( Modifier.isStatic( targetMethod.getModifiers() ) ) proxyParamTypes = new ArrayList< Type >( targetParamTypes.subList( 1, targetParamTypes.size() ) ); Type[] targetParamTypesAsArray = targetParamTypes.toArray( new Type[ targetParamTypes.size() ] ); Type[] proxyParamTypesAsArray = proxyParamTypes.toArray( new Type[ proxyParamTypes.size() ] ); generateMethod( proxyMethodName, proxyParamTypesAsArray, annotations, targetMethod.getName(), targetParamTypesAsArray, targetMethod.getGenericReturnType(), targetMethod.getExceptionTypes() ); } private void generateField( String proxyGetMethodName, String proxySetMethodName, Field field ) { String name = field.getName(); String capName = name.substring( 0, 1 ).toUpperCase() + name.substring( 1 ); generateMethod( proxyGetMethodName, new Class< ? >[]{}, field.getAnnotations(), "get" + capName, new Class< ? >[]{}, field.getField().getType(), new Class< ? >[]{} ); generateMethod( proxySetMethodName, new Class< ? >[]{ field.getField().getType() }, new ArrayList< Annotation >(), "set" + capName, new Class< ? >[]{ field.getField().getType() }, void.class, new Class< ? >[]{} ); } private void generateMethod( String proxyMethodName, Type[] proxyParamTypes, List< Annotation > annotations, String targetMethodName, Type[] targetParamTypes, Type retType, Class< ? >[] exTypes ) { String flatAnnotations = String.join( " ", getAnnotations( annotations ) ); String retTypeName = getTypeName( retType ); String parameters = String.join( ", ", getParameters( proxyParamTypes ) ); String exceptions = String.join( ", ", getExceptions( exTypes ) ); String paramsWithParens = ( parameters.isEmpty() ? "()" : "( " + parameters + " )" ); String execptionsWithThrows = ( exceptions.isEmpty() ? "" : " throws " + exceptions ); printWriter.println( " " + flatAnnotations ); printWriter.println( " public " + retTypeName + " " + proxyMethodName + paramsWithParens + execptionsWithThrows ); printWriter.println( " {" ); printWriter.println( " try" ); printWriter.println( " {" ); generateInvocation( targetMethodName, proxyParamTypes, targetParamTypes, retType, exTypes ); printWriter.println( " }" ); // TODO: Need to do this in the same way as I did in deflector: the // order in which exceptions are caught matters! for ( Class< ? > exType : exTypes ) { printWriter.println( " catch ( " + exType.getName() + " e )" ); printWriter.println( " {" ); printWriter.println( " throw (" + exType.getName() + ")e;" ); printWriter.println( " }" ); } printWriter.println( " catch ( java.lang.RuntimeException e )" ); printWriter.println( " {" ); printWriter.println( " throw (java.lang.RuntimeException)e;" ); printWriter.println( " }" ); printWriter.println( " catch ( java.lang.Throwable e )" ); printWriter.println( " {" ); printWriter.println( " throw new java.lang.IllegalStateException();" ); printWriter.println( " }" ); printWriter.println( " }" ); } @SuppressWarnings( "unchecked" ) private String[] getAnnotations( List< Annotation > annotations ) { List< UnparsedAnnotation > unparsedAnnotations = (List< UnparsedAnnotation >)(Object)annotations; List< String > annotationsAsText = new ArrayList< String >(); for ( UnparsedAnnotation unparsedAnnotation : unparsedAnnotations ) annotationsAsText.add( unparsedAnnotation.value() ); return annotationsAsText.toArray( new String[ annotationsAsText.size() ] ); } private void generateInvocation( String targetMethodName, Type[] proxyParamTypes, Type[] targetParamTypes, Type retType, Class< ? >[] exTypes ) { String parameterClasses = String.join( ", ", getParameterTypes( targetParamTypes ) ); String parameterClassesWithClassArray = ( parameterClasses.isEmpty() ? "new Class< ? >[]{}" : "new Class< ? >[]{ " + parameterClasses + " }"); String arguments = String.join( ", ", getArguments( proxyParamTypes ) ); String argumentsWithObjectArray = ( parameterClasses.isEmpty() ? "new Object[]{}" : "new Object[]{ " + arguments + " }"); String returnKeyword = ( retType != void.class ? "return " : "" ); printWriter.println( " " + returnKeyword + "invoke( \"" + targetMethodName + "\", " + parameterClassesWithClassArray + ", " + argumentsWithObjectArray + " );" ); } private List< String > getParameters( Type[] paramTypes ) { List< String > parameters = new ArrayList< String >(); for ( int i = 0 ; i < paramTypes.length ; ++i ) parameters.add( getTypeName( paramTypes[ i ] ) + " arg" + i ); return parameters; } // TODO: For now, I am handling generic types in a highly // simplified way. In a second pass, we need to handle them // in the same fashion as deflector. private String getTypeName( Type type ) { String typeName; if ( type instanceof Class ) { Class< ? > aClass = (Class< ? >)type; View view = taxonomy.resolveView( aClass ); if ( view == null ) typeName = aClass.getName(); else typeName = getFullyQualifiedViewName( taxonomy, view ); } else if ( type instanceof ParameterizedType ) { ParameterizedType parameterizedType = (ParameterizedType)type; Type rawType = parameterizedType.getRawType(); Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); String rawTypeConverted; List< String > actualTypeArgumentsConverted = new ArrayList< String >(); if ( ProxyRegistry.PROXY_BASE_CLASSES.containsKey( rawType ) ) rawTypeConverted = getFullyQualifiedCollectionName( taxonomy, ProxyRegistry.PROXY_BASE_CLASSES.get( rawType ) ); else throw new IllegalStateException( "No support for non-collection generic types at this time, type: " + type.getTypeName() ); for ( Type actualTypeArgument : actualTypeArguments ) { if ( actualTypeArgument instanceof Class ) actualTypeArgumentsConverted.add( getTypeName( actualTypeArgument ) ); else throw new IllegalStateException( "No support for general purpose generics at this time (only for collections), type: " + type.getTypeName() ); } typeName = rawTypeConverted + "< " + String.join( ", ", actualTypeArgumentsConverted ) + " >"; } else { throw new IllegalStateException( "Unexpected type for 'type': " + type.getClass().getName() ); } return typeName; } private List< String > getExceptions( Class< ? >[] exTypes ) { List< String > exceptions = new ArrayList< String >(); for ( Class< ? > exType : exTypes ) exceptions.add( exType.getName() ); return exceptions; } private List< String > getParameterTypes( Type[] paramTypes ) { List< String > parameters = new ArrayList< String >(); for ( int i = 0 ; i < paramTypes.length ; ++i ) { // TODO: The way I'm getting typeNameOfRawType is, frankly, a hack, but // as I've said, I plan on completely replacing the way generics are // handled with a deflector-like implementation in the near future. String typeName = getTypeName( paramTypes[ i ] ); String typeNameOfRawType; if ( typeName.contains( "<" ) ) typeNameOfRawType = typeName.substring( 0, typeName.indexOf( "<" ) ); else typeNameOfRawType = typeName; parameters.add( typeNameOfRawType + ".class" ); } return parameters; } private List< String > getArguments( Type[] paramTypes ) { List< String > arguments = new ArrayList< String >(); for ( int i = 0 ; i < paramTypes.length ; ++i ) arguments.add( "arg" + i ); return arguments; } }
package com.addicks.sendash.admin.service; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.addicks.sendash.admin.domain.properties.RepositoryProperties; @Service public class FileService { public static final String ZIP_NAME = "sendash.zip"; @Autowired private RepositoryProperties repositoryProperties; private static final Logger log = LoggerFactory.getLogger(FileService.class); public FileService() { } private List<String> generateFileList(String sourceFolder, File node) throws IOException { List<String> fileList = new ArrayList<String>(); // add file only if (node.isFile()) { fileList.add(node.getCanonicalPath()); } if (node.isDirectory()) { String[] subNote = node.list(); for (String filename : subNote) { if (!filename.startsWith(".")) { fileList.addAll(generateFileList(sourceFolder, new File(node, filename))); } } } return fileList; } public void createZip() { String zipFile = ZIP_NAME; String sourceDirectory = repositoryProperties.getLocalRepo(); byte[] buffer = new byte[1024]; try { // create object of FileOutputStream FileOutputStream fout = new FileOutputStream(zipFile); // create object of ZipOutputStream from FileOutputStream try (ZipOutputStream zout = new ZipOutputStream(fout)) { // create File object from directory name File dir = new File(sourceDirectory); log.debug("DIR: " + dir); // check to see if this directory exists if (!dir.isDirectory()) { log.error(sourceDirectory + " is not a directory"); } else { List<String> files = generateFileList(sourceDirectory, dir); for (String fileName : files) { // create object of FileInputStream for source file try { FileInputStream fin = new FileInputStream(fileName); zout.putNextEntry( new ZipEntry(fileName.substring(fileName.indexOf(sourceDirectory.substring(2))))); /* * After creating entry in the zip file, actually write the file. */ int length; while ((length = fin.read(buffer)) > 0) { zout.write(buffer, 0, length); } /* * After writing the file to ZipOutputStream, use * * void closeEntry() method of ZipOutputStream class to close the * current entry and position the stream to write the next entry. */ zout.closeEntry(); // close the InputStream fin.close(); } catch (FileNotFoundException ex) { log.error("File not Found:" + fileName); } } } // close the ZipOutputStream zout.close(); log.debug("Zip file has been created!"); } } catch (IOException ioe) { ioe.printStackTrace(); } } // public FileSystem getZip() { }
package net.meeusen.crypto; import java.util.Arrays; import org.bouncycastle.crypto.engines.AESEngine; import org.bouncycastle.crypto.modes.CCMBlockCipher; import org.bouncycastle.crypto.params.AEADParameters; import org.bouncycastle.crypto.params.KeyParameter; import net.meeusen.util.ByteString; /** * Wrappers around BC AES-CCM, with easy API to validate NIST test vectors for AES-CCM. * * */ public class AesCcmTest { public byte[] getCalculatedOutput() { return calculatedOutput; } public byte[] getPayLoad() { return payLoad; } public byte[] getCipherText() { return cipherText; } private CCMBlockCipher ccmCipher; private KeyParameter keyParameter; private int TlenBytes; private byte[] key; private byte[] nonce; private byte[] Adata; private byte[] payLoad; private byte[] cipherText; private TestType type; // following can be either payload or ciphertext depending on test type. private byte[] calculatedOutput; public String toString() { return this.type.toString() + " Tlen:" + TlenBytes + " KeyLen:" + key.length + " Nlen: " + nonce.length + " Alen: " + Adata.length + " Plen:" + payLoad.length; } /** * Constructor with (hex) String arguments * @throws Exception * */ public AesCcmTest(TestType type, int argTlenBytes, String Key, String Nonce, String argAdata, String argPayload, String argCipherText) throws Exception { this(type, argTlenBytes, new ByteString(Key).getBytes(), new ByteString(Nonce).getBytes(), new ByteString(argAdata).getBytes(), new ByteString(argPayload).getBytes(), new ByteString(argCipherText).getBytes()); } /** * Constructor with byte[] arguments * @throws Exception * */ public AesCcmTest(TestType argTestType, int argTlenBytes, byte[] Key, byte[] Nonce, byte[] argAdata, byte[] argPayload, byte[] argCipherText) throws Exception { switch ( argTestType ) { case ENCRYPT: // need payload to encrypt something if ( argPayload == null ) throw new Exception ("Cannot encrypt without payload."); break; case DECRYPT: // need CT to decrypt something if ( argCipherText == null ) throw new Exception ("Cannot decrypt without ciphertext."); break; default: throw new Exception("not allowed"); } this.type = argTestType; this.ccmCipher = new CCMBlockCipher(new AESEngine()); this.keyParameter = new KeyParameter(Key); this.TlenBytes = argTlenBytes; this.key = Key.clone(); this.nonce = Nonce.clone(); // some of these are optional: if ( argAdata != null ) this.Adata = argAdata.clone(); if ( argPayload != null ) this.payLoad = argPayload.clone(); if ( argCipherText != null ) this.cipherText = argCipherText.clone(); } /** * encrypt or decrypt depending on test type. * store result in instance variable calculatedOutput * result is NOT interpreted, not compared to any expected output... * @throws Exception * */ public void doCalculate() throws Exception{ boolean isEncryption; byte[] testInput=null; //byte[] testOutput=null; switch ( this.type ) { case ENCRYPT: isEncryption = true; testInput = this.payLoad; break; case DECRYPT: isEncryption = false; testInput = this.cipherText; break; default: throw new Exception("not allowed"); } // init int TlenBits = this.TlenBytes * 8; ccmCipher.init(isEncryption, new AEADParameters(this.keyParameter, TlenBits, this.nonce, this.Adata)); // process int inputOffset = 0; int outputOffset = 0; int expectedOutputSize = this.ccmCipher.getOutputSize(testInput.length); this.calculatedOutput = new byte[expectedOutputSize]; int nrProcessBytes = this.ccmCipher.processPacket(testInput, inputOffset, testInput.length, this.calculatedOutput, outputOffset); if ( nrProcessBytes != expectedOutputSize ) { throw new Exception("unexpected internal error or misunderstanding..."); } // strange, when I do another doFinal, there is data coming out, not // expected, and not sure what this data means... // byte[] finalOutput = new byte[ccmCipher.getOutputSize(0)]; // int nrOutputBytes =ccmCipher.doFinal(finalOutput, 0); // if ( nrOutputBytes != finalOutput.length) { // throw new Error("this should not happen."); } /** * calculate AND compare with expected output * */ public boolean checkTestVector() throws Exception { this.doCalculate(); byte[] expectedOutput=null; switch ( this.type ) { case ENCRYPT: expectedOutput = this.cipherText; break; case DECRYPT: expectedOutput = this.payLoad; break; default: throw new Exception("not allowed"); } return Arrays.equals(this.calculatedOutput, expectedOutput); } /** * Check some CCM test vectors NIST. * */ public static void main(String[] args) throws Exception { AesCcmTest someNistAesCcmTestVectors[] = new AesCcmTest[] { // from VPT256.rsp NIST file: new AesCcmTest(TestType.ENCRYPT, 16, "7da6ef35ad594a09cb74daf27e50a6b30d6b4160cf0de41ee32bbf2a208b911d", "98a32d7fe606583e2906420297", "217d130408a738e6a833931e69f8696960c817407301560bbe5fbd92361488b4", "b0053d1f490809794250d856062d0aaa92", "a6341ee3d60eb34a8a8bc2806d50dd57a3f628ee49a8c2005c7d07d354bf80994d"), new AesCcmTest(TestType.ENCRYPT, 16, "c6c14c655e52c8a4c7e8d54e974d698e1f21ee3ba717a0adfa6136d02668c476", "291e91b19de518cd7806de44f6", "b4f8326944a45d95f91887c2a6ac36b60eea5edef84c1c358146a666b6878335", "", "ca482c674b599046cc7d7ee0d00eec1e"), new AesCcmTest(TestType.ENCRYPT, 16, "cc49d4a397887cb57bc92c8a8c26a7aac205c653ef4011c1f48390ad35f5df14", "6df8c5c28d1728975a0b766cd7", "080f82469505118842e5fa70df5323de175a37609904ee5e76288f94ca84b3c5", "1a", "a5f24e87a11a95374d4c190945bf08ef2f"), new AesCcmTest(TestType.ENCRYPT, 16, "62b82637e567ad27c3066d533ed76e314522ac5c53851a8c958ce6c64b82ffd0", "5bc2896d8b81999546f88232ab", "fffb40b0d18cb23018aac109bf62d849adca42629d8a9ad1299b83fe274f9a63", "87294078", "2bc22735ab21dfdcfe95bd83592fb6b4168d9a23"), // from VNT256.rsp: new AesCcmTest(TestType.ENCRYPT, 16, "553521a765ab0c3fd203654e9916330e189bdf951feee9b44b10da208fee7acf", "aaa23f101647d8", "a355d4c611812e5f9258d7188b3df8851477094ffc2af2cf0c8670db903fbbe0", "644eb34b9a126e437b5e015eea141ca1a88020f2d5d6cc2c", "27ed90668174ebf8241a3c74b35e1246b6617e4123578f153bdb67062a13ef4e986f5bb3d0bb4307"), new AesCcmTest(TestType.ENCRYPT, 16, "4a75ff2f66dae2935403cce27e829ad8be98185c73f8bc61d3ce950a83007e11", "ef284d1ddf35d1d23de6a2f84b", "0b90b3a087b9a4d3267bc57c470695ef7cf658353f2f680ee00ccc32c2ba0bdc", "bf35ddbad5e059169468ae8537f00ec790cc038b9ed0a5d7", "b702ad593b4169fd7011f0288e4e62620543095186b32c122389523b5ccc33c6b41b139108a99442"), // from VADT128.rsp: new AesCcmTest(TestType.ENCRYPT, 16, "d24a3d3dde8c84830280cb87abad0bb3", "f1100035bb24a8d26004e0e24b", "", "7c86135ed9c2a515aaae0e9a208133897269220f30870006", "1faeb0ee2ca2cd52f0aa3966578344f24e69b742c4ab37ab1123301219c70599b7c373ad4b3ad67b"), new AesCcmTest(TestType.ENCRYPT, 16, "5a33980e71e7d67fd6cf171454dc96e5", "33ae68ebb8010c6b3da6b9cb29", "eca622a37570df619e10ebb18bebadb2f2b49c4d2b2ff715873bb672e30fc0ff", "a34dfa24847c365291ce1b54bcf8d9a75d861e5133cc3a74", "7a60fa7ee8859e283cce378fb6b95522ab8b70efcdb0265f7c4b4fa597666b86dd1353e400f28864"), // from VTT192.rsp: new AesCcmTest(TestType.ENCRYPT, 4, "11fd45743d946e6d37341fec49947e8c70482494a8f07fcc", "c6aeebcb146cfafaae66f78aab", "7dc8c52144a7cb65b3e5a846e8fd7eae37bf6996c299b56e49144ebf43a1770f", "ee7e6075ba52846de5d6254959a18affc4faf59c8ef63489", "137d9da59baf5cbfd46620c5f298fc766de10ac68e774edf1f2c5bad"), new AesCcmTest(TestType.ENCRYPT, 14, "d2d4482ea8e98c1cf309671895a16610152ce283434bca38", "6ee177d48f59bd37045ec03731", "d4cd69b26ea43596278b8caec441fedcf0d729d4e0c27ed1332f48871c96e958", "e4abe343f98a2df09413c3defb85b56a6d34dba305dcce46", "7e8f27726c042d73aa6ebf43217395202e0af071eacf53790065601bb59972c35b580852e684"), // from DVPT256.rsp: new AesCcmTest(TestType.DECRYPT, 4, "af063639e66c284083c5cf72b70d8bc277f5978e80d9322d99f2fdc718cda569", "a544218dadd3c1", "", "d3d5424e20fbec43ae495353ed830271515ab104f8860c98", "64a1341679972dc5869fcf69b19d5c5ea50aa0b5e985f5b722aa8d59"), new AesCcmTest(TestType.DECRYPT, 4, "a4bc10b1a62c96d459fbaf3a5aa3face7313bb9e1253e696f96a7a8e36801088", "a544218dadd3c10583db49cf39", "3c0e2815d37d844f7ac240ba9d6e3a0b2a86f706e885959e09a1005e024f6907", "", "866d4227"), new AesCcmTest(TestType.DECRYPT, 16, "314a202f836f9f257e22d8c11757832ae5131d357a72df88f3eff0ffcee0da4e", "a544218dadd3c10583db49cf39", "3c0e2815d37d844f7ac240ba9d6e3a0b2a86f706e885959e09a1005e024f6907", "e8de970f6ee8e80ede933581b5bcf4d837e2b72baa8b00c3", "8d34cdca37ce77be68f65baf3382e31efa693e63f914a781367f30f2eaad8c063ca50795acd90203"), }; System.out.println("Running " + someNistAesCcmTestVectors.length + " NIST test vectors."); int testCounter = 0; for (AesCcmTest t : someNistAesCcmTestVectors) { System.out.print(testCounter + ":" + t + ": "); boolean hasPassed = t.checkTestVector(); if (!hasPassed) { System.out.println("ERROR."); } else { System.out.println("OK."); } testCounter++; } System.out.println("DONE running NIST test vectors."); } public enum TestType { ENCRYPT, DECRYPT; public String toString() { switch (this) { case ENCRYPT: return "ENCRYPT"; case DECRYPT: return "DECRYPT"; default: throw new IllegalArgumentException(); } } } }
package com.cobalt.cdpipeline.Controllers; import java.util.ArrayList; import java.util.List; import java.util.Set; import com.atlassian.bamboo.plan.Plan; import com.atlassian.bamboo.plan.PlanManager; import com.atlassian.bamboo.plan.TopLevelPlan; import com.atlassian.bamboo.project.Project; import com.atlassian.bamboo.project.ProjectManager; import com.atlassian.bamboo.resultsummary.ResultsSummary; import com.atlassian.bamboo.resultsummary.ResultsSummaryManager; import com.cobalt.cdpipeline.cdresult.CDResult; import com.cobalt.cdpipeline.cdresult.CDResultFactory; import com.cobalt.cdpipeline.cdresult.ContributorBuilder; /** * The main controller of CDPipeline Plugin Project that handles getting the * results needed for displaying the table. */ public class MainManager { private ProjectManager projectManager; private PlanManager planManager; private ResultsSummaryManager resultsSummaryManager; /** * Constructs a MainManager object. * * @param projectManager The ProjectManager (within Bamboo) to get information about projects. * @param planManager The PlanMananger (within Bamboo) to get information about plans. * @param resultsSummaryManager The ResultsSummaryManager (within Bamboo) to get information * about builds. */ public MainManager(ProjectManager projectManager, PlanManager planManager, ResultsSummaryManager resultsSummaryManager) { if (projectManager == null || planManager == null || resultsSummaryManager == null) { throw new IllegalArgumentException("Null arguments not allowed"); } this.projectManager = projectManager; this.planManager = planManager; this.resultsSummaryManager = resultsSummaryManager; } /** * Get all the results needed for displaying the CDPipeline table. * * @return a list of CDResults, where each CDResult represents one row. * See CDResults for more details. */ public List<CDResult> getCDResults() { // should get the params from the current user ContributorBuilder contributorBuilder = new ContributorBuilder("jira.cobalt.com", "liuch", "4eyesPet!"); List<CDResult> resultList = new ArrayList<CDResult>(); Set<Project> projects = projectManager.getAllProjects(); for (Project project : projects) { String projectName = project.getName(); String projectKey = project.getKey(); List<TopLevelPlan> plans = planManager.getAllPlansByProject(project, TopLevelPlan.class); for (Plan plan : plans) { String planName = plan.getName(); String planKey = plan.getKey(); List<ResultsSummary> buildList = resultsSummaryManager.getResultSummariesForPlan(plan, 0, 0); CDResult result = CDResultFactory.createCDResult(projectName, planName, projectKey, planKey, buildList, contributorBuilder); resultList.add(result); } } return resultList; } }
package com.fasterxml.jackson.databind; import java.io.IOException; import java.util.Iterator; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitable; import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper; import com.fasterxml.jackson.databind.jsontype.TypeSerializer; import com.fasterxml.jackson.databind.ser.PropertyWriter; import com.fasterxml.jackson.databind.util.ClassUtil; import com.fasterxml.jackson.databind.util.NameTransformer; /** * Abstract class that defines API used by {@link ObjectMapper} (and * other chained {@link JsonSerializer}s too) to serialize Objects of * arbitrary types into JSON, using provided {@link JsonGenerator}. * {@link com.fasterxml.jackson.databind.ser.std.StdSerializer} instead * of this class, since it will implement many of optional * methods of this class. *<p> * NOTE: various <code>serialize</code> methods are never (to be) called * with null values -- caller <b>must</b> handle null values, usually * by calling {@link SerializerProvider#findNullValueSerializer} to obtain * serializer to use. * This also means that custom serializers can not be directly used to change * the output to produce when serializing null values. *<p> * If serializer is an aggregate one -- meaning it delegates handling of some * of its contents by using other serializer(s) -- it typically also needs * to implement {@link com.fasterxml.jackson.databind.ser.ResolvableSerializer}, * which can locate secondary serializers needed. This is important to allow dynamic * overrides of serializers; separate call interface is needed to separate * resolution of secondary serializers (which may have cyclic link back * to serializer itself, directly or indirectly). *<p> * In addition, to support per-property annotations (to configure aspects * of serialization on per-property basis), serializers may want * to implement * {@link com.fasterxml.jackson.databind.ser.ContextualSerializer}, * which allows specialization of serializers: call to * {@link com.fasterxml.jackson.databind.ser.ContextualSerializer#createContextual} * is passed information on property, and can create a newly configured * serializer for handling that particular property. *<p> * If both * {@link com.fasterxml.jackson.databind.ser.ResolvableSerializer} and * {@link com.fasterxml.jackson.databind.ser.ContextualSerializer} * are implemented, resolution of serializers occurs before * contextualization. */ public abstract class JsonSerializer<T> implements JsonFormatVisitable // since 2.1 { /** * Method that will return serializer instance that produces * "unwrapped" serialization, if applicable for type being * serialized (which is the case for some serializers * that produce JSON Objects as output). * If no unwrapped serializer can be constructed, will simply * return serializer as-is. *<p> * Default implementation just returns serializer as-is, * indicating that no unwrapped variant exists * * @param unwrapper Name transformation to use to convert between names * of unwrapper properties */ public JsonSerializer<T> unwrappingSerializer(NameTransformer unwrapper) { return this; } /** * Method that can be called to try to replace serializer this serializer * delegates calls to. If not supported (either this serializer does not * delegate anything; or it does not want any changes), should either * throw {@link UnsupportedOperationException} (if operation does not * make sense or is not allowed); or return this serializer as is. * * @since 2.1 */ public JsonSerializer<T> replaceDelegatee(JsonSerializer<?> delegatee) { throw new UnsupportedOperationException(); } /** * Mutant factory method that is called if contextual configuration indicates that * a specific filter (as specified by <code>filterId</code>) is to be used for * serialization. *<p> * Default implementation simply returns <code>this</code>; sub-classes that do support * filtering will need to create and return new instance if filter changes. * * @since 2.6 */ public JsonSerializer<?> withFilterId(Object filterId) { return this; } /** * Method that can be called to ask implementation to serialize * values of type this serializer handles. * * @param value Value to serialize; can <b>not</b> be null. * @param gen Generator used to output resulting Json content * @param serializers Provider that can be used to get serializers for * serializing Objects value contains, if any. */ public abstract void serialize(T value, JsonGenerator gen, SerializerProvider serializers) throws IOException; /** * Method that can be called to ask implementation to serialize * values of type this serializer handles, using specified type serializer * for embedding necessary type information. *<p> * Default implementation will throw {@link UnsupportedOperationException} * to indicate that proper type handling needs to be implemented. *<p> * For simple datatypes written as a single scalar value (JSON String, Number, Boolean), * implementation would look like: *<pre> * // note: method to call depends on whether this type is serialized as JSON scalar, object or Array! * typeSer.writeTypePrefixForScalar(value, gen); * serialize(value, gen, provider); * typeSer.writeTypeSuffixForScalar(value, gen); *</pre> * and implementations for type serialized as JSON Arrays or Objects would differ slightly, * as <code>START-ARRAY</code>/<code>END-ARRAY</code> and * <code>START-OBJECT</code>/<code>END-OBJECT</code> pairs * need to be properly handled with respect to serializing of contents. * * @param value Value to serialize; can <b>not</b> be null. * @param gen Generator used to output resulting Json content * @param serializers Provider that can be used to get serializers for * serializing Objects value contains, if any. * @param typeSer Type serializer to use for including type information */ public void serializeWithType(T value, JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { Class<?> clz = handledType(); if (clz == null) { clz = value.getClass(); } serializers.reportBadDefinition(clz, String.format( "Type id handling not implemented for type %s (by serializer of type %s)", clz.getName(), getClass().getName())); } /** * Method for accessing type of Objects this serializer can handle. * Note that this information is not guaranteed to be exact -- it * may be a more generic (super-type) -- but it should not be * incorrect (return a non-related type). *<p> * Default implementation will return null, which essentially means * same as returning <code>Object.class</code> would; that is, that * nothing is known about handled type. *<p> */ public Class<T> handledType() { return null; } /** * Method called to check whether given serializable value is * considered "empty" value (for purposes of suppressing serialization * of empty values). *<p> * Default implementation will consider only null values to be empty. * * @deprecated Since 2.5 Use {@link #isEmpty(SerializerProvider, Object)} instead; * will be removed from 3.0 */ @Deprecated public boolean isEmpty(T value) { return isEmpty(null, value); } /** * Method called to check whether given serializable value is * considered "empty" value (for purposes of suppressing serialization * of empty values). *<p> * Default implementation will consider only null values to be empty. *<p> * NOTE: replaces {@link #isEmpty(Object)}, which was deprecated in 2.5 * * @since 2.5 */ public boolean isEmpty(SerializerProvider provider, T value) { return (value == null); } /** * Method that can be called to see whether this serializer instance * will use Object Id to handle cyclic references. */ public boolean usesObjectId() { return false; } /** * Accessor for checking whether this serializer is an * "unwrapping" serializer; this is necessary to know since * it may also require caller to suppress writing of the * leading property name. */ public boolean isUnwrappingSerializer() { return false; } /** * Accessor that can be used to determine if this serializer uses * another serializer for actual serialization, by delegating * calls. If so, will return immediate delegate (which itself may * delegate to further serializers); otherwise will return null. * * @return Serializer this serializer delegates calls to, if null; * null otherwise. * * @since 2.1 */ public JsonSerializer<?> getDelegatee() { return null; } /** * Accessor for iterating over logical properties that the type * handled by this serializer has, from serialization perspective. * Actual type of properties, if any, will be * {@link com.fasterxml.jackson.databind.ser.BeanPropertyWriter}. * Of standard Jackson serializers, only {@link com.fasterxml.jackson.databind.ser.BeanSerializer} * exposes properties. * * @since 2.6 */ public Iterator<PropertyWriter> properties() { return ClassUtil.emptyIterator(); } /** * Default implementation simply calls {@link JsonFormatVisitorWrapper#expectAnyFormat(JavaType)}. * * @since 2.1 */ @Override public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType type) throws JsonMappingException { visitor.expectAnyFormat(type); } /** * This marker class is only to be used with annotations, to * indicate that <b>no serializer is configured</b>. *<p> * Specifically, this class is to be used as the marker for * annotation {@link com.fasterxml.jackson.databind.annotation.JsonSerialize}. */ public abstract static class None extends JsonSerializer<Object> { } }
package com.github.horrorho.liquiddonkey.cloud; import com.github.horrorho.liquiddonkey.cloud.data.Backup; import com.github.horrorho.liquiddonkey.cloud.data.Account; import com.github.horrorho.liquiddonkey.cloud.data.Accounts; import com.github.horrorho.liquiddonkey.cloud.data.Auth; import com.github.horrorho.liquiddonkey.cloud.data.Backups; import com.github.horrorho.liquiddonkey.cloud.data.Core; import com.github.horrorho.liquiddonkey.cloud.data.Cores; import com.github.horrorho.liquiddonkey.cloud.data.Snapshot; import com.github.horrorho.liquiddonkey.cloud.data.Snapshots; import com.github.horrorho.liquiddonkey.cloud.file.FileFilter; import com.github.horrorho.liquiddonkey.cloud.file.LocalFileFilter; import com.github.horrorho.liquiddonkey.cloud.keybag.KeyBagManager; import com.github.horrorho.liquiddonkey.cloud.protobuf.ICloud; import com.github.horrorho.liquiddonkey.exception.BadDataException; import com.github.horrorho.liquiddonkey.http.HttpClientFactory; import com.github.horrorho.liquiddonkey.settings.config.Config; import com.github.horrorho.liquiddonkey.util.MemMonitor; import com.github.horrorho.liquiddonkey.util.Printer; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.stream.Collectors; import net.jcip.annotations.ThreadSafe; import org.apache.http.client.HttpClient; import org.apache.http.client.HttpResponseException; import org.apache.http.impl.client.CloseableHttpClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Looter. * * @author ahseya */ @ThreadSafe public final class Looter implements Closeable { public static Looter from(Config config, Printer std, Printer err, InputStream in) { logger.trace("<< from()"); CloseableHttpClient client = HttpClientFactory.from(config.http()).client(); FileFilter fileFilter = FileFilter.from(config.fileFilter()); Looter looter = new Looter(config, client, std, err, in, OutcomesPrinter.from(std, err), fileFilter); logger.trace(">> from()"); return looter; } private static final Logger logger = LoggerFactory.getLogger(Looter.class); private final Config config; private final CloseableHttpClient client; private final Printer std; private final Printer err; private final InputStream in; private final OutcomesPrinter outcomesPrinter; private final FileFilter filter; private final boolean isAggressive = true; Looter( Config config, CloseableHttpClient client, Printer std, Printer err, InputStream in, OutcomesPrinter outcomesPrinter, FileFilter filter) { this.config = Objects.requireNonNull(config); this.client = Objects.requireNonNull(client); this.std = Objects.requireNonNull(std); this.err = Objects.requireNonNull(err); this.in = Objects.requireNonNull(in); this.outcomesPrinter = Objects.requireNonNull(outcomesPrinter); this.filter = Objects.requireNonNull(filter); } public void loot() throws BadDataException, IOException, InterruptedException { logger.trace("<< loot()"); std.println("Authenticating."); // Authenticate Auth auth = config.authentication().hasIdPassword() ? Auth.from(client, config.authentication().id(), config.authentication().password()) : Auth.from(config.authentication().dsPrsID(), config.authentication().mmeAuthToken()); if (config.engine().toDumpToken()) { std.println("Authorization token: " + auth.dsPrsID() + ":" + auth.mmeAuthToken()); return; } // Core settings. Core core = Cores.from(client, auth); std.println("AppleId: " + core.appleId()); std.println("Full name: " + core.fullName()); std.println(); // Use Core auth, it may have a newer mmeAuthToken. Authenticator authenticator = Authenticator.from(core.auth()); // HttpAgent. HttpAgent agent = HttpAgent.from(client, config.engine().retryCount(), config.engine().retryDelayMs(), authenticator); // Account. Account account = agent.execute((c, mmeAuthToken) -> Accounts.from(c, core, mmeAuthToken)); // Available backups. List<Backup> backups = agent.execute((c, mmeAuthToken) -> Backups.from(c, core, mmeAuthToken, account)); // Filter backups. List<Backup> selected = BackupSelector.from(config.selection().udids(), Backup::mbsBackup, BackupFormatter.create(), std, in) .apply(backups); // Fetch backups. for (Backup backup : selected) { if (config.debug().toMonitorMemory()) { monitoredBackup(client, core, agent, backup); } else { backup(client, core, agent, backup); } } logger.trace(">> loot()"); } void monitoredBackup(HttpClient client, Core core, HttpAgent agent, Backup backup) throws BadDataException, IOException, InterruptedException { // Potential for large scale memory leakage. Lightweight memory usage reporting. MemMonitor memMonitor = MemMonitor.from(5000); try { Thread thread = new Thread(memMonitor); thread.setDaemon(true); thread.start(); // Fetch backup. backup(client, core, agent, backup); } finally { memMonitor.kill(); logger.debug("-- loot() > max sampled memory used (MB): {}", memMonitor.max() / 1048510); } } void backup(HttpClient client, Core core, HttpAgent agent, Backup backup) throws BadDataException, IOException, InterruptedException { logger.info("-- backup() > udid: {}", backup.backupUDID()); std.println("Retrieving backup: " + backup.backupUDID()); // Available snapshots SnapshotIdReferences references = SnapshotIdReferences.from(backup.mbsBackup()); logger.debug("-- backup() > requested ids: {}", config.selection().snapshots()); // Resolve snapshots with configured selection Set<Integer> resolved = config.selection().snapshots() .stream() .map(references::applyAsInt). filter(id -> id != -1) .collect(Collectors.toCollection(LinkedHashSet::new)); logger.debug("-- backup() > resolved ids: {}", resolved); // Fetch snapshots for (int id : resolved) { try { logger.info("-- backup() > snapshot: {}", id); snapshot(client, core, agent, backup, id); } catch (IOException ex) { if (ex instanceof HttpResponseException) { if (((HttpResponseException) ex).getStatusCode() == 401) { // Authentication failure. throw ex; } } if (isAggressive && !agent.authenticatorIsInvalid()) { logger.warn("-- backup() > exception: {}", ex); } else { throw ex; } } } } void snapshot(HttpClient client, Core core, HttpAgent agent, Backup backup, int id) throws BadDataException, IOException, InterruptedException { // Retrieve file list. int limit = config.client().listLimit(); Snapshot snapshot = agent.execute((c, mmeAuthToken) -> Snapshots.from(c, core, mmeAuthToken, backup, id, limit)); if (snapshot == null) { logger.warn("-- snapshot() > snapshot not found: {}", id); return; } ICloud.MBSSnapshotAttributes attr = snapshot.mbsSnapshot().getAttributes(); logger.info("-- snapshot() > files: {}", snapshot.filesCount()); std.println("Retrieving snapshot: " + id + " (" + attr.getDeviceName() + " " + attr.getProductVersion() + ")"); // Total files std.println("Files(total): " + snapshot.filesCount()); // Non-empty files snapshot = Snapshots.from(snapshot, file -> file.getSize() != 0 && file.hasSignature()); logger.info("-- filter() > filtered non empty, remaining: {}", snapshot.filesCount()); std.println("Files(non-empty): " + snapshot.filesCount()); // User filter snapshot = Snapshots.from(snapshot, filter); logger.info("-- filter() > filtered configured, remaining: {}", snapshot.filesCount()); std.println("Files(filtered): " + snapshot.filesCount()); // Undecryptable filter Snapshot filtered = snapshot; KeyBagManager keyBagManager = backup.keyBagManager(); Predicate<ICloud.MBSFile> undecryptableFilter = file -> !file.getAttributes().hasEncryptionKey() || keyBagManager.fileKey(file) != null; snapshot = Snapshots.from(snapshot, undecryptableFilter); Set<ICloud.MBSFile> undecryptables = filtered.files(); undecryptables.removeAll(snapshot.files()); logger.info("-- filter() > filtered undecryptable, remaining: {}", snapshot.filesCount()); std.println("Files(non-undecryptable): " + snapshot.filesCount()); // Local filter if (config.engine().toForceOverwrite()) { logger.debug("-- filter() > forced overwrite"); } else { long a = System.currentTimeMillis(); snapshot = LocalFileFilter.from(snapshot, config.file()).apply(snapshot); long b = System.currentTimeMillis(); logger.info("-- filter() > filtered local, remaining: {} delay(ms): {}", snapshot.filesCount(), b - a); std.println("Files(non-local): " + snapshot.filesCount()); } // Retrieve Outcomes outcomes = Outcomes.create(); OutcomesProgress progress = OutcomesProgress.from(snapshot, std); Consumer<Map<ICloud.MBSFile, Outcome>> outcomesConsumer = outcomes.andThen(progress); std.println("Retrieving files: " + snapshot.filesCount()); // Dump undecryptables // Map<ICloud.MBSFile, Outcome> undecryptableOutcomes = undecryptables.stream() // .collect(Collectors.toMap(Function.identity(), file -> Outcome.FAILED_DECRYPT_NO_KEY)); // outcomesConsumer.accept(undecryptableOutcomes); // Fetch files SnapshotDownloader.from(config.engine(), config.file()) .download(agent, core, snapshot, outcomesConsumer); std.println("Completed:"); outcomes.print(std); std.println(); } @Override public void close() throws IOException { client.close(); } }
package com.github.kratorius.cuckoohash; import java.util.*; @SuppressWarnings("WeakerAccess") public class CuckooHashMap<K, V> extends AbstractMap<K, V> implements Map<K, V> { // TODO implement Cloneable, Serializable and fail fast iterators. private static final int THRESHOLD_LOOP = 8; private static final int DEFAULT_START_SIZE = 16; private static final float DEFAULT_LOAD_FACTOR = 0.45f; private int defaultStartSize = DEFAULT_START_SIZE; private float loadFactor = DEFAULT_LOAD_FACTOR; private final HashFunctionFactory hashFunctionFactory; private HashFunction hashFunction1; private HashFunction hashFunction2; private int size = 0; /** * Immutable container of entries in the map. */ private static class MapEntry<V1> { final Object key; final V1 value; MapEntry(final Object key, final V1 value) { this.key = key; this.value = value; } } /** * Used as an internal key in the internal map in place of `null` keys supplied * by the user. * * We're only interested in this object's hashcode. The `equals` method * is used for convenience over implementing the same checks in the actual * hashmap implementation and makes for an elegant implementation. */ private static final Object KEY_NULL = new Object() { @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") @Override public boolean equals(Object obj) { return obj == this || obj == null; } }; public interface HashFunction { int hash(Object obj); } public interface HashFunctionFactory { HashFunction generate(int buckets); } private static class DefaultHashFunctionFactory implements HashFunctionFactory { private static final Random RANDOM = new Random(); private static class DefaultHashFunction implements HashFunction { final int a; final int b; final int hashBits; DefaultHashFunction(int a, int b, int buckets) { if (a == 0 || b == 0) { throw new IllegalArgumentException("a and b cannot be 0"); } this.a = a; this.b = b; // Find the position of the most-significant bit; this will determine the number of bits // we need to set in the hash function. int lgBuckets = -1; while (buckets > 0) { lgBuckets++; buckets >>>= 1; } hashBits = lgBuckets; } @Override public int hash(Object obj) { final int h = obj.hashCode(); // Split into two 16 bit words. final int upper = h & 0xFFFF0000; final int lower = h & 0x0000FFFF; // Shift the product down so that only `hashBits` bits remain in the output. return (upper * a + lower * b) >>> (32 - hashBits); } } @Override public HashFunction generate(int buckets) { return new DefaultHashFunction(RANDOM.nextInt(), RANDOM.nextInt(), buckets); } } private MapEntry<V>[] T1; private MapEntry<V>[] T2; /** * Constructs an empty <tt>CuckooHashMap</tt> with the default initial capacity (16). */ public CuckooHashMap() { this(DEFAULT_START_SIZE, DEFAULT_LOAD_FACTOR, new DefaultHashFunctionFactory()); } /** * Constructs an empty <tt>CuckooHashMap</tt> with the specified initial capacity. * The given capacity will be rounded to the nearest power of two. * * @param initialCapacity the initial capacity. */ public CuckooHashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR, new DefaultHashFunctionFactory()); } /** * Constructs an empty <tt>CuckooHashMap</tt> with the specified load factor. * * The load factor will cause the Cuckoo hash map to double in size when the number * of items it contains has filled up more than <tt>loadFactor</tt>% of the available * space. * * @param loadFactor the load factor. */ public CuckooHashMap(float loadFactor) { this(DEFAULT_START_SIZE, loadFactor, new DefaultHashFunctionFactory()); } @SuppressWarnings("unchecked") public CuckooHashMap(int initialCapacity, float loadFactor, HashFunctionFactory hashFunctionFactory) { if (initialCapacity <= 0) { throw new IllegalArgumentException("initial capacity must be strictly positive"); } if (loadFactor <= 0.f || loadFactor > 1.f) { throw new IllegalArgumentException("load factor must be a value in the (0.0f, 1.0f] range."); } initialCapacity = roundPowerOfTwo(initialCapacity); defaultStartSize = initialCapacity; // Capacity is meant to be the total capacity of the two internal tables. T1 = new MapEntry[initialCapacity / 2]; T2 = new MapEntry[initialCapacity / 2]; this.loadFactor = loadFactor; this.hashFunctionFactory = hashFunctionFactory; regenHashFunctions(initialCapacity / 2); } @Override public boolean containsKey(Object key) { return get(key) != null; } @Override public V get(Object key) { return get(key, null); } @SuppressWarnings("Since15") @Override public V getOrDefault(Object key, V defaultValue) { return get(key, defaultValue); } private V get(Object key, V defaultValue) { Object actualKey = (key != null ? key : KEY_NULL); MapEntry<V> v1 = T1[hashFunction1.hash(actualKey)]; MapEntry<V> v2 = T2[hashFunction2.hash(actualKey)]; if (v1 == null && v2 == null) { return defaultValue; } else if (v1 != null && v1.key.equals(actualKey)) { return v1.value; } else if (v2 != null && v2.key.equals(actualKey)) { return v2.value; } return defaultValue; } @SuppressWarnings("unchecked") @Override public V put(K key, V value) { Object actualKey = (key != null ? key : KEY_NULL); final V old = get(actualKey); if (old == null) { // If we need to grow after adding this item, it's probably best to grow before we add it. final float currentLoad = (size() + 1) / (T1.length + T2.length); if (currentLoad >= loadFactor) { grow(); } } MapEntry<V> v; while ((v = putSafe(actualKey, value)) != null) { actualKey = v.key; value = v.value; if (!rehash()) { grow(); } } if (old == null) { // Do not increase the size if we're replacing the item. size++; } return old; } /** * @return the key we failed to move because of collisions or <tt>null</tt> if * successful. */ private MapEntry<V> putSafe(Object key, V value) { MapEntry<V> newV, t1, t2; int loop = 0; while (loop++ < THRESHOLD_LOOP) { newV = new MapEntry<>(key, value); t1 = T1[hashFunction1.hash(key)]; t2 = T2[hashFunction2.hash(key)]; // Check if we must just update the value first. if (t1 != null && t1.key.equals(key)) { T1[hashFunction1.hash(key)] = newV; return null; } if (t2 != null && t2.key.equals(key)) { T2[hashFunction2.hash(key)] = newV; return null; } // We're intentionally biased towards adding items in T1 since that leads to // slightly faster successful lookups. if (t1 == null) { T1[hashFunction1.hash(key)] = newV; return null; } else if (t2 == null) { T2[hashFunction2.hash(key)] = newV; return null; } else { // Both tables have an item in the required position, we need to move things around. // Prefer always moving from T1 for simplicity. key = t1.key; value= t1.value; T1[hashFunction1.hash(key)] = newV; } } return new MapEntry<>(key, value); } @Override public V remove(Object key) { // TODO halve the size of the hashmap when we delete enough keys. Object actualKey = (key != null ? key : KEY_NULL); MapEntry<V> v1 = T1[hashFunction1.hash(actualKey)]; MapEntry<V> v2 = T2[hashFunction2.hash(actualKey)]; V oldValue; if (v1 != null && v1.key.equals(actualKey)) { oldValue = T1[hashFunction1.hash(actualKey)].value; T1[hashFunction1.hash(actualKey)] = null; size return oldValue; } if (v2 != null && v2.key.equals(actualKey)) { oldValue = T2[hashFunction2.hash(actualKey)].value; T2[hashFunction2.hash(actualKey)] = null; size return oldValue; } return null; } @SuppressWarnings("unchecked") @Override public void clear() { size = 0; T1 = new MapEntry[defaultStartSize / 2]; T2 = new MapEntry[defaultStartSize / 2]; } private void regenHashFunctions(final int size) { hashFunction1 = hashFunctionFactory.generate(size); hashFunction2 = hashFunctionFactory.generate(size); } /** * Double the size of the map until we can successfully manage to re-add all the items * we currently contain. */ private void grow() { int newSize = T1.length; do { newSize <<= 1; } while (!grow(newSize)); } @SuppressWarnings("unchecked") private boolean grow(final int newSize) { // Save old state as we may need to restore it if the grow fails. MapEntry<V>[] oldT1 = T1; MapEntry<V>[] oldT2 = T2; HashFunction oldH1 = hashFunction1; HashFunction oldH2 = hashFunction2; // Already point T1 and T2 to the new tables since putSafe operates on them. T1 = new MapEntry[newSize]; T2 = new MapEntry[newSize]; regenHashFunctions(newSize); for (int i = 0; i < oldT1.length; i++) { if (oldT1[i] != null) { if (putSafe(oldT1[i].key, oldT1[i].value) != null) { T1 = oldT1; T2 = oldT2; hashFunction1 = oldH1; hashFunction2 = oldH2; return false; } } if (oldT2[i] != null) { if (putSafe(oldT2[i].key, oldT2[i].value) != null) { T1 = oldT1; T2 = oldT2; hashFunction1 = oldH1; hashFunction2 = oldH2; return false; } } } return true; } @SuppressWarnings("unchecked") private boolean rehash() { // Save old state as we may need to restore it if the grow fails. MapEntry<V>[] oldT1 = T1; MapEntry<V>[] oldT2 = T2; HashFunction oldH1 = hashFunction1; HashFunction oldH2 = hashFunction2; boolean success; for (int threshold = 0; threshold < THRESHOLD_LOOP; threshold++) { success = true; hashFunction1 = hashFunctionFactory.generate(T1.length); hashFunction2 = hashFunctionFactory.generate(T1.length); // Already point T1 and T2 to the new tables since putSafe operates on them. T1 = new MapEntry[oldT1.length]; T2 = new MapEntry[oldT2.length]; for (int i = 0; i < oldT1.length; i++) { if (oldT1[i] != null) { if (putSafe(oldT1[i].key, oldT1[i].value) != null) { // Restore state, we need to change hash function. T1 = oldT1; T2 = oldT2; hashFunction1 = oldH1; hashFunction2 = oldH2; success = false; break; } } if (oldT2[i] != null) { if (putSafe(oldT2[i].key, oldT2[i].value) != null) { // Restore state, we need to change hash function. T1 = oldT1; T2 = oldT2; hashFunction1 = oldH1; hashFunction2 = oldH2; success = false; break; } } } if (success) { return true; } } return false; } @Override public int size() { return size; } @Override public boolean isEmpty() { return size == 0; } @Override public void putAll(Map<? extends K, ? extends V> m) { for (Map.Entry<? extends K, ? extends V> entry : m.entrySet()) { put(entry.getKey(), entry.getValue()); } } @SuppressWarnings("unchecked") @Override public Set<K> keySet() { Set<K> set = new HashSet<>(size); for (int i = 0; i < T1.length; i++) { if (T1[i] != null) { if (KEY_NULL.equals(T1[i].key)) { set.add(null); } else { set.add((K) T1[i].key); } } if (T2[i] != null) { if (KEY_NULL.equals(T2[i].key)) { set.add(null); } else { set.add((K) T2[i].key); } } } return set; } @Override public Collection<V> values() { List<V> values = new ArrayList<>(size); // Since we must not return the values in a specific order, it's more efficient to // iterate over each array individually so we can exploit cache locality rather than // reuse the index over T1 and T2. for (int i = 0; i < T1.length; i++) { if (T1[i] != null) { values.add(T1[i].value); } } for (int i = 0; i < T2.length; i++) { if (T2[i] != null) { values.add(T2[i].value); } } return values; } @Override public Set<Entry<K, V>> entrySet() { Set<Entry<K, V>> entrySet = new HashSet<>(size); for (K key : keySet()) { entrySet.add(new SimpleEntry<>(key, get(key))); } return entrySet; } @Override public boolean containsValue(Object value) { for (int i = 0; i < T1.length; i++) { if (T1[i] != null && T1[i].value.equals(value)) { return true; } } for (int i = 0; i < T2.length; i++) { if (T2[i] != null && T2[i].value.equals(value)) { return true; } } return false; } private static int roundPowerOfTwo(int n) { n n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; return (n < 0) ? 1 : n + 1; } }
package com.gordon_from_blumberg.utils; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Properties; /** * Util class for work with properties files */ public class ProperiesUtils { private static final String PROPERTIES_ENCODING = "ISO8859-1"; /** * Reads properties file * * @param file File with properties * @return Properties object * @throws RuntimeException if the IO exception is thrown during file reading */ public static Properties readProperties(File file) { Properties properties = new Properties(); try (FileInputStream inputStream = new FileInputStream(file)) { properties.load(inputStream); inputStream.close(); return properties; } catch(IOException e) { throw new RuntimeException(e); } } /** * Finds property in the passed properties object by the specified key * @param properties Properties object * @param key Property key * @return Found property value or empty string */ public static String getProperty(Properties properties, String key) { String property = properties.getProperty(key); return property != null ? convert(property) : ""; } /** * Finds property by the specified key in the specified file * @param file Properties file * @param key Property key * @return Found property value or empty string */ public static String getProperty(File file, String key) { return getProperty(readProperties(file), key); } private static String convert(String string) { try { return new String(string.getBytes(PROPERTIES_ENCODING)); } catch(UnsupportedEncodingException e) { throw new RuntimeException(e); } } }
package com.kryptnostic.v2.api; import java.util.UUID; import com.kryptnostic.v2.constants.Names; import retrofit.http.GET; import retrofit.http.Path; public interface ObjectAuthorizationApi { String CONTROLLER = "/access"; String READERS_PATH = "/readers"; String WRITERS_PATH = "/writers"; String OWNERS_PATH = "/owners"; String ID = Names.ID_FIELD; String OBJECT_ID_PATH = "/{" + ID + "}"; String FULL_READERS_PATH = READERS_PATH + OBJECT_ID_PATH; String FULL_WRITERS_PATH = WRITERS_PATH + OBJECT_ID_PATH; String FULL_OWNERS_PATH = OWNERS_PATH + OBJECT_ID_PATH; @GET( CONTROLLER + FULL_READERS_PATH ) Iterable<UUID> getUsersWithReadAccess( @Path( ID ) UUID objectId); @GET( CONTROLLER + FULL_WRITERS_PATH ) Iterable<UUID> getUsersWithWriteAccess( @Path( ID ) UUID objectId); @GET( CONTROLLER + FULL_OWNERS_PATH ) Iterable<UUID> getUsersWithOwnerAccess( @Path( ID ) UUID objectId); }
package com.lazerycode.selenium.extract; import com.lazerycode.selenium.exceptions.ExpectedFileNotFoundException; import com.lazerycode.selenium.repository.BinaryType; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.ArchiveInputStream; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipFile; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.input.CloseShieldInputStream; import org.apache.log4j.Logger; import org.apache.maven.plugin.MojoFailureException; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Enumeration; import static com.lazerycode.selenium.extract.DownloadableFileType.TAR; public class FileExtractor { private static final Logger LOG = Logger.getLogger(FileExtractor.class); private final boolean overwriteFilesThatExist; /** * @param overwriteFilesThatExist Overwrite any existing files */ public FileExtractor(boolean overwriteFilesThatExist) { this.overwriteFilesThatExist = overwriteFilesThatExist; } public String extractFileFromArchive(File downloadedCompressedFile, String extractedToFilePath, BinaryType possibleFilenames) throws IOException, IllegalArgumentException, MojoFailureException { DownloadableFileType fileType = DownloadableFileType.valueOf(FilenameUtils.getExtension(downloadedCompressedFile.getName()).toUpperCase()); LOG.debug("Determined archive type: " + fileType); LOG.debug("Overwrite files that exist: " + overwriteFilesThatExist); switch (fileType) { case GZ: case BZ2: CompressedFile compressedFile = new CompressedFile(downloadedCompressedFile); if (null != compressedFile.getArchiveType() && compressedFile.getArchiveType().equals(TAR)) { return untarFile(compressedFile.getInputStream(), extractedToFilePath, possibleFilenames); } else { return copyFileToDisk(compressedFile.getInputStream(), extractedToFilePath, compressedFile.getDecompressedFilename()); } case ZIP: return unzipFile(downloadedCompressedFile, extractedToFilePath, possibleFilenames); case EXE: if (possibleFilenames.getBinaryFilenames().contains(downloadedCompressedFile.getName())) { return copyFileToDisk(new FileInputStream(downloadedCompressedFile), extractedToFilePath, downloadedCompressedFile.getName()); } default: throw new IllegalArgumentException("." + fileType + " is an unsupported archive type"); } } /** * Unzip a downloaded zip file (this will implicitly overwrite any existing files) * * @param downloadedCompressedFile The downloaded zip file * @param extractedToFilePath Path to extracted file * @param possibleFilenames Names of the files we want to extract * @return boolean * @throws IOException IOException */ String unzipFile(File downloadedCompressedFile, String extractedToFilePath, BinaryType possibleFilenames) throws IOException, ExpectedFileNotFoundException { LOG.debug("Attempting to extract binary from .zip file..."); ArrayList<String> filenamesWeAreSearchingFor = possibleFilenames.getBinaryFilenames(); ZipFile zip = new ZipFile(downloadedCompressedFile); try { Enumeration<ZipArchiveEntry> zipFile = zip.getEntries(); if (filenamesWeAreSearchingFor.get(0).equals("*")) { filenamesWeAreSearchingFor.remove(0); LOG.debug("Extracting full archive"); return this.unzipFolder(zip, extractedToFilePath, filenamesWeAreSearchingFor); } else { while (zipFile.hasMoreElements()) { ZipArchiveEntry zipFileEntry = zipFile.nextElement(); for (String aFilenameWeAreSearchingFor : filenamesWeAreSearchingFor) { if (zipFileEntry.getName().endsWith(aFilenameWeAreSearchingFor)) { LOG.debug("Found: " + zipFileEntry.getName()); return copyFileToDisk(zip.getInputStream(zipFileEntry), extractedToFilePath, aFilenameWeAreSearchingFor); } } } } } finally { zip.close(); } throw new ExpectedFileNotFoundException("Unable to find any expected files for " + possibleFilenames.getBinaryTypeAsString()); } /** * Untar a decompressed tar file (this will implicitly overwrite any existing files) * * @param compressedFileInputStream The expanded tar file * @param extractedToFilePath Path to extracted file * @param possibleFilenames Names of the files we want to extract * @return boolean * @throws IOException MojoFailureException */ private String untarFile(InputStream compressedFileInputStream, String extractedToFilePath, BinaryType possibleFilenames) throws IOException, ExpectedFileNotFoundException { LOG.debug("Attempting to extract binary from a .tar file..."); ArchiveEntry currentFile; ArrayList<String> filenamesWeAreSearchingFor = possibleFilenames.getBinaryFilenames(); try { if (filenamesWeAreSearchingFor.contains("*")) { filenamesWeAreSearchingFor.remove(0); LOG.debug("Extracting full archive"); return this.untarFolder(compressedFileInputStream, extractedToFilePath, filenamesWeAreSearchingFor); } else { ArchiveInputStream archiveInputStream = new TarArchiveInputStream(compressedFileInputStream); while ((currentFile = archiveInputStream.getNextEntry()) != null) { for (String aFilenameWeAreSearchingFor : filenamesWeAreSearchingFor) { if (currentFile.getName().endsWith(aFilenameWeAreSearchingFor)) { LOG.debug("Found: " + currentFile.getName()); return copyFileToDisk(archiveInputStream, extractedToFilePath, aFilenameWeAreSearchingFor); } } } } } finally { compressedFileInputStream.close(); } throw new ExpectedFileNotFoundException( "Unable to find any expected filed for " + possibleFilenames.getBinaryTypeAsString()); } private String untarFolder(InputStream compressedFileInputStream, String destinationFolder, ArrayList<String> possibleFilenames) throws IOException { String executablePath = ""; ArchiveEntry currentFile; ArchiveInputStream archiveInputStream = new TarArchiveInputStream(compressedFileInputStream); CloseShieldInputStream notClosableArchiveInputStream = new CloseShieldInputStream(archiveInputStream); try { while ((currentFile = archiveInputStream.getNextEntry()) != null) { String name = currentFile.getName(); name = this.handlePathCreation(name, destinationFolder); if (name.length() > 0) { String extractedFile = copyFileToDisk(notClosableArchiveInputStream, destinationFolder, name); for (String expectedFileName : possibleFilenames) { if (extractedFile.endsWith(expectedFileName)) { executablePath = extractedFile; } } } } } finally { compressedFileInputStream.close(); notClosableArchiveInputStream.close(); } return executablePath; } private String unzipFolder(ZipFile zipFile, String destinationFolder, ArrayList<String> possibleFilenames) { String executablePath = ""; try { Enumeration<ZipArchiveEntry> entries = zipFile.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry zipEntry = entries.nextElement(); String name = zipEntry.getName(); name = this.handlePathCreation(name, destinationFolder); if (name.length() > 0) { String extractedFile = copyFileToDisk(zipFile.getInputStream(zipEntry), destinationFolder, name); for (String expectedFileName : possibleFilenames) { if (extractedFile.endsWith(expectedFileName)) { executablePath = extractedFile; } } } } } catch (IOException e) { LOG.error("Unzip failed:" + e.getMessage()); } finally { if (zipFile != null) { try { zipFile.close(); } catch (IOException e) { LOG.error("Error closing zip file"); } } } return executablePath; } /** * Copy a file from an inputsteam to disk * * @param inputStream A valid input stream to read * @param pathToExtractTo Path of the file we want to create * @param filename Filename of the file we want to create * @return Absolute path of the newly created file (Or existing file if overwriteFilesThatExist is set to false) * @throws IOException IOException */ private String copyFileToDisk(InputStream inputStream, String pathToExtractTo, String filename) throws IOException { if (!overwriteFilesThatExist) { File[] existingFiles = new File(pathToExtractTo).listFiles(); if (null != existingFiles && existingFiles.length > 0) { for (File existingFile : existingFiles) { String existingFilename = existingFile.getName(); if (existingFilename.equals(filename)) { LOG.info("Binary '" + existingFilename + "' exists: true"); LOG.info("Using existing '" + existingFilename + " 'binary."); return existingFile.getAbsolutePath(); } } } } File outputFile = new File(pathToExtractTo, filename); try { if (!outputFile.exists() && !outputFile.getParentFile().mkdirs() && !outputFile.createNewFile()) { throw new IOException("Unable to create " + outputFile.getAbsolutePath()); } LOG.info("Extracting binary '" + filename + "'..."); FileUtils.copyInputStreamToFile(inputStream, outputFile); LOG.info("Binary copied to " + outputFile.getAbsolutePath()); if (!outputFile.setExecutable(true) && !outputFile.canExecute()) { LOG.warn("Unable to set executable flag (+x) on " + filename); } } finally { inputStream.close(); } return outputFile.getAbsolutePath(); } private String handlePathCreation(String name, String destinationFolder) { name = name.replace('\\', '/'); File destinationFile = new File(destinationFolder, name); if (name.endsWith("/")) { if (!destinationFile.isDirectory() && !destinationFile.mkdirs()) { LOG.error("Error creating temp directory:" + destinationFile.getPath()); } return ""; } else { // Create the the parent directory if it doesn't exist File parentFolder = destinationFile.getParentFile(); if (!parentFolder.isDirectory()) { if (!parentFolder.mkdirs()) { LOG.error("Error creating temp directory:" + parentFolder.getPath()); } } return name; } } }
package com.lothrazar.cyclicmagic.spell; import com.lothrazar.cyclicmagic.util.UtilSound; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; public class SpellReplacer extends BaseSpell { public SpellReplacer(int id, String n) { super(id, n); this.cooldown = 1; } @Override public boolean cast(World world, EntityPlayer player, BlockPos pos, EnumFacing side) { if (pos == null || side == null) { return false; } if(!player.capabilities.allowEdit) { return false; } if (world.getBlockState(pos) == null || world.getBlockState(pos).getBlock() == null) { return false; } if(world.getTileEntity(pos) != null){ return false;//not chests, etc } //if there is a block here, we might have to stop IBlockState stateHere = world.getBlockState(pos); Block blockHere = stateHere.getBlock(); if(blockHere.getBlockHardness(world, pos) == -1){ return false; // is unbreakable-> like bedrock } int current = player.inventory.currentItem; if(current >= 9){ return false; } int slotFound = current + 1; ItemStack toPlace = player.inventory.getStackInSlot(slotFound); if(toPlace == null || toPlace.getItem() == null || Block.getBlockFromItem(toPlace.getItem()) == null){ return false; } //int toplaceMeta = toPlace.getMetadata() IBlockState placeState = Block.getBlockFromItem(toPlace.getItem()).getStateFromMeta(toPlace.getMetadata()); if(placeState.getBlock() == blockHere && blockHere.getMetaFromState(stateHere) == toPlace.getMetadata()){ return false;//dont replace cobblestone with cobblestone } if (world.destroyBlock(pos, true) && world.setBlockState(pos, placeState)) { //replacement worked! if(player.capabilities.isCreativeMode == false){ player.inventory.decrStackSize(slotFound, 1); player.inventoryContainer.detectAndSendChanges(); } if(placeState.getBlock().stepSound != null && placeState.getBlock().stepSound.getBreakSound() != null){ UtilSound.playSoundAt(player, placeState.getBlock().stepSound.getPlaceSound()); } return true; } return false; } @Override public void onCastSuccess(World world, EntityPlayer player, BlockPos pos) { //this is here to stop the default success sound from playing } }
package com.plivo.helper.api.response.account; import com.google.gson.annotations.SerializedName; public class Account { public String city ; public String name ; @SerializedName("cash_credits") public String cashCredits ; public String created ; public String enabled ; public String modified ; public String error ; @SerializedName("api_id") public String apiId ; public String postpaid ; public String state ; public String address ; public String timezone ; @SerializedName("auth_id") public String authID ; @SerializedName("resource_uri") public String resourceURI ; public Account() { // empty } }
package com.raphydaphy.vitality.render; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; import com.google.common.collect.ImmutableSet; import com.raphydaphy.vitality.api.spell.Spell; import com.raphydaphy.vitality.api.spell.SpellHelper; import com.raphydaphy.vitality.item.ItemSpell; import com.raphydaphy.vitality.item.ItemWand; import com.raphydaphy.vitality.network.MessageChangeSpell; import com.raphydaphy.vitality.network.PacketManager; import com.raphydaphy.vitality.registry.KeyBindings; import com.raphydaphy.vitality.util.RenderHelper; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.settings.KeyBinding; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; public class GUISpellSelect extends GuiScreen { private int activeSector = -1; private ItemStack wandStack; @Override public void drawScreen(int mx, int my, float partialTicks) { super.drawScreen(mx, my, partialTicks); List<Spell> spells = new ArrayList<Spell>() EntityPlayer player = Minecraft.getMinecraft().thePlayer; wandStack = player.getHeldItemMainhand(); if (!(wandStack.getItem() instanceof ItemWand)) { wandStack = player.getHeldItemOffhand(); if (!(wandStack.getItem() instanceof ItemWand)) { return; } } for (int i = 0; i < player.inventory.getSizeInventory(); i++) { // get the currently selected item in the players inventory ItemStack stackAt = player.inventory.getStackInSlot(i); // check that the current stack isnt null to prevent // NullPointerExceptions if (stackAt != null) { if (stackAt.getItem() instanceof ItemSpell) { if (!(spells.contains(((ItemSpell)stackAt.getItem()).toSpell()))) { spells.add(((ItemSpell)stackAt.getItem()).toSpell()); } } } } if (spells.size() > 0) { float angle = -90; int radius = 75; int amount = spells.size(); int screenWidth = width / 2; int screenHeight = height / 2; // if any spells are held in the bag if (amount > 0) { float anglePer; if (wandStack.getTagCompound().getString(Spell.ACTIVE_KEY) != "") { anglePer = 360F / (amount - 1); } else { anglePer = 360F / amount; } net.minecraft.client.renderer.RenderHelper.enableGUIStandardItemLighting(); GlStateManager.pushMatrix(); RenderHelper.renderCircle(screenWidth, screenHeight); GlStateManager.popMatrix(); activeSector = -1; for (int curItem = 0; curItem < spells.size(); curItem++) { if (spells.get(curItem).toString().equals(wandStack.getTagCompound().getString(Spell.ACTIVE_KEY))) { GlStateManager.pushMatrix(); GlStateManager.translate(screenWidth - 16, screenHeight - 16, 0); GlStateManager.scale(2, 2, 2); if (wandStack.getTagCompound().getString(Spell.ACTIVE_KEY) != "") { if (Spell.valueOf(wandStack.getTagCompound().getString(Spell.ACTIVE_KEY)).getAsItem() != null) { mc.getRenderItem().renderItemIntoGUI(new ItemStack(Spell.valueOf(wandStack.getTagCompound().getString(Spell.ACTIVE_KEY)).getAsItem()), 0, 0); } } GlStateManager.translate(-screenWidth, -screenHeight, 0); GlStateManager.popMatrix(); } else { double xPos = screenWidth + Math.cos(angle * Math.PI / 180D) * radius - 13.6; double yPos = screenHeight + Math.sin(angle * Math.PI / 180D) * radius - 13.6; // i got no clue what this shit does its been half a year since i wrote it xD if (mx > xPos && mx < xPos + 27.2 && my > yPos && my < yPos + 27.2) { activeSector = curItem; GlStateManager.pushMatrix(); GlStateManager.translate(xPos, yPos, 0); GlStateManager.scale(1.7, 1.7, 1.7); System.out.println(spells.get(curItem).getAsItem().getUnlocalizedName()); if (spells.get(curItem).getAsItem() != null) { mc.getRenderItem().renderItemIntoGUI(new ItemStack(spells.get(curItem).getAsItem()), 0, 0); } GlStateManager.translate(-xPos, -yPos, 0); GlStateManager.popMatrix(); } else { xPos = screenWidth + Math.cos(angle * Math.PI / 180D) * radius - 12; yPos = screenHeight + Math.sin(angle * Math.PI / 180D) * radius - 12; GlStateManager.pushMatrix(); GlStateManager.translate(xPos, yPos, 0); GlStateManager.scale(1.5, 1.5, 1.5); if (spells.get(curItem).getAsItem() != null) { mc.getRenderItem().renderItemIntoGUI(new ItemStack(spells.get(curItem).getAsItem()), 0, 0); } GlStateManager.translate(-xPos, -yPos, 0); GlStateManager.popMatrix(); } angle += anglePer; } } net.minecraft.client.renderer.RenderHelper.disableStandardItemLighting(); } } } @Override protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException { super.mouseClicked(mouseX, mouseY, mouseButton); if (activeSector != -1) { if (Minecraft.getMinecraft().thePlayer.getHeldItemMainhand() != null) { if (Minecraft.getMinecraft().thePlayer.getHeldItemMainhand().getItem() instanceof ItemWand) { Minecraft.getMinecraft().thePlayer.getHeldItemMainhand().getTagCompound().setString(Spell.ACTIVE_KEY, spells.get(activeSector).toString()); } } PacketManager.INSTANCE.sendToServer(new MessageChangeSpell(SpellHelper.getIDFromSpell(spells.get(activeSector)))); } } @Override public void updateScreen() { super.updateScreen(); if(!isKeyDown(KeyBindings.pickSpell)) { mc.displayGuiScreen(null); } ImmutableSet<KeyBinding> set = ImmutableSet.of(mc.gameSettings.keyBindForward, mc.gameSettings.keyBindLeft, mc.gameSettings.keyBindBack, mc.gameSettings.keyBindRight, mc.gameSettings.keyBindSneak, mc.gameSettings.keyBindSprint, mc.gameSettings.keyBindJump); for(KeyBinding k : set) { KeyBinding.setKeyBindState(k.getKeyCode(), isKeyDown(k)); } } public boolean isKeyDown(KeyBinding keybind) { int key = keybind.getKeyCode(); if(key < 0) { int button = 100 + key; return Mouse.isButtonDown(button); } return Keyboard.isKeyDown(key); } @Override public boolean doesGuiPauseGame() { return false; } }
package com.redhat.ceylon.compiler.js; import java.util.ArrayList; import java.util.Map; import java.util.Objects; import com.redhat.ceylon.compiler.typechecker.model.Class; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.Method; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.ProducedType; import com.redhat.ceylon.compiler.typechecker.model.Scope; import com.redhat.ceylon.compiler.typechecker.model.TypeAlias; import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration; import com.redhat.ceylon.compiler.typechecker.model.TypeParameter; import com.redhat.ceylon.compiler.typechecker.model.Util; import com.redhat.ceylon.compiler.typechecker.model.Value; import com.redhat.ceylon.compiler.typechecker.tree.Node; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.compiler.typechecker.tree.Tree.ValueLiteral; public class MetamodelHelper { static void generateOpenType(final Node that, Declaration d, final GenerateJsVisitor gen) { final Module m = d.getUnit().getPackage().getModule(); if (d instanceof TypeParameter == false) { if (JsCompiler.isCompilingLanguageModule()) { gen.out("$init$Open"); } else { gen.out(gen.getClAlias(), "Open"); } } if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) { gen.out("Interface$jsint"); } else if (d instanceof Class) { gen.out("Class$jsint"); } else if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Constructor) { gen.out("Constructor$jsint"); } else if (d instanceof Method) { gen.out("Function"); } else if (d instanceof Value) { gen.out("Value$jsint"); } else if (d instanceof com.redhat.ceylon.compiler.typechecker.model.IntersectionType) { gen.out("Intersection"); } else if (d instanceof com.redhat.ceylon.compiler.typechecker.model.UnionType) { gen.out("Union"); } else if (d instanceof TypeParameter) { generateOpenType(that, ((TypeParameter)d).getDeclaration(),gen); gen.out(".getTypeParameterDeclaration('", d.getName(), "')"); return; } else if (d instanceof com.redhat.ceylon.compiler.typechecker.model.NothingType) { gen.out("NothingType"); } else if (d instanceof TypeAlias) { gen.out("Alias$jsint("); if (JsCompiler.isCompilingLanguageModule()) { gen.out(")("); } if (d.isMember()) { //Make the chain to the top-level container ArrayList<Declaration> parents = new ArrayList<Declaration>(2); Declaration pd = (Declaration)d.getContainer(); while (pd!=null) { parents.add(0,pd); pd = pd.isMember()?(Declaration)pd.getContainer():null; } for (Declaration _d : parents) { gen.out(gen.getNames().name(_d), ".$$.prototype."); } } gen.out(gen.getNames().name(d), ")"); return; } //TODO optimize for local declarations if (JsCompiler.isCompilingLanguageModule()) { gen.out("()"); } gen.out("(", gen.getClAlias()); final String pkgname = d.getUnit().getPackage().getNameAsString(); if (Objects.equals(that.getUnit().getPackage().getModule(), d.getUnit().getPackage().getModule())) { gen.out("lmp$(ex$,'"); } else { //TODO use $ for language module as well gen.out("fmp$('", m.getNameAsString(), "','", m.getVersion(), "','"); } gen.out("ceylon.language".equals(pkgname) ? "$" : pkgname, "'),"); if (d.isMember()) { if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Constructor) { if (((Class)d.getContainer()).isMember()) { outputPathToDeclaration(that, (Class)d.getContainer(), gen); } else { gen.out(gen.getNames().name((Class)d.getContainer())); } gen.out("_", gen.getNames().name(d), ")"); return; } else { outputPathToDeclaration(that, d, gen); } } if (d instanceof Value) { if (!d.isMember()) gen.qualify(that, d); gen.out("$prop$", gen.getNames().getter(d), ")"); } else { if (d.isAnonymous()) { final String oname = gen.getNames().objectName(d); if (d.isToplevel()) { gen.qualify(that, d); } gen.out("$init$", oname); if (!d.isToplevel()) { gen.out("()"); } } else { if (!d.isMember()) gen.qualify(that, d); gen.out(gen.getNames().name(d)); } gen.out(")"); } } static void generateClosedTypeLiteral(final Tree.TypeLiteral that, final GenerateJsVisitor gen) { final ProducedType ltype = that.getType().getTypeModel(); final TypeDeclaration td = ltype.getDeclaration(); final Map<TypeParameter,ProducedType> targs = that.getType().getTypeModel().getTypeArguments(); if (td instanceof Class) { if (Util.getContainingClassOrInterface(td.getContainer()) == null) { gen.out(gen.getClAlias(), "$init$AppliedClass$meta$model()("); } else { gen.out(gen.getClAlias(), "$init$AppliedMemberClass$meta$model()("); } //Tuple is a special case, otherwise gets gen'd as {t:'T'... if (that.getUnit().getTupleDeclaration().equals(td)) { gen.qualify(that, td); gen.out(gen.getNames().name(td)); } else { TypeUtils.outputQualifiedTypename(null, gen.isImported(gen.getCurrentPackage(), td), ltype, gen, false); } gen.out(","); TypeUtils.printTypeArguments(that, that.getTypeModel().getTypeArguments(), gen, false, that.getTypeModel().getVarianceOverrides()); if (targs != null && !targs.isEmpty()) { gen.out(",undefined,"); TypeUtils.printTypeArguments(that, targs, gen, false, that.getType().getTypeModel().getVarianceOverrides()); } gen.out(")"); } else if (td instanceof com.redhat.ceylon.compiler.typechecker.model.Constructor) { Class _pc = (Class)td.getContainer(); if (_pc.isToplevel()) { gen.out(gen.getClAlias(), "$init$AppliedConstructor$jsint()("); } else { gen.out(gen.getClAlias(), "$init$AppliedMemberConstructor$jsint()("); } TypeUtils.outputQualifiedTypename(null, gen.isImported(gen.getCurrentPackage(), _pc), _pc.getType(), gen, false); gen.out("_", gen.getNames().name(td), ","); TypeUtils.printTypeArguments(that, that.getTypeModel().getTypeArguments(), gen, false, that.getTypeModel().getVarianceOverrides()); if (targs != null && !targs.isEmpty()) { gen.out(",undefined,"); TypeUtils.printTypeArguments(that, targs, gen, false, that.getType().getTypeModel().getVarianceOverrides()); } gen.out(")"); } else if (td instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) { if (td.isToplevel()) { gen.out(gen.getClAlias(), "$init$AppliedInterface$jsint()("); } else { gen.out(gen.getClAlias(), "$init$AppliedMemberInterface$meta$model()("); } TypeUtils.outputQualifiedTypename(null, gen.isImported(gen.getCurrentPackage(), td), ltype, gen, false); gen.out(","); TypeUtils.printTypeArguments(that, that.getTypeModel().getTypeArguments(), gen, false, that.getTypeModel().getVarianceOverrides()); if (targs != null && !targs.isEmpty()) { gen.out(",undefined,"); TypeUtils.printTypeArguments(that, targs, gen, false, that.getType().getTypeModel().getVarianceOverrides()); } gen.out(")"); } else if (td instanceof com.redhat.ceylon.compiler.typechecker.model.NothingType) { gen.out(gen.getClAlias(),"getNothingType$meta$model()"); } else if (that instanceof Tree.AliasLiteral) { gen.out("/*TODO: applied alias*/"); } else if (that instanceof Tree.TypeParameterLiteral) { gen.out("/*TODO: applied type parameter*/"); } else { gen.out(gen.getClAlias(), "typeLiteral$meta({Type$typeLiteral:"); TypeUtils.typeNameOrList(that, ltype, gen, false); gen.out("})"); } } static void generateMemberLiteral(final Tree.MemberLiteral that, final GenerateJsVisitor gen) { final com.redhat.ceylon.compiler.typechecker.model.ProducedReference ref = that.getTarget(); final ProducedType ltype = that.getType() == null ? null : that.getType().getTypeModel(); final Declaration d = ref.getDeclaration(); final Class anonClass = d.isMember()&&d.getContainer() instanceof Class && ((Class)d.getContainer()).isAnonymous()?(Class)d.getContainer():null; if (that instanceof Tree.FunctionLiteral || d instanceof Method) { gen.out(gen.getClAlias(), d.isMember()&&anonClass==null?"AppliedMethod$meta$model(":"AppliedFunction$meta$model("); if (ltype == null) { if (anonClass != null) { gen.qualify(that, anonClass); gen.out(gen.getNames().objectName(anonClass), "."); } else { gen.qualify(that, d); } } else { if (ltype.getDeclaration().isMember()) { outputPathToDeclaration(that, ltype.getDeclaration(), gen); } else { gen.qualify(that, ltype.getDeclaration()); } gen.out(gen.getNames().name(ltype.getDeclaration())); gen.out(".$$.prototype."); } if (d instanceof Value) { gen.out("$prop$", gen.getNames().getter(d), ","); } else { gen.out(gen.getNames().name(d),","); } if (d.isMember()&&anonClass==null) { if (that.getTypeArgumentList()!=null) { gen.out("["); boolean first=true; for (ProducedType targ : that.getTypeArgumentList().getTypeModels()) { if (first)first=false;else gen.out(","); gen.out(gen.getClAlias(),"typeLiteral$meta({Type$typeLiteral:"); TypeUtils.typeNameOrList(that, targ, gen, false); gen.out("})"); } gen.out("]"); gen.out(","); } else { gen.out("undefined,"); } TypeUtils.printTypeArguments(that, that.getTypeModel().getTypeArguments(), gen, false, that.getTypeModel().getVarianceOverrides()); } else { TypeUtils.printTypeArguments(that, that.getTypeModel().getTypeArguments(), gen, false, that.getTypeModel().getVarianceOverrides()); if (anonClass != null) { gen.out(","); gen.qualify(that, anonClass); gen.out(gen.getNames().objectName(anonClass)); } if (ref.getTypeArguments() != null && !ref.getTypeArguments().isEmpty()) { if (anonClass == null) { gen.out(",undefined"); } gen.out(","); TypeUtils.printTypeArguments(that, ref.getTypeArguments(), gen, false, ref.getType().getVarianceOverrides()); } } gen.out(")"); } else if (that instanceof ValueLiteral || d instanceof Value) { Value vd = (Value)d; if (vd.isMember() && anonClass==null) { gen.out(gen.getClAlias(), "$init$AppliedAttribute$meta$model()('"); gen.out(d.getName(), "',"); } else { gen.out(gen.getClAlias(), "$init$AppliedValue$jsint()("); if (anonClass == null) { gen.out("undefined"); } else { gen.qualify(that, anonClass); gen.out(gen.getNames().objectName(anonClass)); } gen.out(","); } if (ltype == null) { if (anonClass != null) { gen.qualify(that, anonClass); gen.out(gen.getNames().objectName(anonClass), "."); } else { gen.qualify(that, d); } } else { gen.qualify(that, ltype.getDeclaration()); gen.out(gen.getNames().name(ltype.getDeclaration())); gen.out(".$$.prototype."); } if (d instanceof Value) { gen.out("$prop$", gen.getNames().getter(d),","); } else { gen.out(gen.getNames().name(d),","); } TypeUtils.printTypeArguments(that, that.getTypeModel().getTypeArguments(), gen, false, that.getTypeModel().getVarianceOverrides()); gen.out(")"); } else { gen.out(gen.getClAlias(), "/*TODO:closed member literal*/typeLiteral$meta({Type$typeLiteral:"); gen.out("{t:"); if (ltype == null) { gen.qualify(that, d); } else { gen.qualify(that, ltype.getDeclaration()); gen.out(gen.getNames().name(ltype.getDeclaration())); gen.out(".$$.prototype."); } if (d instanceof Value) { gen.out("$prop$", gen.getNames().getter(d)); } else { gen.out(gen.getNames().name(d)); } if (ltype != null && ltype.getTypeArguments() != null && !ltype.getTypeArguments().isEmpty()) { gen.out(",a:"); TypeUtils.printTypeArguments(that, ltype.getTypeArguments(), gen, false, ltype.getVarianceOverrides()); } gen.out("}})"); } } static void findModule(final Module m, final GenerateJsVisitor gen) { gen.out(gen.getClAlias(), "getModules$meta().find('", m.getNameAsString(), "','", m.getVersion(), "')"); } static void outputPathToDeclaration(final Node that, final Declaration d, final GenerateJsVisitor gen) { final Declaration parent = Util.getContainingDeclaration(d); if (!gen.opts.isOptimize() && parent instanceof TypeDeclaration && Util.contains((Scope)parent, that.getScope())) { gen.out(gen.getNames().self((TypeDeclaration)parent), "."); } else { Declaration _md = d; final ArrayList<Declaration> parents = new ArrayList<>(3); while (_md.isMember()) { _md=Util.getContainingDeclaration(_md); parents.add(0, _md); } boolean first=true; boolean imported=false; for (Declaration _d : parents) { if (first){ imported = gen.qualify(that, _d); first=false; } if (_d.isAnonymous()) { final String oname = gen.getNames().objectName(_d); if (_d.isToplevel()) { gen.out(oname, "."); } else { gen.out("$init$", oname, "().$$.prototype."); } } else { if (!imported)gen.out("$init$"); gen.out(gen.getNames().name(_d), imported?".$$.prototype.":"().$$.prototype."); } imported=true; } } } }
package com.sonymobile.gitlab.model; /** * Access levels to a GitLab group for a group member. * * @author Emil Nilsson */ public enum GitLabAccessLevel { /** Not a member in a group. */ NONE ("None", 0), /** A guest in a group. */ GUEST ("Guest", 10), /** A reporter in a group. */ REPORTER ("Reporter", 20), /** A developer in a group. */ DEVELOPER ("Developer", 30), /** A master of a group. */ MASTER ("Master", 40), /** An owner of a group. */ OWNER ("Owner", 50); /** The name. */ private final String name; /** The unique ID. */ private final int id; /** Access levels by name. */ public static final String[] all = {OWNER.name, MASTER.name, DEVELOPER.name, REPORTER.name, GUEST.name}; /** * Creates an access level with a name and unique id * * @param name the name * @param id the unique ID */ private GitLabAccessLevel(String name, int id) { this.name = name; this.id = id; } @Override public String toString() { return name; } /** * Returns the access level for an ID * * @param id the unique ID */ public static GitLabAccessLevel accessLevelForId(int id) { for (GitLabAccessLevel accessLevel : GitLabAccessLevel.values()) { if (accessLevel.id == id) { return accessLevel; } } throw new IllegalArgumentException("Invalid access level ID"); } /** * Returns the access level with the given name. * * The method doesn't take upper or lower case into consideration. * * @param name the name * @return a GitLab access level */ public static GitLabAccessLevel getAccessLevelWithName(String name) { name = name.toUpperCase(); for (GitLabAccessLevel accessLevel : GitLabAccessLevel.values()) { if (name.equals(accessLevel.name())) { return accessLevel; } } throw new IllegalArgumentException("Invalid access level name"); } }
package com.sourcepulp.treespy.jse7; import static java.nio.file.LinkOption.NOFOLLOW_LINKS; import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE; import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE; import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY; import static java.nio.file.StandardWatchEventKinds.OVERFLOW; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.nio.file.FileSystems; import java.nio.file.FileVisitResult; import java.nio.file.FileVisitor; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.PathMatcher; import java.nio.file.SimpleFileVisitor; import java.nio.file.WatchEvent; import java.nio.file.WatchEvent.Kind; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.nio.file.attribute.BasicFileAttributes; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicBoolean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sourcepulp.treespy.Events; import com.sourcepulp.treespy.TreeSpy; import com.sourcepulp.treespy.TreeSpyListener; /** * Java SE 7 compliant implementation of a directory watching service. * * @author Will Faithfull * */ public class TreeSpyJSE7StdLib implements TreeSpy { private static final Logger log = LoggerFactory.getLogger(TreeSpy.class); private WatchService watcher; private ConcurrentMap<WatchKey, Path> watchKeysToDirectories; private ConcurrentMap<Path, Set<TreeSpyListener>> directoriesToListeners; private ConcurrentMap<TreeSpyListener, Set<PathMatcher>> callbacksToGlobMatchers; private AtomicBoolean running = new AtomicBoolean(false); private Executor daemonExecutor; private ExecutorService callbackExecutorService; private boolean runCallbacksOnDaemonThread = true; /** * Constructs a directory spy using the provided executor to orchestrate the * background task. * * @param daemonExecutor * @throws IOException */ public TreeSpyJSE7StdLib(Executor daemonExecutor) throws IOException { this.daemonExecutor = daemonExecutor; reset(); } /** * Constructs a directory spy using the provided executor to orchestrate the * background task, and the provided ExecutorService to execute callbacks. * * @param daemonExecutor * @param callbackExecutorService * @throws IOException */ public TreeSpyJSE7StdLib(Executor daemonExecutor, ExecutorService callbackExecutorService) throws IOException { this(daemonExecutor); this.callbackExecutorService = callbackExecutorService; runCallbacksOnDaemonThread = false; } /** * {@inheritDoc} */ public void reset() throws IOException { stop(); watcher = FileSystems.getDefault().newWatchService(); watchKeysToDirectories = new ConcurrentHashMap<WatchKey, Path>(); directoriesToListeners = new ConcurrentHashMap<Path, Set<TreeSpyListener>>(); callbacksToGlobMatchers = new ConcurrentHashMap<TreeSpyListener, Set<PathMatcher>>(); } /** * {@inheritDoc} */ public void watchRecursive(File directory, TreeSpyListener callback) throws IOException { this.watch(directory, callback, true); } /** * {@inheritDoc} */ public void watchJust(File directory, TreeSpyListener callback) throws IOException { this.watch(directory, callback, false); } /** * {@inheritDoc} */ public void watchRecursive(File directory, TreeSpyListener callback, String... globs) throws IOException { registerGlobs(callback, globs); this.watch(directory, callback, true); } /** * {@inheritDoc} */ public void watchJust(File directory, TreeSpyListener callback, String... globs) throws IOException { registerGlobs(callback, globs); this.watch(directory, callback, false); } private void watch(File directory, TreeSpyListener callback, boolean recursive) throws IOException { if (!directory.isDirectory()) throw new IllegalArgumentException("Path must be a directory"); Path path = directory.toPath(); if (!isWatched(path)) register(path, callback, recursive); if (!running.get()) start(); log.info(String.format("Watching %s%s", path.toString(), recursive ? " and subdirectories." : ".")); } private void registerGlobs(TreeSpyListener callback, String[] globs) { if (!callbacksToGlobMatchers.containsKey(callback)) callbacksToGlobMatchers.put(callback, new HashSet<PathMatcher>()); Set<PathMatcher> storedMatchers = callbacksToGlobMatchers.get(callback); for (String glob : globs) { if(!glob.startsWith("glob:")) glob = "glob:" + glob; PathMatcher matcher = FileSystems.getDefault().getPathMatcher(glob); storedMatchers.add(matcher); } } /** * Indicates whether the specified directory already has a matching * WatchKey. * * @param directory * The path to check. * @return True if there is an existing WatchKey for the path. */ private boolean isWatched(Path directory) { return watchKeysToDirectories.containsValue(directory); } /** * Indicates whether the specified directory already has attached listeners. * * @param directory * The path to check. * @return True if there are attached listeners to the path. */ private boolean isListened(Path directory) { if (directoriesToListeners.containsKey(directory)) return !directoriesToListeners.get(directory).isEmpty(); return false; } /** * Register the specified listener to the specified path, and recursively * all subdirectories, if specified by the boolean. * * @param path * The path to register the listener against. * @param listener * The listener to be registered. * @param all * Whether or not to recurse and register the listener against * all subdirectories of the specified path. * @throws IOException */ private void register(Path path, TreeSpyListener listener, boolean all) throws IOException { FileVisitor<Path> visitor = makeVisitor(listener); if (all) Files.walkFileTree(path, visitor); else visitor.preVisitDirectory(path, Files.readAttributes(path, BasicFileAttributes.class)); } /** * Creates a FileVisitor that registers the specified callback at all * directories it visits. * * @param listener * A callback to be registered at any directories the visitor * visits. * @return A FileVisitor implementation that registers the callback where it * visits. */ private FileVisitor<Path> makeVisitor(final TreeSpyListener listener) { return new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY, OVERFLOW); watchKeysToDirectories.put(key, dir); if (!isListened(dir)) directoriesToListeners.put(dir, new LinkedHashSet<TreeSpyListener>()); directoriesToListeners.get(dir).add(listener); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); exc.printStackTrace(pw); log.warn(sw.toString()); return FileVisitResult.SKIP_SUBTREE; } }; } /** * Attempts to notify all listeners of the specified key. * * @param key */ private void notifyAll(WatchKey key) { Path directory = watchKeysToDirectories.get(key); Set<TreeSpyListener> listeners = directoriesToListeners.get(directory); for (WatchEvent<?> event : key.pollEvents()) { // Find the directory or file referenced by this WatchEvent WatchEvent<Path> ev = cast(event); Path filename = ev.context(); Path child = directory.resolve(filename); Kind<?> kind = event.kind(); // Find out ahead of time if a new directory has been created. boolean newDirectory = kind == ENTRY_CREATE && Files.isDirectory(child, NOFOLLOW_LINKS); for (TreeSpyListener listener : listeners) { Events eventType = Events.kindToEvent(kind); // If users have particularly heavy or frequent tasks in // callbacks, this provides the option to pass them off to an // executor service rather than clogging up the daemon thread. if (this.runCallbacksOnDaemonThread) { notify(listener, child, eventType); } else { notifyAsync(listener, child, eventType); } // If a new directory was created, register it and any // subdirectories. if (newDirectory) { try { register(child, listener, true); } catch (IOException ex) { log.warn(String.format("Could not register %s", child.toString())); } } } // Reset key to allow subsequent monitoring. boolean valid = key.reset(); if (!valid) { log.warn(String.format("Invalid key - Directory %s is no longer accessible.", directory.toString())); watchKeysToDirectories.remove(key); } } } private void notifyAsync(final TreeSpyListener listener, final Path path, final Events eventType) { callbackExecutorService.execute(new Runnable() { @Override public void run() { TreeSpyJSE7StdLib.this.notify(listener, path, eventType); } }); } private void notify(final TreeSpyListener listener, final Path path, final Events eventType) { Set<PathMatcher> globs = callbacksToGlobMatchers.get(listener); // If there's no globs, continue and notify. If there's globs, but no // matches, continue and notify. Else, return and do nothing. if (!(globs == null || globs.isEmpty())) { if (!matches(globs, path)) { return; } } listener.onChange(path, eventType); } private boolean matches(Set<PathMatcher> globs, Path path) { for (PathMatcher glob : globs) { if (glob.matches(path)) return true; } return false; } /** * Unchecked cast method suggested by the Java 7 SE API documentation for * {@link java.nio.file.WatcherService} * * @param event * @return */ @SuppressWarnings("unchecked") private static <T> WatchEvent<T> cast(WatchEvent<?> event) { return (WatchEvent<T>) event; } /** * {@inheritDoc} */ public void start() { daemonExecutor.execute(new WatchServiceRunnable(this)); running.set(true); log.info("TreeSpy started spying."); } /** * {@inheritDoc} */ public void stop() { if (running.get()) { running.set(false); log.info("TreeSpy stopped spying."); } } /** * Runnable implementation for the background daemon thread. Can be lazily * killed by setting the AtomicBoolean in the outer class. * * @author wfaithfull * */ private class WatchServiceRunnable implements Runnable { TreeSpyJSE7StdLib spy; public WatchServiceRunnable(TreeSpyJSE7StdLib spy) { this.spy = spy; } public void run() { while (running.get()) { WatchKey key; try { key = spy.watcher.take(); } catch (InterruptedException ex) { log.error("Thread was interrupted unexpectedly", ex); return; } spy.notifyAll(key); } running.set(false); } } }
package com.stratio.qa.cucumber.testng; import cucumber.api.CucumberOptions; import cucumber.runtime.ClassFinder; import cucumber.runtime.CucumberException; import cucumber.runtime.RuntimeOptions; import cucumber.runtime.RuntimeOptionsFactory; import cucumber.runtime.io.MultiLoader; import cucumber.runtime.io.ResourceLoader; import cucumber.runtime.io.ResourceLoaderClassFinder; import org.reflections.Reflections; import java.io.File; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import java.util.Set; public class CucumberRunner { private final cucumber.runtime.Runtime runtime; @SuppressWarnings("unused") public CucumberRunner(Class<?> clazz, String... feature) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { ClassLoader classLoader = clazz.getClassLoader(); ResourceLoader resourceLoader = new MultiLoader(classLoader); RuntimeOptionsFactory runtimeOptionsFactory = new RuntimeOptionsFactory(clazz, new Class[]{CucumberOptions.class}); RuntimeOptions runtimeOptions = runtimeOptionsFactory.create(); String testSuffix = System.getProperty("TESTSUFFIX"); String targetExecutionsPath = "target/executions/"; if (testSuffix != null) { targetExecutionsPath = targetExecutionsPath + testSuffix + "/"; } boolean aux = new File(targetExecutionsPath).mkdirs(); CucumberReporter reporterTestNG; if ((feature.length == 0)) { reporterTestNG = new CucumberReporter(targetExecutionsPath, clazz.getCanonicalName(), ""); } else { List<String> features = new ArrayList<String>(); String fPath = "src/test/resources/features/" + feature[0] + ".feature"; features.add(fPath); runtimeOptions.getFeaturePaths().addAll(features); reporterTestNG = new CucumberReporter(targetExecutionsPath, clazz.getCanonicalName(), feature[0]); } List<String> uniqueGlue = new ArrayList<String>(); uniqueGlue.add("classpath:com/stratio/qa/specs"); uniqueGlue.add("classpath:com/stratio/sparta/testsAT/specs"); uniqueGlue.add("classpath:com/stratio/gosecsso/testsAT/specs"); uniqueGlue.add("classpath:com/stratio/dcos/crossdata/testsAT/specs"); uniqueGlue.add("classpath:com/stratio/crossdata/testsAT/specs"); uniqueGlue.add("classpath:com/stratio/streaming/testsAT/specs"); uniqueGlue.add("classpath:com/stratio/ingestion/testsAT/specs"); uniqueGlue.add("classpath:com/stratio/datavis/testsAT/specs"); uniqueGlue.add("classpath:com/stratio/connectors/testsAT/specs"); uniqueGlue.add("classpath:com/stratio/admin/testsAT/specs"); uniqueGlue.add("classpath:com/stratio/explorer/testsAT/specs"); uniqueGlue.add("classpath:com/stratio/manager/testsAT/specs"); uniqueGlue.add("classpath:com/stratio/viewer/testsAT/specs"); uniqueGlue.add("classpath:com/stratio/decision/testsAT/specs"); uniqueGlue.add("classpath:com/stratio/paas/testsAT/specs"); uniqueGlue.add("classpath:com/stratio/cassandra/lucene/testsAT/specs"); uniqueGlue.add("classpath:com/stratio/analytic/testsAT/specs"); uniqueGlue.add("classpath:com/stratio/exhibitor/testsAT/specs"); uniqueGlue.add("classpath:com/stratio/intelligence/testsAT/specs"); uniqueGlue.add("classpath:com/stratio/postgresbd/testsAT/specs"); runtimeOptions.getGlue().clear(); runtimeOptions.getGlue().addAll(uniqueGlue); runtimeOptions.addFormatter(reporterTestNG); Set<Class<? extends ICucumberFormatter>> implementers = new Reflections("com.stratio.tests.utils") .getSubTypesOf(ICucumberFormatter.class); for (Class<? extends ICucumberFormatter> implementerClazz : implementers) { Constructor<?> ctor = implementerClazz.getConstructor(); ctor.setAccessible(true); runtimeOptions.addFormatter((ICucumberFormatter) ctor.newInstance()); } ClassFinder classFinder = new ResourceLoaderClassFinder(resourceLoader, classLoader); runtime = new cucumber.runtime.Runtime(resourceLoader, classFinder, classLoader, runtimeOptions); } /** * Run the testclases(Features). * * @throws IOException */ public void runCukes() throws IOException { runtime.run(); if (!runtime.getErrors().isEmpty()) { throw new CucumberException(runtime.getErrors().get(0)); } } }
// File generated from our OpenAPI spec package com.stripe.param.checkout; import com.google.gson.annotations.SerializedName; import com.stripe.net.ApiRequestParams; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import lombok.Getter; @Getter public class SessionCreateParams extends ApiRequestParams { /** Enables user redeemable promotion codes. */ @SerializedName("allow_promotion_codes") Boolean allowPromotionCodes; /** Specify whether Checkout should collect the customer's billing address. */ @SerializedName("billing_address_collection") BillingAddressCollection billingAddressCollection; /** * The URL the customer will be directed to if they decide to cancel payment and return to your * website. */ @SerializedName("cancel_url") String cancelUrl; /** * A unique string to reference the Checkout Session. This can be a customer ID, a cart ID, or * similar, and can be used to reconcile the session with your internal systems. */ @SerializedName("client_reference_id") String clientReferenceId; /** * ID of an existing customer, if one exists. The email stored on the customer will be used to * prefill the email field on the Checkout page. If the customer changes their email on the * Checkout page, the Customer object will be updated with the new email. If blank for Checkout * Sessions in {@code payment} or {@code subscription} mode, Checkout will create a new customer * object based on information provided during the session. */ @SerializedName("customer") String customer; /** * If provided, this value will be used when the Customer object is created. If not provided, * customers will be asked to enter their email address. Use this parameter to prefill customer * data if you already have an email on file. To access information about the customer once a * session is complete, use the {@code customer} field. */ @SerializedName("customer_email") String customerEmail; /** * The coupon or promotion code to apply to this session. Currently, only up to one may be * specified. */ @SerializedName("discounts") List<Discount> discounts; /** Specifies which fields in the response should be expanded. */ @SerializedName("expand") List<String> expand; /** * Map of extra parameters for custom features not available in this client library. The content * in this map is not serialized under this field's {@code @SerializedName} value. Instead, each * key/value pair is serialized as if the key is a root-level field (serialized) name in this * param object. Effectively, this map is flattened to its parent instance. */ @SerializedName(ApiRequestParams.EXTRA_PARAMS_KEY) Map<String, Object> extraParams; @SerializedName("line_items") List<LineItem> lineItems; /** * The IETF language tag of the locale Checkout is displayed in. If blank or {@code auto}, the * browser's locale is used. */ @SerializedName("locale") Locale locale; @SerializedName("metadata") Map<String, String> metadata; /** * The mode of the Checkout Session, one of {@code payment}, {@code setup}, or {@code * subscription}. Required when using prices or {@code setup} mode. Pass {@code subscription} if * Checkout session includes at least one recurring item. */ @SerializedName("mode") Mode mode; /** * A subset of parameters to be passed to PaymentIntent creation for Checkout Sessions in {@code * payment} mode. */ @SerializedName("payment_intent_data") PaymentIntentData paymentIntentData; @SerializedName("payment_method_types") List<PaymentMethodType> paymentMethodTypes; /** * A subset of parameters to be passed to SetupIntent creation for Checkout Sessions in {@code * setup} mode. */ @SerializedName("setup_intent_data") SetupIntentData setupIntentData; /** * When set, provides configuration for Checkout to collect a shipping address from a customer. */ @SerializedName("shipping_address_collection") ShippingAddressCollection shippingAddressCollection; /** * Describes the type of transaction being performed by Checkout in order to customize relevant * text on the page, such as the submit button. {@code submit_type} can only be specified on * Checkout Sessions in {@code payment} mode, but not Checkout Sessions in {@code subscription} or * {@code setup} mode. */ @SerializedName("submit_type") SubmitType submitType; /** * A subset of parameters to be passed to subscription creation for Checkout Sessions in {@code * subscription} mode. */ @SerializedName("subscription_data") SubscriptionData subscriptionData; @SerializedName("success_url") String successUrl; private SessionCreateParams( Boolean allowPromotionCodes, BillingAddressCollection billingAddressCollection, String cancelUrl, String clientReferenceId, String customer, String customerEmail, List<Discount> discounts, List<String> expand, Map<String, Object> extraParams, List<LineItem> lineItems, Locale locale, Map<String, String> metadata, Mode mode, PaymentIntentData paymentIntentData, List<PaymentMethodType> paymentMethodTypes, SetupIntentData setupIntentData, ShippingAddressCollection shippingAddressCollection, SubmitType submitType, SubscriptionData subscriptionData, String successUrl) { this.allowPromotionCodes = allowPromotionCodes; this.billingAddressCollection = billingAddressCollection; this.cancelUrl = cancelUrl; this.clientReferenceId = clientReferenceId; this.customer = customer; this.customerEmail = customerEmail; this.discounts = discounts; this.expand = expand; this.extraParams = extraParams; this.lineItems = lineItems; this.locale = locale; this.metadata = metadata; this.mode = mode; this.paymentIntentData = paymentIntentData; this.paymentMethodTypes = paymentMethodTypes; this.setupIntentData = setupIntentData; this.shippingAddressCollection = shippingAddressCollection; this.submitType = submitType; this.subscriptionData = subscriptionData; this.successUrl = successUrl; } public static Builder builder() { return new Builder(); } public static class Builder { private Boolean allowPromotionCodes; private BillingAddressCollection billingAddressCollection; private String cancelUrl; private String clientReferenceId; private String customer; private String customerEmail; private List<Discount> discounts; private List<String> expand; private Map<String, Object> extraParams; private List<LineItem> lineItems; private Locale locale; private Map<String, String> metadata; private Mode mode; private PaymentIntentData paymentIntentData; private List<PaymentMethodType> paymentMethodTypes; private SetupIntentData setupIntentData; private ShippingAddressCollection shippingAddressCollection; private SubmitType submitType; private SubscriptionData subscriptionData; private String successUrl; /** Finalize and obtain parameter instance from this builder. */ public SessionCreateParams build() { return new SessionCreateParams( this.allowPromotionCodes, this.billingAddressCollection, this.cancelUrl, this.clientReferenceId, this.customer, this.customerEmail, this.discounts, this.expand, this.extraParams, this.lineItems, this.locale, this.metadata, this.mode, this.paymentIntentData, this.paymentMethodTypes, this.setupIntentData, this.shippingAddressCollection, this.submitType, this.subscriptionData, this.successUrl); } /** Enables user redeemable promotion codes. */ public Builder setAllowPromotionCodes(Boolean allowPromotionCodes) { this.allowPromotionCodes = allowPromotionCodes; return this; } /** Specify whether Checkout should collect the customer's billing address. */ public Builder setBillingAddressCollection(BillingAddressCollection billingAddressCollection) { this.billingAddressCollection = billingAddressCollection; return this; } /** * The URL the customer will be directed to if they decide to cancel payment and return to your * website. */ public Builder setCancelUrl(String cancelUrl) { this.cancelUrl = cancelUrl; return this; } /** * A unique string to reference the Checkout Session. This can be a customer ID, a cart ID, or * similar, and can be used to reconcile the session with your internal systems. */ public Builder setClientReferenceId(String clientReferenceId) { this.clientReferenceId = clientReferenceId; return this; } /** * ID of an existing customer, if one exists. The email stored on the customer will be used to * prefill the email field on the Checkout page. If the customer changes their email on the * Checkout page, the Customer object will be updated with the new email. If blank for Checkout * Sessions in {@code payment} or {@code subscription} mode, Checkout will create a new customer * object based on information provided during the session. */ public Builder setCustomer(String customer) { this.customer = customer; return this; } /** * If provided, this value will be used when the Customer object is created. If not provided, * customers will be asked to enter their email address. Use this parameter to prefill customer * data if you already have an email on file. To access information about the customer once a * session is complete, use the {@code customer} field. */ public Builder setCustomerEmail(String customerEmail) { this.customerEmail = customerEmail; return this; } /** * Add an element to `discounts` list. A list is initialized for the first `add/addAll` call, * and subsequent calls adds additional elements to the original list. See {@link * SessionCreateParams#discounts} for the field documentation. */ public Builder addDiscount(Discount element) { if (this.discounts == null) { this.discounts = new ArrayList<>(); } this.discounts.add(element); return this; } /** * Add all elements to `discounts` list. A list is initialized for the first `add/addAll` call, * and subsequent calls adds additional elements to the original list. See {@link * SessionCreateParams#discounts} for the field documentation. */ public Builder addAllDiscount(List<Discount> elements) { if (this.discounts == null) { this.discounts = new ArrayList<>(); } this.discounts.addAll(elements); return this; } /** * Add an element to `expand` list. A list is initialized for the first `add/addAll` call, and * subsequent calls adds additional elements to the original list. See {@link * SessionCreateParams#expand} for the field documentation. */ public Builder addExpand(String element) { if (this.expand == null) { this.expand = new ArrayList<>(); } this.expand.add(element); return this; } /** * Add all elements to `expand` list. A list is initialized for the first `add/addAll` call, and * subsequent calls adds additional elements to the original list. See {@link * SessionCreateParams#expand} for the field documentation. */ public Builder addAllExpand(List<String> elements) { if (this.expand == null) { this.expand = new ArrayList<>(); } this.expand.addAll(elements); return this; } /** * Add a key/value pair to `extraParams` map. A map is initialized for the first `put/putAll` * call, and subsequent calls add additional key/value pairs to the original map. See {@link * SessionCreateParams#extraParams} for the field documentation. */ public Builder putExtraParam(String key, Object value) { if (this.extraParams == null) { this.extraParams = new HashMap<>(); } this.extraParams.put(key, value); return this; } /** * Add all map key/value pairs to `extraParams` map. A map is initialized for the first * `put/putAll` call, and subsequent calls add additional key/value pairs to the original map. * See {@link SessionCreateParams#extraParams} for the field documentation. */ public Builder putAllExtraParam(Map<String, Object> map) { if (this.extraParams == null) { this.extraParams = new HashMap<>(); } this.extraParams.putAll(map); return this; } /** * Add an element to `lineItems` list. A list is initialized for the first `add/addAll` call, * and subsequent calls adds additional elements to the original list. See {@link * SessionCreateParams#lineItems} for the field documentation. */ public Builder addLineItem(LineItem element) { if (this.lineItems == null) { this.lineItems = new ArrayList<>(); } this.lineItems.add(element); return this; } /** * Add all elements to `lineItems` list. A list is initialized for the first `add/addAll` call, * and subsequent calls adds additional elements to the original list. See {@link * SessionCreateParams#lineItems} for the field documentation. */ public Builder addAllLineItem(List<LineItem> elements) { if (this.lineItems == null) { this.lineItems = new ArrayList<>(); } this.lineItems.addAll(elements); return this; } /** * The IETF language tag of the locale Checkout is displayed in. If blank or {@code auto}, the * browser's locale is used. */ public Builder setLocale(Locale locale) { this.locale = locale; return this; } /** * Add a key/value pair to `metadata` map. A map is initialized for the first `put/putAll` call, * and subsequent calls add additional key/value pairs to the original map. See {@link * SessionCreateParams#metadata} for the field documentation. */ public Builder putMetadata(String key, String value) { if (this.metadata == null) { this.metadata = new HashMap<>(); } this.metadata.put(key, value); return this; } /** * Add all map key/value pairs to `metadata` map. A map is initialized for the first * `put/putAll` call, and subsequent calls add additional key/value pairs to the original map. * See {@link SessionCreateParams#metadata} for the field documentation. */ public Builder putAllMetadata(Map<String, String> map) { if (this.metadata == null) { this.metadata = new HashMap<>(); } this.metadata.putAll(map); return this; } /** * The mode of the Checkout Session, one of {@code payment}, {@code setup}, or {@code * subscription}. Required when using prices or {@code setup} mode. Pass {@code subscription} if * Checkout session includes at least one recurring item. */ public Builder setMode(Mode mode) { this.mode = mode; return this; } /** * A subset of parameters to be passed to PaymentIntent creation for Checkout Sessions in {@code * payment} mode. */ public Builder setPaymentIntentData(PaymentIntentData paymentIntentData) { this.paymentIntentData = paymentIntentData; return this; } /** * Add an element to `paymentMethodTypes` list. A list is initialized for the first `add/addAll` * call, and subsequent calls adds additional elements to the original list. See {@link * SessionCreateParams#paymentMethodTypes} for the field documentation. */ public Builder addPaymentMethodType(PaymentMethodType element) { if (this.paymentMethodTypes == null) { this.paymentMethodTypes = new ArrayList<>(); } this.paymentMethodTypes.add(element); return this; } /** * Add all elements to `paymentMethodTypes` list. A list is initialized for the first * `add/addAll` call, and subsequent calls adds additional elements to the original list. See * {@link SessionCreateParams#paymentMethodTypes} for the field documentation. */ public Builder addAllPaymentMethodType(List<PaymentMethodType> elements) { if (this.paymentMethodTypes == null) { this.paymentMethodTypes = new ArrayList<>(); } this.paymentMethodTypes.addAll(elements); return this; } /** * A subset of parameters to be passed to SetupIntent creation for Checkout Sessions in {@code * setup} mode. */ public Builder setSetupIntentData(SetupIntentData setupIntentData) { this.setupIntentData = setupIntentData; return this; } /** * When set, provides configuration for Checkout to collect a shipping address from a customer. */ public Builder setShippingAddressCollection( ShippingAddressCollection shippingAddressCollection) { this.shippingAddressCollection = shippingAddressCollection; return this; } /** * Describes the type of transaction being performed by Checkout in order to customize relevant * text on the page, such as the submit button. {@code submit_type} can only be specified on * Checkout Sessions in {@code payment} mode, but not Checkout Sessions in {@code subscription} * or {@code setup} mode. */ public Builder setSubmitType(SubmitType submitType) { this.submitType = submitType; return this; } /** * A subset of parameters to be passed to subscription creation for Checkout Sessions in {@code * subscription} mode. */ public Builder setSubscriptionData(SubscriptionData subscriptionData) { this.subscriptionData = subscriptionData; return this; } public Builder setSuccessUrl(String successUrl) { this.successUrl = successUrl; return this; } } @Getter public static class Discount { /** The ID of the coupon to apply to this session. */ @SerializedName("coupon") String coupon; /** * Map of extra parameters for custom features not available in this client library. The content * in this map is not serialized under this field's {@code @SerializedName} value. Instead, each * key/value pair is serialized as if the key is a root-level field (serialized) name in this * param object. Effectively, this map is flattened to its parent instance. */ @SerializedName(ApiRequestParams.EXTRA_PARAMS_KEY) Map<String, Object> extraParams; /** The ID of a promotion code to apply to this session. */ @SerializedName("promotion_code") String promotionCode; private Discount(String coupon, Map<String, Object> extraParams, String promotionCode) { this.coupon = coupon; this.extraParams = extraParams; this.promotionCode = promotionCode; } public static Builder builder() { return new Builder(); } public static class Builder { private String coupon; private Map<String, Object> extraParams; private String promotionCode; /** Finalize and obtain parameter instance from this builder. */ public Discount build() { return new Discount(this.coupon, this.extraParams, this.promotionCode); } /** The ID of the coupon to apply to this session. */ public Builder setCoupon(String coupon) { this.coupon = coupon; return this; } /** * Add a key/value pair to `extraParams` map. A map is initialized for the first `put/putAll` * call, and subsequent calls add additional key/value pairs to the original map. See {@link * SessionCreateParams.Discount#extraParams} for the field documentation. */ public Builder putExtraParam(String key, Object value) { if (this.extraParams == null) { this.extraParams = new HashMap<>(); } this.extraParams.put(key, value); return this; } /** * Add all map key/value pairs to `extraParams` map. A map is initialized for the first * `put/putAll` call, and subsequent calls add additional key/value pairs to the original map. * See {@link SessionCreateParams.Discount#extraParams} for the field documentation. */ public Builder putAllExtraParam(Map<String, Object> map) { if (this.extraParams == null) { this.extraParams = new HashMap<>(); } this.extraParams.putAll(map); return this; } /** The ID of a promotion code to apply to this session. */ public Builder setPromotionCode(String promotionCode) { this.promotionCode = promotionCode; return this; } } } @Getter public static class LineItem { /** * The amount to be collected per unit of the line item. If specified, must also pass {@code * currency} and {@code name}. */ @SerializedName("amount") Long amount; @SerializedName("currency") String currency; /** * The description for the line item, to be displayed on the Checkout page. * * <p>If using {@code price} or {@code price_data}, will default to the name of the associated * product. */ @SerializedName("description") String description; /** * Map of extra parameters for custom features not available in this client library. The content * in this map is not serialized under this field's {@code @SerializedName} value. Instead, each * key/value pair is serialized as if the key is a root-level field (serialized) name in this * param object. Effectively, this map is flattened to its parent instance. */ @SerializedName(ApiRequestParams.EXTRA_PARAMS_KEY) Map<String, Object> extraParams; /** * A list of image URLs representing this line item. Each image can be up to 5 MB in size. If * passing {@code price} or {@code price_data}, specify images on the associated product * instead. */ @SerializedName("images") List<String> images; /** * The name for the item to be displayed on the Checkout page. Required if {@code amount} is * passed. */ @SerializedName("name") String name; @SerializedName("price") String price; @SerializedName("price_data") PriceData priceData; /** The quantity of the line item being purchased. */ @SerializedName("quantity") Long quantity; @SerializedName("tax_rates") List<String> taxRates; private LineItem( Long amount, String currency, String description, Map<String, Object> extraParams, List<String> images, String name, String price, PriceData priceData, Long quantity, List<String> taxRates) { this.amount = amount; this.currency = currency; this.description = description; this.extraParams = extraParams; this.images = images; this.name = name; this.price = price; this.priceData = priceData; this.quantity = quantity; this.taxRates = taxRates; } public static Builder builder() { return new Builder(); } public static class Builder { private Long amount; private String currency; private String description; private Map<String, Object> extraParams; private List<String> images; private String name; private String price; private PriceData priceData; private Long quantity; private List<String> taxRates; /** Finalize and obtain parameter instance from this builder. */ public LineItem build() { return new LineItem( this.amount, this.currency, this.description, this.extraParams, this.images, this.name, this.price, this.priceData, this.quantity, this.taxRates); } /** * The amount to be collected per unit of the line item. If specified, must also pass {@code * currency} and {@code name}. */ public Builder setAmount(Long amount) { this.amount = amount; return this; } public Builder setCurrency(String currency) { this.currency = currency; return this; } /** * The description for the line item, to be displayed on the Checkout page. * * <p>If using {@code price} or {@code price_data}, will default to the name of the associated * product. */ public Builder setDescription(String description) { this.description = description; return this; } /** * Add a key/value pair to `extraParams` map. A map is initialized for the first `put/putAll` * call, and subsequent calls add additional key/value pairs to the original map. See {@link * SessionCreateParams.LineItem#extraParams} for the field documentation. */ public Builder putExtraParam(String key, Object value) { if (this.extraParams == null) { this.extraParams = new HashMap<>(); } this.extraParams.put(key, value); return this; } /** * Add all map key/value pairs to `extraParams` map. A map is initialized for the first * `put/putAll` call, and subsequent calls add additional key/value pairs to the original map. * See {@link SessionCreateParams.LineItem#extraParams} for the field documentation. */ public Builder putAllExtraParam(Map<String, Object> map) { if (this.extraParams == null) { this.extraParams = new HashMap<>(); } this.extraParams.putAll(map); return this; } /** * Add an element to `images` list. A list is initialized for the first `add/addAll` call, and * subsequent calls adds additional elements to the original list. See {@link * SessionCreateParams.LineItem#images} for the field documentation. */ public Builder addImage(String element) { if (this.images == null) { this.images = new ArrayList<>(); } this.images.add(element); return this; } /** * Add all elements to `images` list. A list is initialized for the first `add/addAll` call, * and subsequent calls adds additional elements to the original list. See {@link * SessionCreateParams.LineItem#images} for the field documentation. */ public Builder addAllImage(List<String> elements) { if (this.images == null) { this.images = new ArrayList<>(); } this.images.addAll(elements); return this; } /** * The name for the item to be displayed on the Checkout page. Required if {@code amount} is * passed. */ public Builder setName(String name) { this.name = name; return this; } public Builder setPrice(String price) { this.price = price; return this; } public Builder setPriceData(PriceData priceData) { this.priceData = priceData; return this; } /** The quantity of the line item being purchased. */ public Builder setQuantity(Long quantity) { this.quantity = quantity; return this; } /** * Add an element to `taxRates` list. A list is initialized for the first `add/addAll` call, * and subsequent calls adds additional elements to the original list. See {@link * SessionCreateParams.LineItem#taxRates} for the field documentation. */ public Builder addTaxRate(String element) { if (this.taxRates == null) { this.taxRates = new ArrayList<>(); } this.taxRates.add(element); return this; } /** * Add all elements to `taxRates` list. A list is initialized for the first `add/addAll` call, * and subsequent calls adds additional elements to the original list. See {@link * SessionCreateParams.LineItem#taxRates} for the field documentation. */ public Builder addAllTaxRate(List<String> elements) { if (this.taxRates == null) { this.taxRates = new ArrayList<>(); } this.taxRates.addAll(elements); return this; } } @Getter public static class PriceData { @SerializedName("currency") String currency; /** * Map of extra parameters for custom features not available in this client library. The * content in this map is not serialized under this field's {@code @SerializedName} value. * Instead, each key/value pair is serialized as if the key is a root-level field (serialized) * name in this param object. Effectively, this map is flattened to its parent instance. */ @SerializedName(ApiRequestParams.EXTRA_PARAMS_KEY) Map<String, Object> extraParams; /** * The ID of the product that this price will belong to. One of {@code product} or {@code * product_data} is required. */ @SerializedName("product") String product; /** * Data used to generate a new product object inline. One of {@code product} or {@code * product_data} is required. */ @SerializedName("product_data") ProductData productData; /** The recurring components of a price such as {@code interval} and {@code usage_type}. */ @SerializedName("recurring") Recurring recurring; /** * A non-negative integer in %s representing how much to charge. One of {@code unit_amount} or * {@code unit_amount_decimal} is required. */ @SerializedName("unit_amount") Long unitAmount; /** * Same as {@code unit_amount}, but accepts a decimal value in %s with at most 12 decimal * places. Only one of {@code unit_amount} and {@code unit_amount_decimal} can be set. */ @SerializedName("unit_amount_decimal") BigDecimal unitAmountDecimal; private PriceData( String currency, Map<String, Object> extraParams, String product, ProductData productData, Recurring recurring, Long unitAmount, BigDecimal unitAmountDecimal) { this.currency = currency; this.extraParams = extraParams; this.product = product; this.productData = productData; this.recurring = recurring; this.unitAmount = unitAmount; this.unitAmountDecimal = unitAmountDecimal; } public static Builder builder() { return new Builder(); } public static class Builder { private String currency; private Map<String, Object> extraParams; private String product; private ProductData productData; private Recurring recurring; private Long unitAmount; private BigDecimal unitAmountDecimal; /** Finalize and obtain parameter instance from this builder. */ public PriceData build() { return new PriceData( this.currency, this.extraParams, this.product, this.productData, this.recurring, this.unitAmount, this.unitAmountDecimal); } public Builder setCurrency(String currency) { this.currency = currency; return this; } /** * Add a key/value pair to `extraParams` map. A map is initialized for the first * `put/putAll` call, and subsequent calls add additional key/value pairs to the original * map. See {@link SessionCreateParams.LineItem.PriceData#extraParams} for the field * documentation. */ public Builder putExtraParam(String key, Object value) { if (this.extraParams == null) { this.extraParams = new HashMap<>(); } this.extraParams.put(key, value); return this; } /** * Add all map key/value pairs to `extraParams` map. A map is initialized for the first * `put/putAll` call, and subsequent calls add additional key/value pairs to the original * map. See {@link SessionCreateParams.LineItem.PriceData#extraParams} for the field * documentation. */ public Builder putAllExtraParam(Map<String, Object> map) { if (this.extraParams == null) { this.extraParams = new HashMap<>(); } this.extraParams.putAll(map); return this; } /** * The ID of the product that this price will belong to. One of {@code product} or {@code * product_data} is required. */ public Builder setProduct(String product) { this.product = product; return this; } /** * Data used to generate a new product object inline. One of {@code product} or {@code * product_data} is required. */ public Builder setProductData(ProductData productData) { this.productData = productData; return this; } /** The recurring components of a price such as {@code interval} and {@code usage_type}. */ public Builder setRecurring(Recurring recurring) { this.recurring = recurring; return this; } /** * A non-negative integer in %s representing how much to charge. One of {@code unit_amount} * or {@code unit_amount_decimal} is required. */ public Builder setUnitAmount(Long unitAmount) { this.unitAmount = unitAmount; return this; } /** * Same as {@code unit_amount}, but accepts a decimal value in %s with at most 12 decimal * places. Only one of {@code unit_amount} and {@code unit_amount_decimal} can be set. */ public Builder setUnitAmountDecimal(BigDecimal unitAmountDecimal) { this.unitAmountDecimal = unitAmountDecimal; return this; } } @Getter public static class ProductData { /** * The product's description, meant to be displayable to the customer. Use this field to * optionally store a long form explanation of the product being sold for your own rendering * purposes. */ @SerializedName("description") String description; /** * Map of extra parameters for custom features not available in this client library. The * content in this map is not serialized under this field's {@code @SerializedName} value. * Instead, each key/value pair is serialized as if the key is a root-level field * (serialized) name in this param object. Effectively, this map is flattened to its parent * instance. */ @SerializedName(ApiRequestParams.EXTRA_PARAMS_KEY) Map<String, Object> extraParams; /** * A list of up to 8 URLs of images for this product, meant to be displayable to the * customer. */ @SerializedName("images") List<String> images; @SerializedName("metadata") Map<String, String> metadata; /** * The product's name, meant to be displayable to the customer. Whenever this product is * sold via a subscription, name will show up on associated invoice line item descriptions. */ @SerializedName("name") String name; private ProductData( String description, Map<String, Object> extraParams, List<String> images, Map<String, String> metadata, String name) { this.description = description; this.extraParams = extraParams; this.images = images; this.metadata = metadata; this.name = name; } public static Builder builder() { return new Builder(); } public static class Builder { private String description; private Map<String, Object> extraParams; private List<String> images; private Map<String, String> metadata; private String name; /** Finalize and obtain parameter instance from this builder. */ public ProductData build() { return new ProductData( this.description, this.extraParams, this.images, this.metadata, this.name); } /** * The product's description, meant to be displayable to the customer. Use this field to * optionally store a long form explanation of the product being sold for your own * rendering purposes. */ public Builder setDescription(String description) { this.description = description; return this; } /** * Add a key/value pair to `extraParams` map. A map is initialized for the first * `put/putAll` call, and subsequent calls add additional key/value pairs to the original * map. See {@link SessionCreateParams.LineItem.PriceData.ProductData#extraParams} for the * field documentation. */ public Builder putExtraParam(String key, Object value) { if (this.extraParams == null) { this.extraParams = new HashMap<>(); } this.extraParams.put(key, value); return this; } /** * Add all map key/value pairs to `extraParams` map. A map is initialized for the first * `put/putAll` call, and subsequent calls add additional key/value pairs to the original * map. See {@link SessionCreateParams.LineItem.PriceData.ProductData#extraParams} for the * field documentation. */ public Builder putAllExtraParam(Map<String, Object> map) { if (this.extraParams == null) { this.extraParams = new HashMap<>(); } this.extraParams.putAll(map); return this; } /** * Add an element to `images` list. A list is initialized for the first `add/addAll` call, * and subsequent calls adds additional elements to the original list. See {@link * SessionCreateParams.LineItem.PriceData.ProductData#images} for the field documentation. */ public Builder addImage(String element) { if (this.images == null) { this.images = new ArrayList<>(); } this.images.add(element); return this; } /** * Add all elements to `images` list. A list is initialized for the first `add/addAll` * call, and subsequent calls adds additional elements to the original list. See {@link * SessionCreateParams.LineItem.PriceData.ProductData#images} for the field documentation. */ public Builder addAllImage(List<String> elements) { if (this.images == null) { this.images = new ArrayList<>(); } this.images.addAll(elements); return this; } /** * Add a key/value pair to `metadata` map. A map is initialized for the first `put/putAll` * call, and subsequent calls add additional key/value pairs to the original map. See * {@link SessionCreateParams.LineItem.PriceData.ProductData#metadata} for the field * documentation. */ public Builder putMetadata(String key, String value) { if (this.metadata == null) { this.metadata = new HashMap<>(); } this.metadata.put(key, value); return this; } /** * Add all map key/value pairs to `metadata` map. A map is initialized for the first * `put/putAll` call, and subsequent calls add additional key/value pairs to the original * map. See {@link SessionCreateParams.LineItem.PriceData.ProductData#metadata} for the * field documentation. */ public Builder putAllMetadata(Map<String, String> map) { if (this.metadata == null) { this.metadata = new HashMap<>(); } this.metadata.putAll(map); return this; } /** * The product's name, meant to be displayable to the customer. Whenever this product is * sold via a subscription, name will show up on associated invoice line item * descriptions. */ public Builder setName(String name) { this.name = name; return this; } } } @Getter public static class Recurring { /** * Map of extra parameters for custom features not available in this client library. The * content in this map is not serialized under this field's {@code @SerializedName} value. * Instead, each key/value pair is serialized as if the key is a root-level field * (serialized) name in this param object. Effectively, this map is flattened to its parent * instance. */ @SerializedName(ApiRequestParams.EXTRA_PARAMS_KEY) Map<String, Object> extraParams; /** * Specifies billing frequency. Either {@code day}, {@code week}, {@code month} or {@code * year}. */ @SerializedName("interval") Interval interval; /** * The number of intervals between subscription billings. For example, {@code * interval=month} and {@code interval_count=3} bills every 3 months. Maximum of one year * interval allowed (1 year, 12 months, or 52 weeks). */ @SerializedName("interval_count") Long intervalCount; private Recurring(Map<String, Object> extraParams, Interval interval, Long intervalCount) { this.extraParams = extraParams; this.interval = interval; this.intervalCount = intervalCount; } public static Builder builder() { return new Builder(); } public static class Builder { private Map<String, Object> extraParams; private Interval interval; private Long intervalCount; /** Finalize and obtain parameter instance from this builder. */ public Recurring build() { return new Recurring(this.extraParams, this.interval, this.intervalCount); } /** * Add a key/value pair to `extraParams` map. A map is initialized for the first * `put/putAll` call, and subsequent calls add additional key/value pairs to the original * map. See {@link SessionCreateParams.LineItem.PriceData.Recurring#extraParams} for the * field documentation. */ public Builder putExtraParam(String key, Object value) { if (this.extraParams == null) { this.extraParams = new HashMap<>(); } this.extraParams.put(key, value); return this; } /** * Add all map key/value pairs to `extraParams` map. A map is initialized for the first * `put/putAll` call, and subsequent calls add additional key/value pairs to the original * map. See {@link SessionCreateParams.LineItem.PriceData.Recurring#extraParams} for the * field documentation. */ public Builder putAllExtraParam(Map<String, Object> map) { if (this.extraParams == null) { this.extraParams = new HashMap<>(); } this.extraParams.putAll(map); return this; } /** * Specifies billing frequency. Either {@code day}, {@code week}, {@code month} or {@code * year}. */ public Builder setInterval(Interval interval) { this.interval = interval; return this; } /** * The number of intervals between subscription billings. For example, {@code * interval=month} and {@code interval_count=3} bills every 3 months. Maximum of one year * interval allowed (1 year, 12 months, or 52 weeks). */ public Builder setIntervalCount(Long intervalCount) { this.intervalCount = intervalCount; return this; } } public enum Interval implements ApiRequestParams.EnumParam { @SerializedName("day") DAY("day"), @SerializedName("month") MONTH("month"), @SerializedName("week") WEEK("week"), @SerializedName("year") YEAR("year"); @Getter(onMethod_ = {@Override}) private final String value; Interval(String value) { this.value = value; } } } } } @Getter public static class PaymentIntentData { @SerializedName("application_fee_amount") Long applicationFeeAmount; /** Controls when the funds will be captured from the customer's account. */ @SerializedName("capture_method") CaptureMethod captureMethod; /** An arbitrary string attached to the object. Often useful for displaying to users. */ @SerializedName("description") String description; /** * Map of extra parameters for custom features not available in this client library. The content * in this map is not serialized under this field's {@code @SerializedName} value. Instead, each * key/value pair is serialized as if the key is a root-level field (serialized) name in this * param object. Effectively, this map is flattened to its parent instance. */ @SerializedName(ApiRequestParams.EXTRA_PARAMS_KEY) Map<String, Object> extraParams; @SerializedName("metadata") Map<String, String> metadata; @SerializedName("on_behalf_of") String onBehalfOf; @SerializedName("receipt_email") String receiptEmail; /** * Indicates that you intend to make future payments with the payment method collected by this * Checkout Session. * * <p>When setting this to {@code off_session}, Checkout will show a notice to the customer that * their payment details will be saved and used for future payments. * * <p>When processing card payments, Checkout also uses {@code setup_future_usage} to * dynamically optimize your payment flow and comply with regional legislation and network * rules, such as SCA. */ @SerializedName("setup_future_usage") SetupFutureUsage setupFutureUsage; /** Shipping information for this payment. */ @SerializedName("shipping") Shipping shipping; /** * Extra information about the payment. This will appear on your customer's statement when this * payment succeeds in creating a charge. */ @SerializedName("statement_descriptor") String statementDescriptor; @SerializedName("statement_descriptor_suffix") String statementDescriptorSuffix; @SerializedName("transfer_data") TransferData transferData; @SerializedName("transfer_group") String transferGroup; private PaymentIntentData( Long applicationFeeAmount, CaptureMethod captureMethod, String description, Map<String, Object> extraParams, Map<String, String> metadata, String onBehalfOf, String receiptEmail, SetupFutureUsage setupFutureUsage, Shipping shipping, String statementDescriptor, String statementDescriptorSuffix, TransferData transferData, String transferGroup) { this.applicationFeeAmount = applicationFeeAmount; this.captureMethod = captureMethod; this.description = description; this.extraParams = extraParams; this.metadata = metadata; this.onBehalfOf = onBehalfOf; this.receiptEmail = receiptEmail; this.setupFutureUsage = setupFutureUsage; this.shipping = shipping; this.statementDescriptor = statementDescriptor; this.statementDescriptorSuffix = statementDescriptorSuffix; this.transferData = transferData; this.transferGroup = transferGroup; } public static Builder builder() { return new Builder(); } public static class Builder { private Long applicationFeeAmount; private CaptureMethod captureMethod; private String description; private Map<String, Object> extraParams; private Map<String, String> metadata; private String onBehalfOf; private String receiptEmail; private SetupFutureUsage setupFutureUsage; private Shipping shipping; private String statementDescriptor; private String statementDescriptorSuffix; private TransferData transferData; private String transferGroup; /** Finalize and obtain parameter instance from this builder. */ public PaymentIntentData build() { return new PaymentIntentData( this.applicationFeeAmount, this.captureMethod, this.description, this.extraParams, this.metadata, this.onBehalfOf, this.receiptEmail, this.setupFutureUsage, this.shipping, this.statementDescriptor, this.statementDescriptorSuffix, this.transferData, this.transferGroup); } public Builder setApplicationFeeAmount(Long applicationFeeAmount) { this.applicationFeeAmount = applicationFeeAmount; return this; } /** Controls when the funds will be captured from the customer's account. */ public Builder setCaptureMethod(CaptureMethod captureMethod) { this.captureMethod = captureMethod; return this; } /** An arbitrary string attached to the object. Often useful for displaying to users. */ public Builder setDescription(String description) { this.description = description; return this; } /** * Add a key/value pair to `extraParams` map. A map is initialized for the first `put/putAll` * call, and subsequent calls add additional key/value pairs to the original map. See {@link * SessionCreateParams.PaymentIntentData#extraParams} for the field documentation. */ public Builder putExtraParam(String key, Object value) { if (this.extraParams == null) { this.extraParams = new HashMap<>(); } this.extraParams.put(key, value); return this; } /** * Add all map key/value pairs to `extraParams` map. A map is initialized for the first * `put/putAll` call, and subsequent calls add additional key/value pairs to the original map. * See {@link SessionCreateParams.PaymentIntentData#extraParams} for the field documentation. */ public Builder putAllExtraParam(Map<String, Object> map) { if (this.extraParams == null) { this.extraParams = new HashMap<>(); } this.extraParams.putAll(map); return this; } /** * Add a key/value pair to `metadata` map. A map is initialized for the first `put/putAll` * call, and subsequent calls add additional key/value pairs to the original map. See {@link * SessionCreateParams.PaymentIntentData#metadata} for the field documentation. */ public Builder putMetadata(String key, String value) { if (this.metadata == null) { this.metadata = new HashMap<>(); } this.metadata.put(key, value); return this; } /** * Add all map key/value pairs to `metadata` map. A map is initialized for the first * `put/putAll` call, and subsequent calls add additional key/value pairs to the original map. * See {@link SessionCreateParams.PaymentIntentData#metadata} for the field documentation. */ public Builder putAllMetadata(Map<String, String> map) { if (this.metadata == null) { this.metadata = new HashMap<>(); } this.metadata.putAll(map); return this; } public Builder setOnBehalfOf(String onBehalfOf) { this.onBehalfOf = onBehalfOf; return this; } public Builder setReceiptEmail(String receiptEmail) { this.receiptEmail = receiptEmail; return this; } /** * Indicates that you intend to make future payments with the payment method collected by this * Checkout Session. * * <p>When setting this to {@code off_session}, Checkout will show a notice to the customer * that their payment details will be saved and used for future payments. * * <p>When processing card payments, Checkout also uses {@code setup_future_usage} to * dynamically optimize your payment flow and comply with regional legislation and network * rules, such as SCA. */ public Builder setSetupFutureUsage(SetupFutureUsage setupFutureUsage) { this.setupFutureUsage = setupFutureUsage; return this; } /** Shipping information for this payment. */ public Builder setShipping(Shipping shipping) { this.shipping = shipping; return this; } /** * Extra information about the payment. This will appear on your customer's statement when * this payment succeeds in creating a charge. */ public Builder setStatementDescriptor(String statementDescriptor) { this.statementDescriptor = statementDescriptor; return this; } public Builder setStatementDescriptorSuffix(String statementDescriptorSuffix) { this.statementDescriptorSuffix = statementDescriptorSuffix; return this; } public Builder setTransferData(TransferData transferData) { this.transferData = transferData; return this; } public Builder setTransferGroup(String transferGroup) { this.transferGroup = transferGroup; return this; } } @Getter public static class Shipping { /** Shipping address. */ @SerializedName("address") Address address; /** The delivery service that shipped a physical product, such as Fedex, UPS, USPS, etc. */ @SerializedName("carrier") String carrier; /** * Map of extra parameters for custom features not available in this client library. The * content in this map is not serialized under this field's {@code @SerializedName} value. * Instead, each key/value pair is serialized as if the key is a root-level field (serialized) * name in this param object. Effectively, this map is flattened to its parent instance. */ @SerializedName(ApiRequestParams.EXTRA_PARAMS_KEY) Map<String, Object> extraParams; /** Recipient name. */ @SerializedName("name") String name; /** Recipient phone (including extension). */ @SerializedName("phone") String phone; /** * The tracking number for a physical product, obtained from the delivery service. If multiple * tracking numbers were generated for this purchase, please separate them with commas. */ @SerializedName("tracking_number") String trackingNumber; private Shipping( Address address, String carrier, Map<String, Object> extraParams, String name, String phone, String trackingNumber) { this.address = address; this.carrier = carrier; this.extraParams = extraParams; this.name = name; this.phone = phone; this.trackingNumber = trackingNumber; } public static Builder builder() { return new Builder(); } public static class Builder { private Address address; private String carrier; private Map<String, Object> extraParams; private String name; private String phone; private String trackingNumber; /** Finalize and obtain parameter instance from this builder. */ public Shipping build() { return new Shipping( this.address, this.carrier, this.extraParams, this.name, this.phone, this.trackingNumber); } /** Shipping address. */ public Builder setAddress(Address address) { this.address = address; return this; } /** The delivery service that shipped a physical product, such as Fedex, UPS, USPS, etc. */ public Builder setCarrier(String carrier) { this.carrier = carrier; return this; } /** * Add a key/value pair to `extraParams` map. A map is initialized for the first * `put/putAll` call, and subsequent calls add additional key/value pairs to the original * map. See {@link SessionCreateParams.PaymentIntentData.Shipping#extraParams} for the field * documentation. */ public Builder putExtraParam(String key, Object value) { if (this.extraParams == null) { this.extraParams = new HashMap<>(); } this.extraParams.put(key, value); return this; } /** * Add all map key/value pairs to `extraParams` map. A map is initialized for the first * `put/putAll` call, and subsequent calls add additional key/value pairs to the original * map. See {@link SessionCreateParams.PaymentIntentData.Shipping#extraParams} for the field * documentation. */ public Builder putAllExtraParam(Map<String, Object> map) { if (this.extraParams == null) { this.extraParams = new HashMap<>(); } this.extraParams.putAll(map); return this; } /** Recipient name. */ public Builder setName(String name) { this.name = name; return this; } /** Recipient phone (including extension). */ public Builder setPhone(String phone) { this.phone = phone; return this; } /** * The tracking number for a physical product, obtained from the delivery service. If * multiple tracking numbers were generated for this purchase, please separate them with * commas. */ public Builder setTrackingNumber(String trackingNumber) { this.trackingNumber = trackingNumber; return this; } } @Getter public static class Address { /** City, district, suburb, town, or village. */ @SerializedName("city") String city; @SerializedName("country") String country; /** * Map of extra parameters for custom features not available in this client library. The * content in this map is not serialized under this field's {@code @SerializedName} value. * Instead, each key/value pair is serialized as if the key is a root-level field * (serialized) name in this param object. Effectively, this map is flattened to its parent * instance. */ @SerializedName(ApiRequestParams.EXTRA_PARAMS_KEY) Map<String, Object> extraParams; /** Address line 1 (e.g., street, PO Box, or company name). */ @SerializedName("line1") String line1; /** Address line 2 (e.g., apartment, suite, unit, or building). */ @SerializedName("line2") String line2; /** ZIP or postal code. */ @SerializedName("postal_code") String postalCode; /** State, county, province, or region. */ @SerializedName("state") String state; private Address( String city, String country, Map<String, Object> extraParams, String line1, String line2, String postalCode, String state) { this.city = city; this.country = country; this.extraParams = extraParams; this.line1 = line1; this.line2 = line2; this.postalCode = postalCode; this.state = state; } public static Builder builder() { return new Builder(); } public static class Builder { private String city; private String country; private Map<String, Object> extraParams; private String line1; private String line2; private String postalCode; private String state; /** Finalize and obtain parameter instance from this builder. */ public Address build() { return new Address( this.city, this.country, this.extraParams, this.line1, this.line2, this.postalCode, this.state); } /** City, district, suburb, town, or village. */ public Builder setCity(String city) { this.city = city; return this; } public Builder setCountry(String country) { this.country = country; return this; } /** * Add a key/value pair to `extraParams` map. A map is initialized for the first * `put/putAll` call, and subsequent calls add additional key/value pairs to the original * map. See {@link SessionCreateParams.PaymentIntentData.Shipping.Address#extraParams} for * the field documentation. */ public Builder putExtraParam(String key, Object value) { if (this.extraParams == null) { this.extraParams = new HashMap<>(); } this.extraParams.put(key, value); return this; } /** * Add all map key/value pairs to `extraParams` map. A map is initialized for the first * `put/putAll` call, and subsequent calls add additional key/value pairs to the original * map. See {@link SessionCreateParams.PaymentIntentData.Shipping.Address#extraParams} for * the field documentation. */ public Builder putAllExtraParam(Map<String, Object> map) { if (this.extraParams == null) { this.extraParams = new HashMap<>(); } this.extraParams.putAll(map); return this; } /** Address line 1 (e.g., street, PO Box, or company name). */ public Builder setLine1(String line1) { this.line1 = line1; return this; } /** Address line 2 (e.g., apartment, suite, unit, or building). */ public Builder setLine2(String line2) { this.line2 = line2; return this; } /** ZIP or postal code. */ public Builder setPostalCode(String postalCode) { this.postalCode = postalCode; return this; } /** State, county, province, or region. */ public Builder setState(String state) { this.state = state; return this; } } } } @Getter public static class TransferData { /** The amount that will be transferred automatically when a charge succeeds. */ @SerializedName("amount") Long amount; /** * If specified, successful charges will be attributed to the destination account for tax * reporting, and the funds from charges will be transferred to the destination account. The * ID of the resulting transfer will be returned on the successful charge's {@code transfer} * field. */ @SerializedName("destination") String destination; /** * Map of extra parameters for custom features not available in this client library. The * content in this map is not serialized under this field's {@code @SerializedName} value. * Instead, each key/value pair is serialized as if the key is a root-level field (serialized) * name in this param object. Effectively, this map is flattened to its parent instance. */ @SerializedName(ApiRequestParams.EXTRA_PARAMS_KEY) Map<String, Object> extraParams; private TransferData(Long amount, String destination, Map<String, Object> extraParams) { this.amount = amount; this.destination = destination; this.extraParams = extraParams; } public static Builder builder() { return new Builder(); } public static class Builder { private Long amount; private String destination; private Map<String, Object> extraParams; /** Finalize and obtain parameter instance from this builder. */ public TransferData build() { return new TransferData(this.amount, this.destination, this.extraParams); } /** The amount that will be transferred automatically when a charge succeeds. */ public Builder setAmount(Long amount) { this.amount = amount; return this; } /** * If specified, successful charges will be attributed to the destination account for tax * reporting, and the funds from charges will be transferred to the destination account. The * ID of the resulting transfer will be returned on the successful charge's {@code transfer} * field. */ public Builder setDestination(String destination) { this.destination = destination; return this; } /** * Add a key/value pair to `extraParams` map. A map is initialized for the first * `put/putAll` call, and subsequent calls add additional key/value pairs to the original * map. See {@link SessionCreateParams.PaymentIntentData.TransferData#extraParams} for the * field documentation. */ public Builder putExtraParam(String key, Object value) { if (this.extraParams == null) { this.extraParams = new HashMap<>(); } this.extraParams.put(key, value); return this; } /** * Add all map key/value pairs to `extraParams` map. A map is initialized for the first * `put/putAll` call, and subsequent calls add additional key/value pairs to the original * map. See {@link SessionCreateParams.PaymentIntentData.TransferData#extraParams} for the * field documentation. */ public Builder putAllExtraParam(Map<String, Object> map) { if (this.extraParams == null) { this.extraParams = new HashMap<>(); } this.extraParams.putAll(map); return this; } } } public enum CaptureMethod implements ApiRequestParams.EnumParam { @SerializedName("automatic") AUTOMATIC("automatic"), @SerializedName("manual") MANUAL("manual"); @Getter(onMethod_ = {@Override}) private final String value; CaptureMethod(String value) { this.value = value; } } public enum SetupFutureUsage implements ApiRequestParams.EnumParam { @SerializedName("off_session") OFF_SESSION("off_session"), @SerializedName("on_session") ON_SESSION("on_session"); @Getter(onMethod_ = {@Override}) private final String value; SetupFutureUsage(String value) { this.value = value; } } } @Getter public static class SetupIntentData { /** An arbitrary string attached to the object. Often useful for displaying to users. */ @SerializedName("description") String description; /** * Map of extra parameters for custom features not available in this client library. The content * in this map is not serialized under this field's {@code @SerializedName} value. Instead, each * key/value pair is serialized as if the key is a root-level field (serialized) name in this * param object. Effectively, this map is flattened to its parent instance. */ @SerializedName(ApiRequestParams.EXTRA_PARAMS_KEY) Map<String, Object> extraParams; @SerializedName("metadata") Map<String, String> metadata; /** The Stripe account for which the setup is intended. */ @SerializedName("on_behalf_of") String onBehalfOf; private SetupIntentData( String description, Map<String, Object> extraParams, Map<String, String> metadata, String onBehalfOf) { this.description = description; this.extraParams = extraParams; this.metadata = metadata; this.onBehalfOf = onBehalfOf; } public static Builder builder() { return new Builder(); } public static class Builder { private String description; private Map<String, Object> extraParams; private Map<String, String> metadata; private String onBehalfOf; /** Finalize and obtain parameter instance from this builder. */ public SetupIntentData build() { return new SetupIntentData( this.description, this.extraParams, this.metadata, this.onBehalfOf); } /** An arbitrary string attached to the object. Often useful for displaying to users. */ public Builder setDescription(String description) { this.description = description; return this; } /** * Add a key/value pair to `extraParams` map. A map is initialized for the first `put/putAll` * call, and subsequent calls add additional key/value pairs to the original map. See {@link * SessionCreateParams.SetupIntentData#extraParams} for the field documentation. */ public Builder putExtraParam(String key, Object value) { if (this.extraParams == null) { this.extraParams = new HashMap<>(); } this.extraParams.put(key, value); return this; } /** * Add all map key/value pairs to `extraParams` map. A map is initialized for the first * `put/putAll` call, and subsequent calls add additional key/value pairs to the original map. * See {@link SessionCreateParams.SetupIntentData#extraParams} for the field documentation. */ public Builder putAllExtraParam(Map<String, Object> map) { if (this.extraParams == null) { this.extraParams = new HashMap<>(); } this.extraParams.putAll(map); return this; } /** * Add a key/value pair to `metadata` map. A map is initialized for the first `put/putAll` * call, and subsequent calls add additional key/value pairs to the original map. See {@link * SessionCreateParams.SetupIntentData#metadata} for the field documentation. */ public Builder putMetadata(String key, String value) { if (this.metadata == null) { this.metadata = new HashMap<>(); } this.metadata.put(key, value); return this; } /** * Add all map key/value pairs to `metadata` map. A map is initialized for the first * `put/putAll` call, and subsequent calls add additional key/value pairs to the original map. * See {@link SessionCreateParams.SetupIntentData#metadata} for the field documentation. */ public Builder putAllMetadata(Map<String, String> map) { if (this.metadata == null) { this.metadata = new HashMap<>(); } this.metadata.putAll(map); return this; } /** The Stripe account for which the setup is intended. */ public Builder setOnBehalfOf(String onBehalfOf) { this.onBehalfOf = onBehalfOf; return this; } } } @Getter public static class ShippingAddressCollection { /** * An array of two-letter ISO country codes representing which countries Checkout should provide * as options for shipping locations. Unsupported country codes: {@code AS, CX, CC, CU, HM, IR, * KP, MH, FM, NF, MP, PW, SD, SY, UM, VI}. */ @SerializedName("allowed_countries") List<AllowedCountry> allowedCountries; /** * Map of extra parameters for custom features not available in this client library. The content * in this map is not serialized under this field's {@code @SerializedName} value. Instead, each * key/value pair is serialized as if the key is a root-level field (serialized) name in this * param object. Effectively, this map is flattened to its parent instance. */ @SerializedName(ApiRequestParams.EXTRA_PARAMS_KEY) Map<String, Object> extraParams; private ShippingAddressCollection( List<AllowedCountry> allowedCountries, Map<String, Object> extraParams) { this.allowedCountries = allowedCountries; this.extraParams = extraParams; } public static Builder builder() { return new Builder(); } public static class Builder { private List<AllowedCountry> allowedCountries; private Map<String, Object> extraParams; /** Finalize and obtain parameter instance from this builder. */ public ShippingAddressCollection build() { return new ShippingAddressCollection(this.allowedCountries, this.extraParams); } /** * Add an element to `allowedCountries` list. A list is initialized for the first `add/addAll` * call, and subsequent calls adds additional elements to the original list. See {@link * SessionCreateParams.ShippingAddressCollection#allowedCountries} for the field * documentation. */ public Builder addAllowedCountry(AllowedCountry element) { if (this.allowedCountries == null) { this.allowedCountries = new ArrayList<>(); } this.allowedCountries.add(element); return this; } /** * Add all elements to `allowedCountries` list. A list is initialized for the first * `add/addAll` call, and subsequent calls adds additional elements to the original list. See * {@link SessionCreateParams.ShippingAddressCollection#allowedCountries} for the field * documentation. */ public Builder addAllAllowedCountry(List<AllowedCountry> elements) { if (this.allowedCountries == null) { this.allowedCountries = new ArrayList<>(); } this.allowedCountries.addAll(elements); return this; } /** * Add a key/value pair to `extraParams` map. A map is initialized for the first `put/putAll` * call, and subsequent calls add additional key/value pairs to the original map. See {@link * SessionCreateParams.ShippingAddressCollection#extraParams} for the field documentation. */ public Builder putExtraParam(String key, Object value) { if (this.extraParams == null) { this.extraParams = new HashMap<>(); } this.extraParams.put(key, value); return this; } /** * Add all map key/value pairs to `extraParams` map. A map is initialized for the first * `put/putAll` call, and subsequent calls add additional key/value pairs to the original map. * See {@link SessionCreateParams.ShippingAddressCollection#extraParams} for the field * documentation. */ public Builder putAllExtraParam(Map<String, Object> map) { if (this.extraParams == null) { this.extraParams = new HashMap<>(); } this.extraParams.putAll(map); return this; } } public enum AllowedCountry implements ApiRequestParams.EnumParam { @SerializedName("AC") AC("AC"), @SerializedName("AD") AD("AD"), @SerializedName("AE") AE("AE"), @SerializedName("AF") AF("AF"), @SerializedName("AG") AG("AG"), @SerializedName("AI") AI("AI"), @SerializedName("AL") AL("AL"), @SerializedName("AM") AM("AM"), @SerializedName("AO") AO("AO"), @SerializedName("AQ") AQ("AQ"), @SerializedName("AR") AR("AR"), @SerializedName("AT") AT("AT"), @SerializedName("AU") AU("AU"), @SerializedName("AW") AW("AW"), @SerializedName("AX") AX("AX"), @SerializedName("AZ") AZ("AZ"), @SerializedName("BA") BA("BA"), @SerializedName("BB") BB("BB"), @SerializedName("BD") BD("BD"), @SerializedName("BE") BE("BE"), @SerializedName("BF") BF("BF"), @SerializedName("BG") BG("BG"), @SerializedName("BH") BH("BH"), @SerializedName("BI") BI("BI"), @SerializedName("BJ") BJ("BJ"), @SerializedName("BL") BL("BL"), @SerializedName("BM") BM("BM"), @SerializedName("BN") BN("BN"), @SerializedName("BO") BO("BO"), @SerializedName("BQ") BQ("BQ"), @SerializedName("BR") BR("BR"), @SerializedName("BS") BS("BS"), @SerializedName("BT") BT("BT"), @SerializedName("BV") BV("BV"), @SerializedName("BW") BW("BW"), @SerializedName("BY") BY("BY"), @SerializedName("BZ") BZ("BZ"), @SerializedName("CA") CA("CA"), @SerializedName("CD") CD("CD"), @SerializedName("CF") CF("CF"), @SerializedName("CG") CG("CG"), @SerializedName("CH") CH("CH"), @SerializedName("CI") CI("CI"), @SerializedName("CK") CK("CK"), @SerializedName("CL") CL("CL"), @SerializedName("CM") CM("CM"), @SerializedName("CN") CN("CN"), @SerializedName("CO") CO("CO"), @SerializedName("CR") CR("CR"), @SerializedName("CV") CV("CV"), @SerializedName("CW") CW("CW"), @SerializedName("CY") CY("CY"), @SerializedName("CZ") CZ("CZ"), @SerializedName("DE") DE("DE"), @SerializedName("DJ") DJ("DJ"), @SerializedName("DK") DK("DK"), @SerializedName("DM") DM("DM"), @SerializedName("DO") DO("DO"), @SerializedName("DZ") DZ("DZ"), @SerializedName("EC") EC("EC"), @SerializedName("EE") EE("EE"), @SerializedName("EG") EG("EG"), @SerializedName("EH") EH("EH"), @SerializedName("ER") ER("ER"), @SerializedName("ES") ES("ES"), @SerializedName("ET") ET("ET"), @SerializedName("FI") FI("FI"), @SerializedName("FJ") FJ("FJ"), @SerializedName("FK") FK("FK"), @SerializedName("FO") FO("FO"), @SerializedName("FR") FR("FR"), @SerializedName("GA") GA("GA"), @SerializedName("GB") GB("GB"), @SerializedName("GD") GD("GD"), @SerializedName("GE") GE("GE"), @SerializedName("GF") GF("GF"), @SerializedName("GG") GG("GG"), @SerializedName("GH") GH("GH"), @SerializedName("GI") GI("GI"), @SerializedName("GL") GL("GL"), @SerializedName("GM") GM("GM"), @SerializedName("GN") GN("GN"), @SerializedName("GP") GP("GP"), @SerializedName("GQ") GQ("GQ"), @SerializedName("GR") GR("GR"), @SerializedName("GS") GS("GS"), @SerializedName("GT") GT("GT"), @SerializedName("GU") GU("GU"), @SerializedName("GW") GW("GW"), @SerializedName("GY") GY("GY"), @SerializedName("HK") HK("HK"), @SerializedName("HN") HN("HN"), @SerializedName("HR") HR("HR"), @SerializedName("HT") HT("HT"), @SerializedName("HU") HU("HU"), @SerializedName("ID") ID("ID"), @SerializedName("IE") IE("IE"), @SerializedName("IL") IL("IL"), @SerializedName("IM") IM("IM"), @SerializedName("IN") IN("IN"), @SerializedName("IO") IO("IO"), @SerializedName("IQ") IQ("IQ"), @SerializedName("IS") IS("IS"), @SerializedName("IT") IT("IT"), @SerializedName("JE") JE("JE"), @SerializedName("JM") JM("JM"), @SerializedName("JO") JO("JO"), @SerializedName("JP") JP("JP"), @SerializedName("KE") KE("KE"), @SerializedName("KG") KG("KG"), @SerializedName("KH") KH("KH"), @SerializedName("KI") KI("KI"), @SerializedName("KM") KM("KM"), @SerializedName("KN") KN("KN"), @SerializedName("KR") KR("KR"), @SerializedName("KW") KW("KW"), @SerializedName("KY") KY("KY"), @SerializedName("KZ") KZ("KZ"), @SerializedName("LA") LA("LA"), @SerializedName("LB") LB("LB"), @SerializedName("LC") LC("LC"), @SerializedName("LI") LI("LI"), @SerializedName("LK") LK("LK"), @SerializedName("LR") LR("LR"), @SerializedName("LS") LS("LS"), @SerializedName("LT") LT("LT"), @SerializedName("LU") LU("LU"), @SerializedName("LV") LV("LV"), @SerializedName("LY") LY("LY"), @SerializedName("MA") MA("MA"), @SerializedName("MC") MC("MC"), @SerializedName("MD") MD("MD"), @SerializedName("ME") ME("ME"), @SerializedName("MF") MF("MF"), @SerializedName("MG") MG("MG"), @SerializedName("MK") MK("MK"), @SerializedName("ML") ML("ML"), @SerializedName("MM") MM("MM"), @SerializedName("MN") MN("MN"), @SerializedName("MO") MO("MO"), @SerializedName("MQ") MQ("MQ"), @SerializedName("MR") MR("MR"), @SerializedName("MS") MS("MS"), @SerializedName("MT") MT("MT"), @SerializedName("MU") MU("MU"), @SerializedName("MV") MV("MV"), @SerializedName("MW") MW("MW"), @SerializedName("MX") MX("MX"), @SerializedName("MY") MY("MY"), @SerializedName("MZ") MZ("MZ"), @SerializedName("NA") NA("NA"), @SerializedName("NC") NC("NC"), @SerializedName("NE") NE("NE"), @SerializedName("NG") NG("NG"), @SerializedName("NI") NI("NI"), @SerializedName("NL") NL("NL"), @SerializedName("NO") NO("NO"), @SerializedName("NP") NP("NP"), @SerializedName("NR") NR("NR"), @SerializedName("NU") NU("NU"), @SerializedName("NZ") NZ("NZ"), @SerializedName("OM") OM("OM"), @SerializedName("PA") PA("PA"), @SerializedName("PE") PE("PE"), @SerializedName("PF") PF("PF"), @SerializedName("PG") PG("PG"), @SerializedName("PH") PH("PH"), @SerializedName("PK") PK("PK"), @SerializedName("PL") PL("PL"), @SerializedName("PM") PM("PM"), @SerializedName("PN") PN("PN"), @SerializedName("PR") PR("PR"), @SerializedName("PS") PS("PS"), @SerializedName("PT") PT("PT"), @SerializedName("PY") PY("PY"), @SerializedName("QA") QA("QA"), @SerializedName("RE") RE("RE"), @SerializedName("RO") RO("RO"), @SerializedName("RS") RS("RS"), @SerializedName("RU") RU("RU"), @SerializedName("RW") RW("RW"), @SerializedName("SA") SA("SA"), @SerializedName("SB") SB("SB"), @SerializedName("SC") SC("SC"), @SerializedName("SE") SE("SE"), @SerializedName("SG") SG("SG"), @SerializedName("SH") SH("SH"), @SerializedName("SI") SI("SI"), @SerializedName("SJ") SJ("SJ"), @SerializedName("SK") SK("SK"), @SerializedName("SL") SL("SL"), @SerializedName("SM") SM("SM"), @SerializedName("SN") SN("SN"), @SerializedName("SO") SO("SO"), @SerializedName("SR") SR("SR"), @SerializedName("SS") SS("SS"), @SerializedName("ST") ST("ST"), @SerializedName("SV") SV("SV"), @SerializedName("SX") SX("SX"), @SerializedName("SZ") SZ("SZ"), @SerializedName("TA") TA("TA"), @SerializedName("TC") TC("TC"), @SerializedName("TD") TD("TD"), @SerializedName("TF") TF("TF"), @SerializedName("TG") TG("TG"), @SerializedName("TH") TH("TH"), @SerializedName("TJ") TJ("TJ"), @SerializedName("TK") TK("TK"), @SerializedName("TL") TL("TL"), @SerializedName("TM") TM("TM"), @SerializedName("TN") TN("TN"), @SerializedName("TO") TO("TO"), @SerializedName("TR") TR("TR"), @SerializedName("TT") TT("TT"), @SerializedName("TV") TV("TV"), @SerializedName("TW") TW("TW"), @SerializedName("TZ") TZ("TZ"), @SerializedName("UA") UA("UA"), @SerializedName("UG") UG("UG"), @SerializedName("US") US("US"), @SerializedName("UY") UY("UY"), @SerializedName("UZ") UZ("UZ"), @SerializedName("VA") VA("VA"), @SerializedName("VC") VC("VC"), @SerializedName("VE") VE("VE"), @SerializedName("VG") VG("VG"), @SerializedName("VN") VN("VN"), @SerializedName("VU") VU("VU"), @SerializedName("WF") WF("WF"), @SerializedName("WS") WS("WS"), @SerializedName("XK") XK("XK"), @SerializedName("YE") YE("YE"), @SerializedName("YT") YT("YT"), @SerializedName("ZA") ZA("ZA"), @SerializedName("ZM") ZM("ZM"), @SerializedName("ZW") ZW("ZW"), @SerializedName("ZZ") ZZ("ZZ"); @Getter(onMethod_ = {@Override}) private final String value; AllowedCountry(String value) { this.value = value; } } } @Getter public static class SubscriptionData { @SerializedName("application_fee_percent") BigDecimal applicationFeePercent; /** * The ID of the coupon to apply to this subscription. A coupon applied to a subscription will * only affect invoices created for that particular subscription. */ @SerializedName("coupon") String coupon; /** * The tax rates that will apply to any subscription item that does not have {@code tax_rates} * set. Invoices created will have their {@code default_tax_rates} populated from the * subscription. */ @SerializedName("default_tax_rates") List<String> defaultTaxRates; /** * Map of extra parameters for custom features not available in this client library. The content * in this map is not serialized under this field's {@code @SerializedName} value. Instead, each * key/value pair is serialized as if the key is a root-level field (serialized) name in this * param object. Effectively, this map is flattened to its parent instance. */ @SerializedName(ApiRequestParams.EXTRA_PARAMS_KEY) Map<String, Object> extraParams; /** * A list of items, each with an attached plan, that the customer is subscribing to. Prefer * using {@code line_items}. */ @SerializedName("items") List<Item> items; @SerializedName("metadata") Map<String, String> metadata; /** * Unix timestamp representing the end of the trial period the customer will get before being * charged for the first time. Has to be at least 48 hours in the future. */ @SerializedName("trial_end") Long trialEnd; @SerializedName("trial_from_plan") Boolean trialFromPlan; /** * Integer representing the number of trial period days before the customer is charged for the * first time. Has to be at least 1. */ @SerializedName("trial_period_days") Long trialPeriodDays; private SubscriptionData( BigDecimal applicationFeePercent, String coupon, List<String> defaultTaxRates, Map<String, Object> extraParams, List<Item> items, Map<String, String> metadata, Long trialEnd, Boolean trialFromPlan, Long trialPeriodDays) { this.applicationFeePercent = applicationFeePercent; this.coupon = coupon; this.defaultTaxRates = defaultTaxRates; this.extraParams = extraParams; this.items = items; this.metadata = metadata; this.trialEnd = trialEnd; this.trialFromPlan = trialFromPlan; this.trialPeriodDays = trialPeriodDays; } public static Builder builder() { return new Builder(); } public static class Builder { private BigDecimal applicationFeePercent; private String coupon; private List<String> defaultTaxRates; private Map<String, Object> extraParams; private List<Item> items; private Map<String, String> metadata; private Long trialEnd; private Boolean trialFromPlan; private Long trialPeriodDays; /** Finalize and obtain parameter instance from this builder. */ public SubscriptionData build() { return new SubscriptionData( this.applicationFeePercent, this.coupon, this.defaultTaxRates, this.extraParams, this.items, this.metadata, this.trialEnd, this.trialFromPlan, this.trialPeriodDays); } public Builder setApplicationFeePercent(BigDecimal applicationFeePercent) { this.applicationFeePercent = applicationFeePercent; return this; } /** * The ID of the coupon to apply to this subscription. A coupon applied to a subscription will * only affect invoices created for that particular subscription. */ public Builder setCoupon(String coupon) { this.coupon = coupon; return this; } /** * Add an element to `defaultTaxRates` list. A list is initialized for the first `add/addAll` * call, and subsequent calls adds additional elements to the original list. See {@link * SessionCreateParams.SubscriptionData#defaultTaxRates} for the field documentation. */ public Builder addDefaultTaxRate(String element) { if (this.defaultTaxRates == null) { this.defaultTaxRates = new ArrayList<>(); } this.defaultTaxRates.add(element); return this; } /** * Add all elements to `defaultTaxRates` list. A list is initialized for the first * `add/addAll` call, and subsequent calls adds additional elements to the original list. See * {@link SessionCreateParams.SubscriptionData#defaultTaxRates} for the field documentation. */ public Builder addAllDefaultTaxRate(List<String> elements) { if (this.defaultTaxRates == null) { this.defaultTaxRates = new ArrayList<>(); } this.defaultTaxRates.addAll(elements); return this; } /** * Add a key/value pair to `extraParams` map. A map is initialized for the first `put/putAll` * call, and subsequent calls add additional key/value pairs to the original map. See {@link * SessionCreateParams.SubscriptionData#extraParams} for the field documentation. */ public Builder putExtraParam(String key, Object value) { if (this.extraParams == null) { this.extraParams = new HashMap<>(); } this.extraParams.put(key, value); return this; } /** * Add all map key/value pairs to `extraParams` map. A map is initialized for the first * `put/putAll` call, and subsequent calls add additional key/value pairs to the original map. * See {@link SessionCreateParams.SubscriptionData#extraParams} for the field documentation. */ public Builder putAllExtraParam(Map<String, Object> map) { if (this.extraParams == null) { this.extraParams = new HashMap<>(); } this.extraParams.putAll(map); return this; } /** * Add an element to `items` list. A list is initialized for the first `add/addAll` call, and * subsequent calls adds additional elements to the original list. See {@link * SessionCreateParams.SubscriptionData#items} for the field documentation. */ public Builder addItem(Item element) { if (this.items == null) { this.items = new ArrayList<>(); } this.items.add(element); return this; } /** * Add all elements to `items` list. A list is initialized for the first `add/addAll` call, * and subsequent calls adds additional elements to the original list. See {@link * SessionCreateParams.SubscriptionData#items} for the field documentation. */ public Builder addAllItem(List<Item> elements) { if (this.items == null) { this.items = new ArrayList<>(); } this.items.addAll(elements); return this; } /** * Add a key/value pair to `metadata` map. A map is initialized for the first `put/putAll` * call, and subsequent calls add additional key/value pairs to the original map. See {@link * SessionCreateParams.SubscriptionData#metadata} for the field documentation. */ public Builder putMetadata(String key, String value) { if (this.metadata == null) { this.metadata = new HashMap<>(); } this.metadata.put(key, value); return this; } /** * Add all map key/value pairs to `metadata` map. A map is initialized for the first * `put/putAll` call, and subsequent calls add additional key/value pairs to the original map. * See {@link SessionCreateParams.SubscriptionData#metadata} for the field documentation. */ public Builder putAllMetadata(Map<String, String> map) { if (this.metadata == null) { this.metadata = new HashMap<>(); } this.metadata.putAll(map); return this; } /** * Unix timestamp representing the end of the trial period the customer will get before being * charged for the first time. Has to be at least 48 hours in the future. */ public Builder setTrialEnd(Long trialEnd) { this.trialEnd = trialEnd; return this; } public Builder setTrialFromPlan(Boolean trialFromPlan) { this.trialFromPlan = trialFromPlan; return this; } /** * Integer representing the number of trial period days before the customer is charged for the * first time. Has to be at least 1. */ public Builder setTrialPeriodDays(Long trialPeriodDays) { this.trialPeriodDays = trialPeriodDays; return this; } } @Getter public static class Item { /** * Map of extra parameters for custom features not available in this client library. The * content in this map is not serialized under this field's {@code @SerializedName} value. * Instead, each key/value pair is serialized as if the key is a root-level field (serialized) * name in this param object. Effectively, this map is flattened to its parent instance. */ @SerializedName(ApiRequestParams.EXTRA_PARAMS_KEY) Map<String, Object> extraParams; /** Plan ID for this item. */ @SerializedName("plan") String plan; /** Quantity for this item. */ @SerializedName("quantity") Long quantity; /** * The tax rates which apply to this item. When set, the {@code default_tax_rates} on {@code * subscription_data} do not apply to this item. */ @SerializedName("tax_rates") List<String> taxRates; private Item( Map<String, Object> extraParams, String plan, Long quantity, List<String> taxRates) { this.extraParams = extraParams; this.plan = plan; this.quantity = quantity; this.taxRates = taxRates; } public static Builder builder() { return new Builder(); } public static class Builder { private Map<String, Object> extraParams; private String plan; private Long quantity; private List<String> taxRates; /** Finalize and obtain parameter instance from this builder. */ public Item build() { return new Item(this.extraParams, this.plan, this.quantity, this.taxRates); } /** * Add a key/value pair to `extraParams` map. A map is initialized for the first * `put/putAll` call, and subsequent calls add additional key/value pairs to the original * map. See {@link SessionCreateParams.SubscriptionData.Item#extraParams} for the field * documentation. */ public Builder putExtraParam(String key, Object value) { if (this.extraParams == null) { this.extraParams = new HashMap<>(); } this.extraParams.put(key, value); return this; } /** * Add all map key/value pairs to `extraParams` map. A map is initialized for the first * `put/putAll` call, and subsequent calls add additional key/value pairs to the original * map. See {@link SessionCreateParams.SubscriptionData.Item#extraParams} for the field * documentation. */ public Builder putAllExtraParam(Map<String, Object> map) { if (this.extraParams == null) { this.extraParams = new HashMap<>(); } this.extraParams.putAll(map); return this; } /** Plan ID for this item. */ public Builder setPlan(String plan) { this.plan = plan; return this; } /** Quantity for this item. */ public Builder setQuantity(Long quantity) { this.quantity = quantity; return this; } /** * Add an element to `taxRates` list. A list is initialized for the first `add/addAll` call, * and subsequent calls adds additional elements to the original list. See {@link * SessionCreateParams.SubscriptionData.Item#taxRates} for the field documentation. */ public Builder addTaxRate(String element) { if (this.taxRates == null) { this.taxRates = new ArrayList<>(); } this.taxRates.add(element); return this; } /** * Add all elements to `taxRates` list. A list is initialized for the first `add/addAll` * call, and subsequent calls adds additional elements to the original list. See {@link * SessionCreateParams.SubscriptionData.Item#taxRates} for the field documentation. */ public Builder addAllTaxRate(List<String> elements) { if (this.taxRates == null) { this.taxRates = new ArrayList<>(); } this.taxRates.addAll(elements); return this; } } } } public enum BillingAddressCollection implements ApiRequestParams.EnumParam { @SerializedName("auto") AUTO("auto"), @SerializedName("required") REQUIRED("required"); @Getter(onMethod_ = {@Override}) private final String value; BillingAddressCollection(String value) { this.value = value; } } public enum Locale implements ApiRequestParams.EnumParam { @SerializedName("auto") AUTO("auto"), @SerializedName("bg") BG("bg"), @SerializedName("cs") CS("cs"), @SerializedName("da") DA("da"), @SerializedName("de") DE("de"), @SerializedName("el") EL("el"), @SerializedName("en") EN("en"), @SerializedName("en-GB") EN_GB("en-GB"), @SerializedName("es") ES("es"), @SerializedName("es-419") ES_419("es-419"), @SerializedName("et") ET("et"), @SerializedName("fi") FI("fi"), @SerializedName("fr") FR("fr"), @SerializedName("fr-CA") FR_CA("fr-CA"), @SerializedName("hu") HU("hu"), @SerializedName("id") ID("id"), @SerializedName("it") IT("it"), @SerializedName("ja") JA("ja"), @SerializedName("lt") LT("lt"), @SerializedName("lv") LV("lv"), @SerializedName("ms") MS("ms"), @SerializedName("mt") MT("mt"), @SerializedName("nb") NB("nb"), @SerializedName("nl") NL("nl"), @SerializedName("pl") PL("pl"), @SerializedName("pt") PT("pt"), @SerializedName("pt-BR") PT_BR("pt-BR"), @SerializedName("ro") RO("ro"), @SerializedName("ru") RU("ru"), @SerializedName("sk") SK("sk"), @SerializedName("sl") SL("sl"), @SerializedName("sv") SV("sv"), @SerializedName("tr") TR("tr"), @SerializedName("zh") ZH("zh"), @SerializedName("zh-HK") ZH_HK("zh-HK"), @SerializedName("zh-TW") ZH_TW("zh-TW"); @Getter(onMethod_ = {@Override}) private final String value; Locale(String value) { this.value = value; } } public enum Mode implements ApiRequestParams.EnumParam { @SerializedName("payment") PAYMENT("payment"), @SerializedName("setup") SETUP("setup"), @SerializedName("subscription") SUBSCRIPTION("subscription"); @Getter(onMethod_ = {@Override}) private final String value; Mode(String value) { this.value = value; } } public enum PaymentMethodType implements ApiRequestParams.EnumParam { @SerializedName("alipay") ALIPAY("alipay"), @SerializedName("bacs_debit") BACS_DEBIT("bacs_debit"), @SerializedName("bancontact") BANCONTACT("bancontact"), @SerializedName("card") CARD("card"), @SerializedName("eps") EPS("eps"), @SerializedName("fpx") FPX("fpx"), @SerializedName("giropay") GIROPAY("giropay"), @SerializedName("ideal") IDEAL("ideal"), @SerializedName("p24") P24("p24"), @SerializedName("sepa_debit") SEPA_DEBIT("sepa_debit"), @SerializedName("sofort") SOFORT("sofort"); @Getter(onMethod_ = {@Override}) private final String value; PaymentMethodType(String value) { this.value = value; } } public enum SubmitType implements ApiRequestParams.EnumParam { @SerializedName("auto") AUTO("auto"), @SerializedName("book") BOOK("book"), @SerializedName("donate") DONATE("donate"), @SerializedName("pay") PAY("pay"); @Getter(onMethod_ = {@Override}) private final String value; SubmitType(String value) { this.value = value; } } }
package com.wizzardo.http.framework; import com.wizzardo.epoll.readable.ReadableData; import com.wizzardo.http.Handler; import com.wizzardo.http.MultiValue; import com.wizzardo.http.framework.di.DependencyFactory; import com.wizzardo.http.framework.template.Renderer; import com.wizzardo.http.request.Parameters; import com.wizzardo.http.request.Request; import com.wizzardo.http.response.Response; import com.wizzardo.http.response.Status; import com.wizzardo.tools.collections.CollectionTools; import com.wizzardo.tools.json.JsonTools; import com.wizzardo.tools.misc.Mapper; import com.wizzardo.tools.misc.Unchecked; import java.io.IOException; import java.lang.reflect.*; import java.lang.reflect.Parameter; import java.util.*; public class ControllerHandler<T extends Controller> implements Handler { protected static final Set<Class> PARSABLE_TYPES = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( String.class, Integer.class, Long.class, Short.class, Byte.class, Float.class, Double.class, Boolean.class, Character.class ))); protected Class<T> controller; protected String controllerName; protected String actionName; protected CollectionTools.Closure<ReadableData, T> renderer; public ControllerHandler(Class<T> controller, String action) { this.controller = controller; controllerName = Controller.getControllerName(controller); actionName = action; renderer = createRenderer(controller, action); } public ControllerHandler(Class<T> controller, String action, CollectionTools.Closure<ReadableData, T> renderer) { this.controller = controller; this.renderer = renderer; controllerName = Controller.getControllerName(controller); actionName = action; } @Override public String name() { return getControllerName() + "." + getActionName(); } @Override public Response handle(Request request, Response response) throws IOException { // request.controller(controllerName); // request.action(actionName); RequestContext context = (RequestContext) Thread.currentThread(); context.setController(controllerName); context.setAction(actionName); T c = DependencyFactory.get(controller); c.request = request; c.response = response; ReadableData data = renderer.execute(c); if (data != null) response.setBody(data); return response; } protected CollectionTools.Closure<ReadableData, T> createRenderer(Class<T> controller, String action) { Method actionMethod = findAction(controller, action); return createRenderer(actionMethod); } protected CollectionTools.Closure<ReadableData, T> createRenderer(Method method) { if (method.getParameterCount() == 0) { return it -> { Renderer renderer = Unchecked.call(() -> (Renderer) method.invoke(it)); return renderer != null ? renderer.renderReadableData() : null; }; } else { Parameter[] parameters = method.getParameters(); for (Parameter parameter : parameters) { if (parameter.isNamePresent()) continue; if (parameter.isAnnotationPresent(com.wizzardo.http.framework.Parameter.class)) continue; Class<?> type = parameter.getType(); if (type.isPrimitive() || type.isEnum() || PARSABLE_TYPES.contains(type)) throw new IllegalStateException("Can't parse parameters for '" + controllerName + "." + actionName + "', parameters names are not present. Please run javac with '-parameters' or add an annotation Parameter"); } Mapper<Parameters, Object>[] argsMappers = new Mapper[parameters.length]; Type[] types = method.getGenericParameterTypes(); for (int i = 0; i < parameters.length; i++) { argsMappers[i] = createParametersMapper(parameters[i], types[i]); } return it -> { Mapper<Parameters, Object>[] mappers = argsMappers; Object[] args = new Object[mappers.length]; Parameters params = it.getParams(); Exceptions exceptions = null; for (int i = 0; i < mappers.length; i++) { try { args[i] = mappers[i].map(params); } catch (Exception e) { if (exceptions == null) exceptions = new Exceptions(mappers.length); // e.printStackTrace(); exceptions.add(e.getClass().getCanonicalName() + ": " + e.getMessage()); } } if (exceptions != null) { it.response.setBody(JsonTools.serialize(exceptions)).status(Status._400); return null; } Renderer renderer = Unchecked.call(() -> (Renderer) method.invoke(it, args)); return renderer != null ? renderer.renderReadableData() : null; }; } } static class Exceptions { List<String> messages; Exceptions(int initSize) { messages = new ArrayList<>(initSize); } public void add(String message) { messages.add(message); } } protected String getParameterName(Parameter parameter) { if (parameter.isNamePresent()) return parameter.getName(); com.wizzardo.http.framework.Parameter annotation = parameter.getAnnotation(com.wizzardo.http.framework.Parameter.class); if (annotation != null) return annotation.name(); return null; } protected Mapper<Parameters, Object> createParametersMapper(Parameter parameter, Class type) { String name = getParameterName(parameter); com.wizzardo.http.framework.Parameter annotation = parameter.getAnnotation(com.wizzardo.http.framework.Parameter.class); String def = annotation != null ? annotation.def() : null; Mapper<Mapper<String, Object>, Mapper<Parameters, Object>> failIfEmpty = mapper -> { return params -> { MultiValue multiValue = params.get(name); String value; if (multiValue != null) value = multiValue.getValue(); else value = def; if (value == null || value.isEmpty()) throw new NullPointerException("parameter '" + name + "' it not present"); return mapper.map(value); }; }; if (type.isPrimitive()) { if (type == int.class) return failIfEmpty.map(Integer::parseInt); if (type == long.class) return failIfEmpty.map(Long::parseLong); if (type == float.class) return failIfEmpty.map(Float::parseFloat); if (type == double.class) return failIfEmpty.map(Double::parseDouble); if (type == boolean.class) return failIfEmpty.map(Boolean::parseBoolean); if (type == short.class) return failIfEmpty.map(Short::parseShort); if (type == byte.class) return failIfEmpty.map(Byte::parseByte); if (type == char.class) return failIfEmpty.map(ControllerHandler::parseChar); } Mapper<Mapper<String, Object>, Mapper<Parameters, Object>> parseNonNull = mapper -> { return params -> { MultiValue multiValue = params.get(name); String value; if (multiValue != null) value = multiValue.getValue(); else value = def; if (value == null || value.isEmpty()) return null; return mapper.map(value); }; }; if (type.isEnum()) return parseNonNull.map(value -> Enum.valueOf((Class<? extends Enum>) type, value)); if (type == String.class) return parseNonNull.map(value -> value); if (type == Integer.class) return parseNonNull.map(Integer::valueOf); if (type == Long.class) return parseNonNull.map(Long::valueOf); if (type == Float.class) return parseNonNull.map(Float::valueOf); if (type == Double.class) return parseNonNull.map(Double::valueOf); if (type == Boolean.class) return parseNonNull.map(Boolean::valueOf); if (type == Short.class) return parseNonNull.map(Short::valueOf); if (type == Byte.class) return parseNonNull.map(Byte::valueOf); if (type == Character.class) return parseNonNull.map(ControllerHandler::parseChar); if (type.isArray()) { Class subtype = type.getComponentType(); if (subtype.isPrimitive()) { if (subtype == int.class) return new ArrayConstructor<>(name, int[]::new, (arr, values) -> { for (int i = 0; i < values.size(); i++) { arr[i] = Integer.parseInt(values.get(i)); } return arr; }); if (subtype == long.class) return new ArrayConstructor<>(name, long[]::new, (arr, values) -> { for (int i = 0; i < values.size(); i++) { arr[i] = Long.parseLong(values.get(i)); } return arr; }); if (subtype == float.class) return new ArrayConstructor<>(name, float[]::new, (arr, values) -> { for (int i = 0; i < values.size(); i++) { arr[i] = Float.parseFloat(values.get(i)); } return arr; }); if (subtype == double.class) return new ArrayConstructor<>(name, double[]::new, (arr, values) -> { for (int i = 0; i < values.size(); i++) { arr[i] = Double.parseDouble(values.get(i)); } return arr; }); if (subtype == boolean.class) return new ArrayConstructor<>(name, boolean[]::new, (arr, values) -> { for (int i = 0; i < values.size(); i++) { arr[i] = Boolean.parseBoolean(values.get(i)); } return arr; }); if (subtype == short.class) return new ArrayConstructor<>(name, short[]::new, (arr, values) -> { for (int i = 0; i < values.size(); i++) { arr[i] = Short.parseShort(values.get(i)); } return arr; }); if (subtype == byte.class) return new ArrayConstructor<>(name, byte[]::new, (arr, values) -> { for (int i = 0; i < values.size(); i++) { arr[i] = Byte.parseByte(values.get(i)); } return arr; }); if (subtype == char.class) return new ArrayConstructor<>(name, char[]::new, (arr, values) -> { for (int i = 0; i < values.size(); i++) { arr[i] = parseChar(values.get(i)); } return arr; }); } } throw new IllegalArgumentException("Can't create mapper for parameter '" + name + "' of type '" + type + "' in '" + controllerName + "." + actionName + "'"); } static char parseChar(String value) { if (value.length() > 1) throw new IllegalArgumentException("Can't assign to char String with more then 1 character"); return value.charAt(0); } static class ArrayConstructor<T> implements Mapper<Parameters, Object> { final String name; final Mapper<Integer, T> creator; final CollectionTools.Closure2<T, T, List<String>> populator; ArrayConstructor(String name, Mapper<Integer, T> creator, CollectionTools.Closure2<T, T, List<String>> populator) { this.name = name; this.creator = creator; this.populator = populator; } @Override public T map(Parameters parameters) { MultiValue multiValue = parameters.get(name); if (multiValue != null) { T t = creator.map(multiValue.size()); return populator.execute(t, multiValue.getValues()); } return null; } } protected Mapper<Parameters, Object> createParametersMapper(Parameter parameter, Type genericType) { if (genericType instanceof Class) return createParametersMapper(parameter, ((Class) genericType)); if (genericType instanceof ParameterizedType) { ParameterizedType type = (ParameterizedType) genericType; if (type.getRawType().equals(Optional.class)) { Mapper<Parameters, Object> mapper = createParametersMapper(parameter, type.getActualTypeArguments()[0]); return parameters -> Optional.ofNullable(mapper.map(parameters)); } } throw new IllegalArgumentException("Can't create mapper for parameter '" + parameter.getName() + "' of type '" + genericType + "' in '" + controllerName + "." + actionName + "'"); } protected Method findAction(Class clazz, String action) { for (Method method : clazz.getDeclaredMethods()) { if ((method.getModifiers() & Modifier.STATIC) == 0 && method.getName().equals(action)) { method.setAccessible(true); return method; } } throw new IllegalStateException("Can't find action '" + action + "' in class '" + clazz + "'"); } public String getActionName() { return actionName; } public String getControllerName() { return controllerName; } }
package com.xpn.xwiki.objects.classes; import com.xpn.xwiki.objects.meta.PropertyMetaClass; import com.xpn.xwiki.objects.BaseCollection; import com.xpn.xwiki.objects.BaseProperty; import com.xpn.xwiki.objects.ListProperty; import com.xpn.xwiki.objects.DBStringListProperty; import com.xpn.xwiki.XWikiContext; import java.util.*; import org.apache.velocity.VelocityContext; import org.apache.ecs.xhtml.select; import org.apache.ecs.xhtml.option; import org.apache.commons.lang.StringUtils; public class DBTreeListClass extends DBListClass { public DBTreeListClass(PropertyMetaClass wclass) { super("dbtreelist", "DB Tree List", wclass); } public DBTreeListClass() { this(null); } public String getParentField() { return getStringValue("parentField"); } public void setParentField(String parentField) { setStringValue("parentField", parentField); } public Map getTreeMap(XWikiContext context) { List list = getDBList(context); Map map = new HashMap(); if ((list==null)||(list.size()==0)) return map; for(int i=0;i<list.size();i++) { Object result = list.get(i); if (result instanceof String) { ListItem item = new ListItem((String)result); map.put(result, item); } else { ListItem item = (ListItem) result; addToList(map, item.getParent(), item); } } return map; } /** * Gets an ordered list of items in the tree * This is necessary to make sure childs are coming after their parents * @param treemap * @return list of ListItems */ protected List getTreeList(Map treemap) { List list = new ArrayList(); addToTreeList(list, treemap, ""); return list; } protected void addToTreeList(List treelist, Map treemap, String parent) { List list = (List)treemap.get(parent); if (list!=null) { for (int i=0;i<list.size();i++) { ListItem item = (ListItem) list.get(i); treelist.add(item); addToTreeList(treelist, treemap, item.getId()); } } } protected void addToList(Map map, String key, ListItem item) { List list = (List)map.get(key); if (list==null) { list = new ArrayList(); map.put(key, list); } list.add(item); } public void displayView(StringBuffer buffer, String name, String prefix, BaseCollection object, XWikiContext context) { List selectlist; BaseProperty prop = (BaseProperty) object.safeget(name); if (prop == null) { selectlist = new ArrayList(); } else if ((prop instanceof ListProperty) || (prop instanceof DBStringListProperty)) { selectlist = (List) prop.getValue(); } else { selectlist = new ArrayList(); selectlist.add(prop.getValue()); } String result = displayTree(name, prefix, selectlist, "view", context); if (result.equals("")) super.displayView(buffer, name, prefix, object, context); else buffer.append(result); } public void displayEdit(StringBuffer buffer, String name, String prefix, BaseCollection object, XWikiContext context) { List selectlist; BaseProperty prop = (BaseProperty) object.safeget(name); if (prop == null) { selectlist = new ArrayList(); } else if ((prop instanceof ListProperty) || (prop instanceof DBStringListProperty)) { selectlist = (List) prop.getValue(); } else { selectlist = new ArrayList(); selectlist.add(prop.getValue()); } if (isPicker()) { String result = displayTree(name, prefix, selectlist, "edit", context); if (result.equals("")) displayTreeSelectEdit(buffer, name, prefix, object, context); else { displayHidden(buffer, name, prefix, object, context); buffer.append(result); } } else { displayTreeSelectEdit(buffer, name, prefix, object, context); } } private String displayTree(String name, String prefix, List selectlist, String mode, XWikiContext context){ VelocityContext vcontext = (VelocityContext) context.get("vcontext"); Map map = getTreeMap(context); vcontext.put("selectlist", selectlist); vcontext.put("fieldname", prefix + name); vcontext.put("tree", map); vcontext.put("treelist", getTreeList(map)); vcontext.put("mode", mode); return context.getWiki().parseTemplate("treeview.vm", context); } protected void addToSelect(select select, List selectlist, Map map, Map treemap, String parent, String level, XWikiContext context) { List list = (List)treemap.get(parent); if (list!=null) { for (int i=0;i<list.size();i++) { ListItem item = (ListItem) list.get(i); String display = level + getDisplayValue(item.getId(), map, context); option option = new option(item.getId(), item.getId()); option.addElement(display); if (selectlist.contains(item.getId())) option.setSelected(true); select.addElement(option); addToSelect(select, selectlist, map, treemap, item.getId(), level + "&nbsp;", context); } } } protected void displayTreeSelectEdit(StringBuffer buffer, String name, String prefix, BaseCollection object, XWikiContext context) { select select = new select(prefix + name, 1); select.setMultiple(isMultiSelect()); select.setSize(getSize()); select.setName(prefix + name); select.setID(prefix + name); Map map = getMap(context); Map treemap = getTreeMap(context); List selectlist; BaseProperty prop = (BaseProperty) object.safeget(name); if (prop == null) { selectlist = new ArrayList(); } else if ((prop instanceof ListProperty) || (prop instanceof DBStringListProperty)) { selectlist = (List) prop.getValue(); } else { selectlist = new ArrayList(); selectlist.add(prop.getValue()); } // Add options from Set addToSelect(select, selectlist, map, treemap, "", "", context); buffer.append(select.toString()); } public String getQuery(XWikiContext context) { String sql = getSql(); if ((sql==null)||(sql.trim().equals(""))) { String classname = getClassname(); String idField = getIdField(); String valueField = getValueField(); String parentField = getParentField(); if ((valueField==null)||(valueField.trim().equals(""))) valueField = idField; if (context.getWiki().getHibernateStore()!=null) { String select = "select "; String tables = " from XWikiDocument as doc, BaseObject as obj"; String where = " where doc.fullName=obj.name and obj.className='" + classname + "'"; if (idField.startsWith("doc.")||idField.startsWith("obj.")) select += idField + ","; else { select += "idprop.value,"; tables += ", StringProperty as idprop"; where += " and obj.id=idprop.id.id and idprop.id.name='" + idField + "'"; } if (valueField.startsWith("doc.")||valueField.startsWith("obj.")) select += valueField + ","; else { if (idField.equals(valueField)) { select += "idprop.value,"; } else { select += "valueprop.value,"; tables += ", StringProperty as valueprop"; where += " and obj.id=valueprop.id.id and valueprop.id.name='" + valueField + "'"; } } if (parentField.startsWith("doc.")||parentField.startsWith("obj.")) select += parentField + ","; else { if (idField.equals(parentField)) { select += "idprop.value,"; } else if (valueField.equals(parentField)) { select += "valueprop.value,"; } else { select += "parentprop.value,"; tables += ", StringProperty as parentprop"; where += " and obj.id=parentprop.id.id and parentprop.id.name='" + parentField + "'"; } } // Let's create the sql sql = select + tables + where; } else { // TODO: query plugin impl. // We need to generate the right query for the query plugin } } return sql; } }
package com.zenfield.database.dialect; import com.zenfield.core.Check; import com.zenfield.core.Closeables; import com.zenfield.core.Exceptions; import com.zenfield.core.Files; import com.zenfield.core.Lists; import com.zenfield.core.Processes; import com.zenfield.core.Strings; import com.zenfield.database.configuration.Environment; import com.zenfield.database.configuration.ReadOnly; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** * * @author MICSKO Viktor (viktor@zenfield.com) */ public class PostgresDialect implements Dialect { private static final String QUERY_LIST_TABLES = "SELECT tablename FROM pg_tables WHERE schemaname='public'"; private static final String QUERY_CLEAR = "DROP SCHEMA public CASCADE; CREATE SCHEMA public;"; @Override public String getName() { return "PostgreSQL"; } @Override public List<String> listTables(Environment environment) { Check.notNull(environment); try { ProcessBuilder builder = createQueryBuilder(environment, QUERY_LIST_TABLES); List<String> result = new ArrayList<>(); Integer exitCode = Processes.execute(builder, result); if (exitCode == null) { System.err.println("Cannot retrieve the tables: null exit code"); return null; } if (exitCode != 0) { System.err.println("Cannot retrieve the tables: exit code was " + exitCode); return null; } return result .stream() .map(s -> s == null ? "" : s.trim()) .filter(s -> !Strings.isEmpty(s)) .collect(Collectors.toList()); } catch (IOException e) { Exceptions.print(e, System.err); return null; } } @Override public int countRows(Environment environment, String table) { Check.notNull(environment); Check.notEmpty(table); try { ProcessBuilder builder = createQueryBuilder(environment, "SELECT COUNT(*) FROM " + table); List<String> result = new ArrayList<>(); Integer exitCode = Processes.execute(builder, result); if (exitCode == null) { System.err.println("Cannot count rows: null exit code"); return -1; } if (exitCode != 0) { System.err.println("Cannot count rows: exit code was " + exitCode); return -1; } if (Lists.isEmpty(result)) { return -1; } String first = result.get(0); if (Strings.isEmpty(first)) { return -1; } first = first.trim(); return Integer.parseInt(first); } catch (NumberFormatException e) { return -1; } catch (IOException e) { Exceptions.print(e, System.err); return -1; } } @Override public boolean clear(Environment environment) { Check.notNull(environment); if (environment.getReadOnly() == ReadOnly.TRUE) { System.err.println("Cannot clear the database: read-only environment"); return false; } try { ProcessBuilder builder = createQueryBuilder(environment, QUERY_CLEAR); List<String> result = new ArrayList<>(); Integer exitCode = Processes.execute(builder, result); if (exitCode == null) { System.err.println("Cannot clear the database: null exit code"); return false; } if (exitCode != 0) { System.err.println("Cannot clear the database: exit code was " + exitCode); return false; } if (Lists.isEmpty(result)) { return false; } for (String line : result) { System.out.println(line); } return true; } catch (NumberFormatException e) { return false; } catch (IOException e) { Exceptions.print(e, System.err); return false; } } @Override public boolean execute(Environment environment, File script) { Check.notNull(environment); Check.notNull(script); if (environment.getReadOnly() == ReadOnly.TRUE) { System.err.println("Cannot execute a script: read-only environment"); return false; } if (!script.exists()) { System.err.println("File not found: " + script.getName()); return false; } if (!script.isFile()) { System.err.println("Not a file: " + script.getName()); return false; } try { ProcessBuilder builder; if (environment.isSsh()) { builder = new ProcessBuilder( "ssh", "-C", environment.getSshUsernameHostname(), "PGPASSWORD=" + environment.getPassword(), "psql", "-q", "-wU", environment.getUsername(), "-h", environment.getHostname(), environment.getDatabase(), "-q1"); builder.redirectInput(script.getAbsoluteFile()); } else { builder = new ProcessBuilder( "psql", "-q", "-wU", environment.getUsername(), "-h", environment.getHostname(), environment.getDatabase(), "-q1f", script.getAbsolutePath()); builder.environment().put("PGPASSWORD", environment.getPassword()); } builder.redirectError(ProcessBuilder.Redirect.INHERIT); builder.redirectOutput(ProcessBuilder.Redirect.INHERIT); Process process = builder.start(); int exitCode = process.waitFor(); if (exitCode != 0) { System.err.println("Cannot execute: exit code was " + exitCode); return false; } return true; } catch (InterruptedException e) { return false; } catch (IOException e) { Exceptions.print(e, System.err); return false; } } @Override public boolean dump(Environment environment, File file) { Check.notNull(environment); Check.notNull(file); ProcessBuilder builder; if (environment.isSsh()) { builder = new ProcessBuilder( "ssh", "-C", environment.getSshUsernameHostname(), "PGPASSWORD=" + environment.getPassword(), "pg_dump", "-wU", environment.getUsername(), "-h", environment.getHostname(), "--no-owner", environment.getDatabase()); } else { builder = new ProcessBuilder( "pg_dump", "-wU", environment.getUsername(), "-h", environment.getHostname(), "--no-owner", environment.getDatabase()); builder.environment().put("PGPASSWORD", environment.getPassword()); } List<String> lines = new ArrayList<>(); try { Integer exitCode = Processes.execute(builder, lines); if (exitCode == null) { System.err.println("Cannot dump the database: null exit code"); return false; } if (exitCode != 0) { System.err.println("Cannot dump the database: exit code was " + exitCode); return false; } } catch (IOException e) { Exceptions.print(e, System.err); return false; } try (Writer writer = new FileWriter(file)) { for (String line : lines) { if (line != null && !line.contains("REVOKE ALL ON SCHEMA") && !line.contains("GRANT ALL ON SCHEMA")) { writer.write(line); writer.write('\n'); } } return true; } catch (IOException e) { Exceptions.print(e, System.err); return false; } } @Override public boolean dump(Environment environment, String table, File file) { Check.notNull(environment); Check.notEmpty(table); Check.notNull(file); ProcessBuilder builder; if (environment.isSsh()) { builder = new ProcessBuilder( "ssh", "-C", environment.getSshUsernameHostname(), "PGPASSWORD=" + environment.getPassword(), "pg_dump", "-wU", environment.getUsername(), "-h", environment.getHostname(), "--no-owner", "-t", table, "-a", environment.getDatabase()); } else { builder = new ProcessBuilder( "pg_dump", "-wU", environment.getUsername(), "-h", environment.getHostname(), "--no-owner", "-t", table, "-a", environment.getDatabase()); builder.environment().put("PGPASSWORD", environment.getPassword()); } try { Integer exitCode = Processes.save(builder, file); if (exitCode == null) { System.err.println("Cannot dump the database: null exit code"); return false; } if (exitCode != 0) { System.err.println("Cannot dump the database: exit code was " + exitCode); return false; } return cleanup(file); } catch (IOException e) { Exceptions.print(e, System.err); return false; } } private boolean cleanup(File file) { Check.notNull(file); if (!file.exists()) { System.err.println("File not found: " + file.getAbsolutePath()); return false; } if (!file.isFile()) { System.err.println("Not a file: " + file.getAbsolutePath()); return false; } File tmp = null; BufferedReader reader = null; BufferedWriter writer = null; try { tmp = File.createTempFile("db-", ".sql"); reader = new BufferedReader(new FileReader(file)); writer = new BufferedWriter(new FileWriter(tmp)); String line; while ((line = reader.readLine()) != null) { if (line == null || Strings.isEmpty(line.trim()) || line.startsWith(" || line.startsWith("SET ")) { continue; } writer.append(line); writer.newLine(); } } catch (IOException e) { Exceptions.print(e, System.err); Files.delete(tmp); return false; } finally { Closeables.close(reader); Closeables.close(writer); } if (tmp == null) { return false; } try { java.nio.file.Files.move(tmp.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING); return true; } catch (IOException e) { Exceptions.print(e, System.err); return false; } finally { Files.delete(tmp); } } private ProcessBuilder createQueryBuilder(Environment environment, String query) { Check.notNull(environment); Check.notEmpty(query); if (environment.isSsh()) { return new ProcessBuilder( "ssh", "-C", environment.getSshUsernameHostname(), "PGPASSWORD=" + environment.getPassword(), "psql", "-q", "-wU", environment.getUsername(), "-h", environment.getHostname(), environment.getDatabase(), "-tc", "\"" + query + "\""); } else { ProcessBuilder builder = new ProcessBuilder( "psql", "-q", "-wU", environment.getUsername(), "-h", environment.getHostname(), environment.getDatabase(), "-tc", query); builder.environment().put("PGPASSWORD", environment.getPassword()); return builder; } } }
package com.zimmerbell.repaper.sources; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import org.apache.commons.io.FileUtils; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.iq80.leveldb.*; import static org.fusesource.leveldbjni.JniDBFactory.*; import com.zimmerbell.repaper.Source; public class MomentumSource implements Source { private static final Logger LOG = LoggerFactory.getLogger(MomentumSource.class); public final static String CHROME_PROFILES = System.getenv("LOCALAPPDATA") + "\\Google\\Chrome\\User Data"; public final static String FIREFOX_PROFILES = System.getenv("LOCALAPPDATA") + "\\..\\Roaming\\Mozilla\\Firefox\\Profiles"; public final static String CHROME_LEVELDB_PATH = "\\Local Storage\\leveldb"; private final static String CHROME_EXTENSION_ID = "laookkfknpbbblfpciffpaejjkokdgca"; private final static String FIREFOX_SQLITE_FILE_PATH = "\\webappsstore.sqlite"; private String chromeProfileFolder; private String firefoxProfileFolder; private JSONObject data; public MomentumSource() { long t; t = 0; for (File profileFolder : new File(CHROME_PROFILES).listFiles()) { File extensionDir = new File(profileFolder, "Extensions\\" + CHROME_EXTENSION_ID); if (extensionDir.exists() && extensionDir.length() > 0 && (extensionDir.lastModified() > t)) { t = extensionDir.lastModified(); chromeProfileFolder = profileFolder.getAbsolutePath(); } } LOG.info("using chrome profile: {}", chromeProfileFolder); t = 0; for (File profileFolder : new File(FIREFOX_PROFILES).listFiles()) { File sqliteFile = new File(profileFolder, FIREFOX_SQLITE_FILE_PATH); if (sqliteFile.exists() && sqliteFile.lastModified() > t) { t = sqliteFile.lastModified(); firefoxProfileFolder = profileFolder.getAbsolutePath(); } } LOG.info("using firefox profile: {}", firefoxProfileFolder); } private String getChromeProfileFolder() { return chromeProfileFolder; } private String getFirefoxProfileFolder() { return firefoxProfileFolder; } private String getFirefoxSqliteFile() { String firefoxProfileFolder = getFirefoxProfileFolder(); return firefoxProfileFolder == null ? null : firefoxProfileFolder + FIREFOX_SQLITE_FILE_PATH; } private File getChromeLevelDBFile() { String chromeProfileFolder = getChromeProfileFolder(); return chromeProfileFolder == null ? null : new File(chromeProfileFolder + CHROME_LEVELDB_PATH); } public boolean exists() { return getChromeLevelDBFile() != null || getFirefoxSqliteFile() != null; } @Override public void update() throws Exception { if(updateFromChromeLevelDB()) { return; } if(updateFromFirefoxSqlite()) { return; } } public boolean updateFromChromeLevelDB() throws Exception { if(getChromeLevelDBFile() == null) { return false; } data = new JSONObject(); File tempDir = Files.createTempDirectory("leveldb").toFile(); System.out.println(tempDir); try { FileUtils.copyDirectory(getChromeLevelDBFile(), tempDir); for (File file : tempDir.listFiles()) { if (file.getName().endsWith(".ldb")) { file.renameTo(new File(file.getParentFile(), file.getName().replaceAll("ldb$", "sst"))); } } try (DB db = factory.open(tempDir, new Options()); DBIterator iterator = db.iterator()) { final String KEY_PREFIX = "_chrome-extension://" + CHROME_EXTENSION_ID; for (iterator.seek(bytes(KEY_PREFIX)); iterator.hasNext(); iterator.next()) { String key = asString(iterator.peekNext().getKey()); if (!key.startsWith(KEY_PREFIX)) { break; } key = key.substring(key.indexOf(1) + 1); if (key.equals(getMomentumKey())) { String value = asString(iterator.peekNext().getValue()); value = value.substring(1); LOG.info(key); data = new JSONObject(value); LOG.info(data.toString()); return true; } } } } finally { try { FileUtils.deleteDirectory(tempDir); } catch (IOException e) { LOG.error(e.getMessage(), e); } } return false; } public boolean updateFromFirefoxSqlite() throws Exception { String sqliteFile = getFirefoxSqliteFile(); if(sqliteFile == null) { return false; } data = new JSONObject(); Class.forName("org.sqlite.JDBC"); LOG.info("sqliteFile: " + sqliteFile); Connection connection = DriverManager.getConnection("jdbc:sqlite:" + sqliteFile); try (Statement stmt = connection.createStatement()) { try (ResultSet rs = stmt.executeQuery("SELECT * FROM webappsstore2 WHERE Key='" + getMomentumKey() + "' ORDER BY Key DESC LIMIT 1")) { if (!rs.next()) { LOG.info("nothing found"); return false; } String key = rs.getString("Key"); LOG.info(key); data = new JSONObject(rs.getString("Value")); LOG.info(data.toString()); return true; } } } private String getMomentumKey() { String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); ; return "momentum-background-" + today; } private String getData(String key) throws Exception { if (data == null) { update(); } try { return data.getString(key); } catch (JSONException e) { return null; } } @Override public String getImageUri() throws Exception { String filename = getData("filename"); if (filename != null && !filename.startsWith("http")) { File[] files = new File(getChromeProfileFolder() + "\\Extensions\\" + CHROME_EXTENSION_ID).listFiles(); Arrays.sort(files); String extensionHome = files[files.length - 1].getAbsolutePath(); filename = extensionHome + File.separator + filename; } return filename; } @Override public String getTitle() throws Exception { return getData("title"); } @Override public String getBy() throws Exception { return getData("source"); } @Override public String getDetailsUri() throws Exception { return getData("sourceUrl"); } }
package dbrecorder.impl.oracle; import java.io.PrintWriter; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.sql.DataSource; import utils.Jdbc; import utils.JdbcException; import utils.ResultSetCallback; import utils.SimpleTransactionManager; import utils.SqlUtils; import utils.TransactionCallback; import utils.TransactionManager; import dbrecorder.DatabaseRecorder; public class OracleDatabaseRecorder implements DatabaseRecorder { private static final int MAX_TRIGGER_NAME_LENGTH = 30; private static final String RECORDER_PREFIX = "DBR_"; private final TransactionManager transactionManager; public OracleDatabaseRecorder(DataSource dataSource) { this(new SimpleTransactionManager(dataSource)); } OracleDatabaseRecorder(TransactionManager transactionManager) { this.transactionManager = transactionManager; } public void setup() { createRecorderTable(); } public void start() { createTriggers(); } public void stop() { dropRecorderTriggers(); } public void tearDown() { dropRecorderTriggers(); dropRecorderTable(); } public void exportTo(final PrintWriter out) { transactionManager.doInTransaction(new TransactionCallback<Object>() { @Override public Object callback(Jdbc jdbc) { jdbc.query("SELECT 'CLIENT_IDENTIFIER='||CLIENT_IDENTIFIER||';SESSION_USER='||SESSION_USER||';SESSIONID='||SESSIONID||';TABLE_NAME='||TABLE_NAME||';ACTION='||ACTION||';'||DATAROW AS DATA FROM DBR_RECORDER", new ResultSetCallback() { @Override public void extractData(ResultSet rs) throws SQLException { out.println(rs.getString(1)); } }); return null; } }); } public void exportAndRemove(final PrintWriter out) { final List<String> retrivedDataIds = new ArrayList<String>(); transactionManager.doInTransaction(new TransactionCallback<Object>() { @Override public Object callback(Jdbc jdbc) { jdbc.query("SELECT DBR_ID, 'CLIENT_IDENTIFIER='||CLIENT_IDENTIFIER||';SESSION_USER='||SESSION_USER||';SESSIONID='||SESSIONID||';TABLE_NAME='||TABLE_NAME||';ACTION='||ACTION||';'||DATAROW AS DATA FROM DBR_RECORDER", new ResultSetCallback() { @Override public void extractData(ResultSet rs) throws SQLException { retrivedDataIds.add(rs.getString(1)); out.println(rs.getString(2)); } }); return null; } }); out.flush(); /* * Deleting after select in order to avoid forcing the database to maintain * two different versions of the data while the select is running. */ transactionManager.doInTransaction(new TransactionCallback<Object>() { @Override public Object callback(Jdbc jdbc) { for (String id : retrivedDataIds) { jdbc.execute("DELETE FROM DBR_RECORDER WHERE DBR_ID = " + id); } return null; } }); } void dropRecorderTable() { transactionManager.doInTransaction(new TransactionCallback<Object>() { @Override public Object callback(Jdbc jdbc) { try { jdbc.execute("DROP TABLE DBR_RECORDER"); } catch (JdbcException e) {} try { jdbc.execute("DROP SEQUENCE DBR_RECORDER_ID_SEQ"); } catch (JdbcException e) {} return null; } }); } private void dropRecorderTriggers() { transactionManager.doInTransaction(new TransactionCallback<Object>() { @Override public Object callback(Jdbc jdbc) { for (String triggerName : getTriggerNames(jdbc)) { if (isRecorderResource(triggerName)) { jdbc.execute("DROP TRIGGER " + triggerName); } } return null; } }); } List<String> getTriggerNames(Jdbc jdbc) { return jdbc.queryForList("SELECT TRIGGER_NAME FROM USER_TRIGGERS", String.class); } void createRecorderTable() { transactionManager.doInTransaction(new TransactionCallback<Object>() { @Override public Object callback(Jdbc jdbc) { jdbc.execute(SqlUtils.readSql("create_recorder_table.sql")); jdbc.execute("CREATE SEQUENCE DBR_RECORDER_ID_SEQ"); return null; } }); } void createTriggers() { transactionManager.doInTransaction(new TransactionCallback<Object>() { @Override public Object callback(Jdbc jdbc) { for (String tableName : getTableNames(jdbc)) { if (isRecorderResource(tableName)) { continue; } final List<String> columnNames = getColumnNames(jdbc, tableName); if (columnNames.isEmpty()) { // TODO: Log ignoring System.out.println("Ignoring table with no columns: " + tableName); continue; } try { createTrigger(jdbc, tableName, columnNames); } catch (JdbcException e) { // TODO: Log exception System.out.println("Ignoring table: " + tableName + " (" + e.getMessage() + ")"); } } return null; } }); } private void createTrigger(Jdbc jdbc, String tableName, final List<String> columnNames) { final String triggerSql = TriggerSqlGenerator.generateTriggerSql( reduceToMaxLength(RECORDER_PREFIX + tableName, MAX_TRIGGER_NAME_LENGTH), tableName, columnNames); jdbc.execute(triggerSql); } List<String> getTableNames(Jdbc jdbc) { return jdbc.queryForList("SELECT TABLE_NAME FROM USER_TABLES", String.class); } List<String> getColumnNames(Jdbc jdbc, String tableName) { return jdbc.queryForList("SELECT COLUMN_NAME FROM USER_TAB_COLS WHERE TABLE_NAME = ? ORDER BY COLUMN_NAME", String.class, tableName); } private boolean isRecorderResource(String resourceName) { return resourceName.startsWith(RECORDER_PREFIX); } String reduceToMaxLength(String s, int length) { return (s.length() <= length) ? s : s.substring(0, length); } }
package de.bmoth.parser.ast.nodes.ltl; import de.bmoth.parser.ast.nodes.PredicateNode; import java.util.*; import static de.bmoth.parser.ast.nodes.ltl.LTLInfixOperatorNode.Kind.*; import static de.bmoth.parser.ast.nodes.ltl.LTLKeywordNode.Kind.TRUE; import static de.bmoth.parser.ast.nodes.ltl.LTLPrefixOperatorNode.Kind.NEXT; public class BuechiAutomaton { private int nodeCounter = 0; private Set<LTLNode> subFormulasForAcceptance = new LinkedHashSet<>(); private List<List<BuechiAutomatonNode>> acceptingStateSets = new ArrayList<>(); private Set<BuechiAutomatonNode> initialStates = new LinkedHashSet<>(); private final Set<BuechiAutomatonNode> nodeSet = new LinkedHashSet<>(); public BuechiAutomaton(LTLNode ltlNode) { createGraph(ltlNode); labelNodes(); determineInitialsAndSuccessors(); } private String newName() { nodeCounter++; return "node" + nodeCounter; } private Boolean checkForContradiction(LTLNode ltlNode, Set<LTLNode> processedNodes) { PredicateNode negatedNode = ((LTLBPredicateNode) ltlNode).getPredicate().getNegatedPredicateNode(); for (LTLNode processedNode : processedNodes) { if (processedNode instanceof LTLBPredicateNode && ((LTLBPredicateNode) processedNode).getPredicate().equalAst(negatedNode)) { return true; } } return false; } private Boolean ltlNodeIsInList(LTLNode ltlNode, Set<LTLNode> processed) { for (LTLNode processedNode : processed) { if (ltlNode.equalAst(processedNode)) { return true; } } return false; } private Boolean compareLTLNodeSets(Set<LTLNode> nodeSet, Set<LTLNode> processedNodeSet) { if (nodeSet.size() == processedNodeSet.size()) { Set<LTLNode> nodeProcessed = new LinkedHashSet<>(nodeSet); Set<LTLNode> nodeInSetProcessed = new LinkedHashSet<>(processedNodeSet); Iterator<LTLNode> nodeIterator = nodeProcessed.iterator(); while (nodeIterator.hasNext()) { LTLNode ltlNode = nodeIterator.next(); Iterator<LTLNode> nodeInSetIterator = nodeInSetProcessed.iterator(); while (nodeInSetIterator.hasNext()) { LTLNode ltlNodeInSet = nodeInSetIterator.next(); if (ltlNode.equalAst(ltlNodeInSet)) { nodeIterator.remove(); nodeInSetIterator.remove(); } } } return (nodeProcessed.isEmpty() && nodeInSetProcessed.isEmpty()); } else { return false; } } private BuechiAutomatonNode buechiNodeIsInNodeSet(BuechiAutomatonNode buechiNode) { // Check whether the finished node is already in the list (determined by the same Old- and Next-sets). for (BuechiAutomatonNode nodeInSet : nodeSet) { boolean processedEquals = compareLTLNodeSets(buechiNode.processed, nodeInSet.processed); boolean nextEquals = compareLTLNodeSets(buechiNode.next, nodeInSet.next); if (processedEquals && nextEquals) { return nodeInSet; } } return null; } private Set<LTLNode> new1(LTLInfixOperatorNode ltlNode) { Set<LTLNode> newNodes = new LinkedHashSet<>(); if (ltlNode.getKind() == RELEASE) { newNodes.add(ltlNode.getRight()); } else if (ltlNode.getKind() == UNTIL || ltlNode.getKind() == OR) { // Until, or newNodes.add(ltlNode.getLeft()); } else { throw new IllegalArgumentException("Formula not normalized"); } return newNodes; } private Set<LTLNode> new2(LTLInfixOperatorNode ltlNode) { Set<LTLNode> newNodes = new LinkedHashSet<>(); newNodes.add(ltlNode.getRight()); if (ltlNode.getKind() == RELEASE) { newNodes.add(ltlNode.getLeft()); } return newNodes; } private Set<LTLNode> next1(LTLInfixOperatorNode ltlNode) { Set<LTLNode> newNodes = new LinkedHashSet<>(); if (ltlNode.getKind() == UNTIL || ltlNode.getKind() == RELEASE) { newNodes.add(ltlNode); return newNodes; } else if (ltlNode.getKind() == OR) { // In case of or an empty list is returned return newNodes; } else { throw new IllegalArgumentException("Formula not normalized"); } } private BuechiAutomatonNode buildFirstNodeInSplit(BuechiAutomatonNode buechiNode, LTLInfixOperatorNode subNode) { // Prepare the different parts of the first new node created for Until, Release and Or Set<LTLNode> unprocessed = new LinkedHashSet<>(buechiNode.unprocessed); for (LTLNode node : new1(subNode)) { if (!ltlNodeIsInList(node, buechiNode.processed)) { unprocessed.add(node); } } Set<LTLNode> next = new LinkedHashSet<>(buechiNode.next); next.addAll(next1(subNode)); Set<LTLNode> processed = new LinkedHashSet<>(buechiNode.processed); processed.add(subNode); return new BuechiAutomatonNode(newName(), new LinkedHashSet<>(buechiNode.incoming), unprocessed, processed, next); } private BuechiAutomatonNode buildSecondNodeInSplit(BuechiAutomatonNode buechiNode, LTLInfixOperatorNode subNode) { // Prepare the different parts of the second new node created for Until, Release and Or Set<LTLNode> unprocessed = new LinkedHashSet<>(buechiNode.unprocessed); for (LTLNode node : new2(subNode)) { if (!ltlNodeIsInList(node, buechiNode.processed)) { unprocessed.add(node); } } Set<LTLNode> processed = new LinkedHashSet<>(buechiNode.processed); processed.add(subNode); return new BuechiAutomatonNode(newName(), new LinkedHashSet<>(buechiNode.incoming), unprocessed, processed, new LinkedHashSet<>(buechiNode.next)); } private void handleProcessedNode(BuechiAutomatonNode buechiNode) { // Add a processed node to the nodeSet or update it. BuechiAutomatonNode nodeInSet = buechiNodeIsInNodeSet(buechiNode); if (nodeInSet != null) { nodeInSet.incoming.addAll(buechiNode.incoming); } else { Set<BuechiAutomatonNode> incoming = new LinkedHashSet<>(); incoming.add(buechiNode); nodeSet.add(buechiNode); expand(new BuechiAutomatonNode(newName(), incoming, new LinkedHashSet<>(buechiNode.next), new LinkedHashSet<>(), new LinkedHashSet<>())); } } private void handleInfixOperatorNode(BuechiAutomatonNode buechiNode, LTLInfixOperatorNode ltlNode) { if (ltlNode.getKind() == LTLInfixOperatorNode.Kind.AND) { // And Set<LTLNode> unprocessed = new LinkedHashSet<>(buechiNode.unprocessed); unprocessed.add(ltlNode.getLeft()); unprocessed.add(ltlNode.getRight()); unprocessed.removeAll(buechiNode.processed); Set<LTLNode> processed = new LinkedHashSet<>(buechiNode.processed); processed.add(ltlNode); expand(new BuechiAutomatonNode(buechiNode.name, new LinkedHashSet<>(buechiNode.incoming), unprocessed, processed, new LinkedHashSet<>(buechiNode.next))); } else { // Until, Release, Or: Split the node in two if (ltlNode.getKind() == UNTIL && !ltlNodeIsInList(ltlNode, subFormulasForAcceptance)) { subFormulasForAcceptance.add(ltlNode); } BuechiAutomatonNode node1 = buildFirstNodeInSplit(buechiNode, ltlNode); BuechiAutomatonNode node2 = buildSecondNodeInSplit(buechiNode, ltlNode); expand(node1); expand(node2); } } private void handlePrefixOperatorNode(BuechiAutomatonNode buechiNode, LTLPrefixOperatorNode ltlNode) { if (ltlNode.getKind() == NEXT) { // Next Set<LTLNode> processed = new LinkedHashSet<>(buechiNode.processed); processed.add(ltlNode); Set<LTLNode> next = new LinkedHashSet<>(buechiNode.next); next.add(ltlNode.getArgument()); expand(new BuechiAutomatonNode(buechiNode.name + "_1", new LinkedHashSet<>(buechiNode.incoming), new LinkedHashSet<>(buechiNode.unprocessed), processed, next)); } else { throw new IllegalArgumentException("Formula not normalized"); } } private void expand(BuechiAutomatonNode buechiNode) { if (buechiNode.unprocessed.isEmpty()) { // The current node is completely processed and can be added to the list (or, in case he was // already added before, updated). handleProcessedNode(buechiNode); } else { Iterator<LTLNode> iterator = buechiNode.unprocessed.iterator(); LTLNode ltlNode = iterator.next(); iterator.remove(); if (ltlNode instanceof LTLKeywordNode) { // False -> discard node if (((LTLKeywordNode) ltlNode).getKind() == TRUE) { buechiNode.processed.add(ltlNode); expand(buechiNode); } } else if (ltlNode instanceof LTLBPredicateNode) { // B predicate if (!checkForContradiction(ltlNode, buechiNode.processed)) { buechiNode.processed.add(ltlNode); expand(buechiNode); } } else if (ltlNode instanceof LTLPrefixOperatorNode) { handlePrefixOperatorNode(buechiNode, (LTLPrefixOperatorNode) ltlNode); } else if (ltlNode instanceof LTLInfixOperatorNode) { handleInfixOperatorNode(buechiNode, (LTLInfixOperatorNode) ltlNode); } } } private void createGraph(LTLNode node) { Set<BuechiAutomatonNode> initIncoming = new LinkedHashSet<>(); initIncoming.add(new BuechiAutomatonNode("init", new LinkedHashSet<>(), new LinkedHashSet<>(), new LinkedHashSet<>(), new LinkedHashSet<>())); Set<LTLNode> unprocessed = new LinkedHashSet<>(); unprocessed.add(node); expand(new BuechiAutomatonNode(newName(), initIncoming, unprocessed, new LinkedHashSet<>(), new LinkedHashSet<>())); } private void labelNodes() { for (BuechiAutomatonNode buechiNode : nodeSet) { buechiNode.label(); } for (LTLNode formulaForAcceptance : subFormulasForAcceptance) { LTLInfixOperatorNode untilNode = (LTLInfixOperatorNode) formulaForAcceptance; List<BuechiAutomatonNode> acceptingStateSet = new ArrayList<>(); for (BuechiAutomatonNode buechiNode : nodeSet) { if (!ltlNodeIsInList(untilNode, buechiNode.processed) || ltlNodeIsInList(untilNode.getRight(), buechiNode.processed)) { buechiNode.isAcceptingState = true; acceptingStateSet.add(buechiNode); } } acceptingStateSets.add(acceptingStateSet); } } private void determineInitialsAndSuccessors() { for (BuechiAutomatonNode node : nodeSet) { for (BuechiAutomatonNode incomingNode : node.incoming) { incomingNode.successors.add(node); } if (node.isInitialState) { initialStates.add(node); } } } public String toString() { StringJoiner nodesString = new StringJoiner(",\n\n", "", ""); for (BuechiAutomatonNode node : nodeSet) { nodesString.add(node.toString()); } StringJoiner acceptingString = new StringJoiner(", ", "[", "]"); for (List<BuechiAutomatonNode> acceptingStateSet : acceptingStateSets) { StringJoiner acceptingStatesString = new StringJoiner(", ", "(", ")"); for (BuechiAutomatonNode node : acceptingStateSet) { acceptingStatesString.add(node.name); } acceptingString.add(acceptingStatesString.toString()); } nodesString.add("Accepting state sets: " + acceptingString.toString()); return nodesString.toString(); } public boolean isAcceptingSet(Set<BuechiAutomatonNode> buechiStates) { for (List<BuechiAutomatonNode> accepting : acceptingStateSets) { Set acceptingSet = new LinkedHashSet(accepting); if (Collections.disjoint(acceptingSet, buechiStates)) { return false; } } return true; } public Set<BuechiAutomatonNode> getFinalNodeSet() { return nodeSet; } public Set<BuechiAutomatonNode> getInitialStates() { return initialStates; } }
package de.cinovo.cloudconductor.api.model; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeInfo.As; import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; @JsonTypeInfo(include = As.PROPERTY, use = Id.CLASS) public class Statistics { private long numberOfHosts; private long numberOfTemplates; private long numberOfServices; private long numberOfPackages; /** * @return the numberOfHosts */ public long getNumberOfHosts() { return this.numberOfHosts; } /** * @param numberOfHosts the numberOfHosts to set */ public void setNumberOfHosts(long numberOfHosts) { this.numberOfHosts = numberOfHosts; } /** * @return the numberOfTemplates */ public long getNumberOfTemplates() { return this.numberOfTemplates; } /** * @param numberOfTemplates the numberOfTemplates to set */ public void setNumberOfTemplates(long numberOfTemplates) { this.numberOfTemplates = numberOfTemplates; } /** * @return the numberOfServices */ public long getNumberOfServices() { return this.numberOfServices; } /** * @param numberOfServices the numberOfServices to set */ public void setNumberOfServices(long numberOfServices) { this.numberOfServices = numberOfServices; } /** * @return the numberOfPackages */ public long getNumberOfPackages() { return this.numberOfPackages; } /** * @param numberOfPackages the numberOfPackages to set */ public void setNumberOfPackages(long numberOfPackages) { this.numberOfPackages = numberOfPackages; } }
package de.csdev.ebus.cfg.std; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Type; import java.net.URL; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonIOException; import com.google.gson.JsonSyntaxException; import com.google.gson.reflect.TypeToken; import de.csdev.ebus.cfg.EBusConfigurationReaderException; import de.csdev.ebus.cfg.IEBusConfigurationReader; import de.csdev.ebus.cfg.std.dto.EBusCollectionDTO; import de.csdev.ebus.cfg.std.dto.EBusCommandDTO; import de.csdev.ebus.cfg.std.dto.EBusCommandMethodDTO; import de.csdev.ebus.cfg.std.dto.EBusCommandTemplatesDTO; import de.csdev.ebus.cfg.std.dto.EBusValueDTO; import de.csdev.ebus.command.EBusCommand; import de.csdev.ebus.command.EBusCommandCollection; import de.csdev.ebus.command.EBusCommandMethod; import de.csdev.ebus.command.EBusCommandNestedValue; import de.csdev.ebus.command.EBusCommandValue; import de.csdev.ebus.command.IEBusCommandCollection; import de.csdev.ebus.command.IEBusCommandMethod; import de.csdev.ebus.command.IEBusCommandMethod.Method; import de.csdev.ebus.command.datatypes.EBusTypeRegistry; import de.csdev.ebus.command.datatypes.IEBusType; import de.csdev.ebus.command.datatypes.ext.EBusTypeBytes; import de.csdev.ebus.core.EBusConsts; import de.csdev.ebus.utils.EBusUtils; /** * @author Christian Sowada - Initial contribution * */ public class EBusConfigurationReader implements IEBusConfigurationReader { private final Logger logger = LoggerFactory.getLogger(EBusConfigurationReader.class); private EBusTypeRegistry registry; private Map<String, Collection<EBusCommandValue>> templateValueRegistry = new HashMap<String, Collection<EBusCommandValue>>(); private Map<String, Collection<EBusCommandValue>> templateBlockRegistry = new HashMap<String, Collection<EBusCommandValue>>(); /* * (non-Javadoc) * * @see de.csdev.ebus.cfg.IEBusConfigurationReader#loadBuildInConfigurations() */ @Override public List<IEBusCommandCollection> loadBuildInConfigurationCollections() { return loadConfigurationCollectionBundle( EBusConfigurationReader.class.getResource("/index-configuration.json")); } /* * (non-Javadoc) * * @see de.csdev.ebus.cfg.IEBusConfigurationReader#loadConfigurationCollection(java.io.InputStream) */ @Override public IEBusCommandCollection loadConfigurationCollection(URL url) throws IOException, EBusConfigurationReaderException { if (registry == null) { throw new RuntimeException("Unable to load configuration without EBusType set!"); } if (url == null) { throw new IllegalArgumentException("Required argument url is null!"); } Type merchantListType = new TypeToken<List<EBusValueDTO>>() { }.getType(); Gson gson = new Gson(); gson = new GsonBuilder().registerTypeAdapter(merchantListType, new EBusValueJsonDeserializer()).create(); MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new IOException(e); } // collect md5 hash while reading file DigestInputStream dis = new DigestInputStream(url.openStream(), md); EBusCollectionDTO collection = gson.fromJson(new InputStreamReader(dis), EBusCollectionDTO.class); EBusCommandCollection commandCollection = (EBusCommandCollection) loadConfigurationCollection(collection); // add md5 hash commandCollection.setSourceHash(md.digest()); return commandCollection; } public IEBusCommandCollection loadConfigurationCollection(EBusCollectionDTO collection) throws EBusConfigurationReaderException { // EBusCollectionDTO collection = gson.fromJson(new InputStreamReader(dis), EBusCollectionDTO.class); EBusCommandCollection commandCollection = new EBusCommandCollection(collection.getId(), collection.getLabel(), collection.getDescription(), collection.getProperties()); // add md5 hash // commandCollection.setSourceHash(md.digest()); commandCollection.setIdentification(collection.getIdentification()); // parse the template block parseTemplateConfiguration(collection); if (collection.getCommands() != null) { for (EBusCommandDTO commandDto : collection.getCommands()) { if (commandDto != null) { commandCollection.addCommand(parseTelegramConfiguration(commandCollection, commandDto)); } } } return commandCollection; } protected void parseTemplateConfiguration(EBusCollectionDTO collection) throws EBusConfigurationReaderException { // extract templates List<EBusCommandTemplatesDTO> templateSection = collection.getTemplates(); if (templateSection != null) { for (EBusCommandTemplatesDTO templates : templateSection) { List<EBusValueDTO> templateValues = templates.getTemplate(); if (templateValues != null) { Collection<EBusCommandValue> blockList = new ArrayList<EBusCommandValue>(); for (EBusValueDTO value : templateValues) { Collection<EBusCommandValue> pv = parseValueConfiguration(value, null, null); blockList.addAll(pv); // global id String id = collection.getId() + "." + templates.getName() + "." + value.getName(); logger.trace("Add template with global id {} to registry ...", id); templateValueRegistry.put(id, pv); } String id = collection.getId() + "." + templates.getName(); // global id logger.trace("Add template block with global id {} to registry ...", id); templateBlockRegistry.put(id, blockList); } } } } /** * @param commandCollection * @param commandElement * @return * @throws EBusConfigurationReaderException */ protected EBusCommand parseTelegramConfiguration(IEBusCommandCollection commandCollection, EBusCommandDTO commandElement) throws EBusConfigurationReaderException { if (commandElement == null) { throw new IllegalArgumentException("Parameter \"command dto\" not set!"); } LinkedHashMap<String, EBusCommandValue> templateMap = new LinkedHashMap<String, EBusCommandValue>(); // collect available channels List<String> methods = new ArrayList<String>(); if (commandElement.getGet() != null) { methods.add("get"); } if (commandElement.getSet() != null) { methods.add("set"); } if (commandElement.getBroadcast() != null) { methods.add("broadcast"); } // extract default values String id = commandElement.getId(); byte[] command = EBusUtils.toByteArray(commandElement.getCommand()); String label = commandElement.getLabel(); String device = commandElement.getDevice(); Byte destination = EBusUtils.toByte(commandElement.getDst()); Byte source = EBusUtils.toByte(commandElement.getSrc()); // read in template block if (commandElement.getTemplate() != null) { for (EBusValueDTO template : commandElement.getTemplate()) { for (EBusCommandValue templateCfg : parseValueConfiguration(template, null, null)) { if (StringUtils.isEmpty(templateCfg.getName())) { logger.warn("Template block value without a name {}.{}", commandCollection.getId(), commandElement.getId()); } templateMap.put(templateCfg.getName(), templateCfg); } } } EBusCommand cfg = new EBusCommand(); cfg.setId(id); cfg.setLabel(label); cfg.setDevice(device); cfg.setParentCollection(commandCollection); // loop all available channnels for (String channel : methods) { EBusCommandMethodDTO commandMethodElement = null; IEBusCommandMethod.Method method = null; if (channel.equals("get")) { commandMethodElement = commandElement.getGet(); method = IEBusCommandMethod.Method.GET; } else if (channel.equals("set")) { commandMethodElement = commandElement.getSet(); method = IEBusCommandMethod.Method.SET; } else if (channel.equals("broadcast")) { commandMethodElement = commandElement.getBroadcast(); method = IEBusCommandMethod.Method.BROADCAST; } if (commandMethodElement != null) { EBusCommandMethod commandMethod = new EBusCommandMethod(cfg, method); // overwrite with local command if (StringUtils.isNotEmpty(commandMethodElement.getCommand())) { commandMethod.setCommand(EBusUtils.toByteArray(commandMethodElement.getCommand())); } else { commandMethod.setCommand(command); } commandMethod.setDestinationAddress(destination); commandMethod.setSourceAddress(source); if (commandMethodElement.getMaster() != null) { for (EBusValueDTO template : commandMethodElement.getMaster()) { for (EBusCommandValue ev : parseValueConfiguration(template, templateMap, commandMethod)) { commandMethod.addMasterValue(ev); } } } if (commandMethodElement.getSlave() != null) { for (EBusValueDTO template : commandMethodElement.getSlave()) { for (EBusCommandValue ev : parseValueConfiguration(template, templateMap, commandMethod)) { commandMethod.addSlaveValue(ev); } } } // default type is always master-slave if not explicit set or a broadcast if (StringUtils.equals(commandMethodElement.getType(), "master-master")) { commandMethod.setType(IEBusCommandMethod.Type.MASTER_MASTER); } else if (method == Method.BROADCAST) { commandMethod.setDestinationAddress(EBusConsts.BROADCAST_ADDRESS); commandMethod.setType(IEBusCommandMethod.Type.BROADCAST); } else { commandMethod.setType(IEBusCommandMethod.Type.MASTER_SLAVE); } } } return cfg; } /** * @param template * @param templateMap * @param commandMethod * @return * @throws EBusConfigurationReaderException */ protected Collection<EBusCommandValue> parseValueConfiguration(EBusValueDTO template, Map<String, EBusCommandValue> templateMap, EBusCommandMethod commandMethod) throws EBusConfigurationReaderException { Collection<EBusCommandValue> result = new ArrayList<EBusCommandValue>(); String typeStr = template.getType(); String collectionId = null; // check if really set if (commandMethod != null && commandMethod.getParent() != null && commandMethod.getParent().getParentCollection() != null) { collectionId = commandMethod.getParent().getParentCollection().getId(); } if (StringUtils.isEmpty(typeStr)) { throw new EBusConfigurationReaderException("Property 'type' is missing for command ! {0}", commandMethod.getParent()); } else if (typeStr.equals("template-block")) { Collection<EBusCommandValue> templateCollection = null; if (StringUtils.isNotEmpty(template.getName())) { logger.warn("Property 'name' is not allowed for type 'template-block', ignore property !"); } // use the global or local id as template block, new with alpha 15 String id = (String) template.getProperty("id"); String globalId = collectionId + "." + id; if (StringUtils.isNotEmpty(id)) { templateCollection = templateBlockRegistry.get(id); if (templateCollection == null) { // try to convert the local id to a global id logger.trace("Unable to find a template with id {}, second try with {} ...", id, globalId); templateCollection = templateBlockRegistry.get(globalId); if (templateCollection == null) { throw new EBusConfigurationReaderException("Unable to find a template-block with id {0}!", id); } } } else if (templateMap != null) { // return the complete template block from within command block templateCollection = templateMap.values(); } else { throw new EBusConfigurationReaderException( "No additional information for type 'template-block' defined!"); } if (templateCollection != null) { for (EBusCommandValue commandValue : templateCollection) { // clone the original value EBusCommandValue clone = commandValue.clone(); clone.setParent(commandMethod); overwritePropertiesFromTemplate(clone, template); result.add(clone); } } return result; } else if (typeStr.equals("template")) { String id = (String) template.getProperty("id"); String globalId = collectionId + "." + id; Collection<EBusCommandValue> templateCollection = null; if (StringUtils.isEmpty(id)) { throw new EBusConfigurationReaderException("No additional information for type 'template' defined!"); } if (templateValueRegistry.containsKey(id)) { templateCollection = templateValueRegistry.get(id); } else if (templateValueRegistry.containsKey(globalId)) { templateCollection = templateValueRegistry.get(globalId); } else if (templateMap != null && templateMap.containsKey(id)) { // return the complete template block from within command block templateCollection = new ArrayList<EBusCommandValue>(); templateCollection.add(templateMap.get(id)); } else { throw new EBusConfigurationReaderException("Unable to find a template for id {0}!", id); } if (templateCollection != null && !templateCollection.isEmpty()) { for (EBusCommandValue commandValue : templateCollection) { EBusCommandValue clone = commandValue.clone(); clone.setParent(commandMethod); overwritePropertiesFromTemplate(clone, template); // allow owerwrite for single names clone.setName(StringUtils.defaultIfEmpty(template.getName(), clone.getName())); result.add(clone); } } else { throw new EBusConfigurationReaderException("Internal template collection is empty!"); } return result; } else if (typeStr.equals("static")) { // convert static content to bytes byte[] byteArray = EBusUtils.toByteArray(template.getDefault()); Map<String, Object> properties = new HashMap<String, Object>(); properties.put("length", byteArray.length); final IEBusType<?> typeByte = registry.getType(EBusTypeBytes.TYPE_BYTES, properties); EBusCommandValue commandValue = EBusCommandValue.getInstance(typeByte, byteArray); commandValue.setParent(commandMethod); result.add(commandValue); return result; } EBusCommandValue ev = null; // value is a nested value if (template.getChildren() != null) { EBusCommandNestedValue evc = new EBusCommandNestedValue(); ev = evc; int pos = 0; for (EBusValueDTO childElem : template.getChildren()) { // add pos information from list childElem.setPos(pos); // parse child value for (EBusCommandValue childValue : parseValueConfiguration(childElem, templateMap, commandMethod)) { evc.add(childValue); } pos++; } } else { // default value ev = new EBusCommandValue(); } Map<String, Object> map = template.getAsMap(); IEBusType<?> type = registry.getType(typeStr, map); ev.setType(type); ev.setName(template.getName()); ev.setLabel(template.getLabel()); ev.setFactor(template.getFactor()); ev.setMin(template.getMin()); ev.setMax(template.getMax()); ev.setMapping(template.getMapping()); ev.setFormat(template.getFormat()); ev.setParent(commandMethod); result.add(ev); return result; } private void overwritePropertiesFromTemplate(EBusCommandValue clone, EBusValueDTO template) { // allow placeholders in template-block mode if (StringUtils.isNotEmpty(template.getLabel())) { if (StringUtils.isNotEmpty(clone.getLabel()) && clone.getLabel().contains("%s")) { clone.setLabel(String.format(clone.getLabel(), template.getLabel())); } else { clone.setLabel(template.getLabel()); } } // clone.setName(StringUtils.defaultIfEmpty(template.g, clone.getName())); } /* * (non-Javadoc) * * @see de.csdev.ebus.cfg.IEBusConfigurationReader#setEBusTypes(de.csdev.ebus.command.datatypes.EBusTypeRegistry) */ @Override public void setEBusTypes(EBusTypeRegistry ebusTypes) { registry = ebusTypes; } @Override public List<IEBusCommandCollection> loadConfigurationCollectionBundle(URL url) { List<IEBusCommandCollection> result = new ArrayList<IEBusCommandCollection>(); Gson gson = new Gson(); Type type = new TypeToken<Map<String, ?>>() { }.getType(); try { Map<String, ?> mapping = gson.fromJson(new InputStreamReader(url.openStream()), type); if (mapping.containsKey("files")) { @SuppressWarnings("unchecked") List<Map<String, String>> files = (List<Map<String, String>>) mapping.get("files"); for (Map<String, String> file : files) { URL fileUrl = new URL(url, file.get("url")); try { logger.debug("Load configuration from url {} ...", fileUrl); IEBusCommandCollection collection = loadConfigurationCollection(fileUrl); if (collection != null) { result.add(collection); } } catch (EBusConfigurationReaderException e) { logger.error(e.getMessage() + " (Url: " + fileUrl + ")"); } catch (IOException e) { logger.error("error!", e); } } } } catch (JsonSyntaxException e) { logger.error("error!", e); } catch (JsonIOException e) { logger.error("error!", e); } catch (IOException e) { logger.error("error!", e); } return result; } @Override public void clear() { templateBlockRegistry.clear(); templateValueRegistry.clear(); } public Map<String, Collection<EBusCommandValue>> getTemplateValueRegistry() { return templateValueRegistry; } public Map<String, Collection<EBusCommandValue>> getTemplateBlockRegistry() { return templateBlockRegistry; } }
package de.maredit.tar.controllers; import de.maredit.tar.models.CalendarEvent; import de.maredit.tar.models.Vacation; import de.maredit.tar.models.enums.State; import de.maredit.tar.repositories.VacationRepository; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import static java.util.stream.Collectors.toList; @Controller public class CalendarController { private static final Logger LOG = LogManager.getLogger(CalendarController.class); @Autowired private VacationRepository vacationRepository; @RequestMapping("/calendar") public String calendar(Model model) { List<Vacation> vacations = this.vacationRepository.findAll(); model.addAttribute("vacations", vacations); return "application/calendar"; } @RequestMapping(value = "/calendar", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public List<CalendarEvent> getCalendarElements(@RequestParam(value = "start") String start, @RequestParam(value = "end") String end, @RequestParam(value = "showApproved", defaultValue = "true") Boolean showApproved, @RequestParam(value = "showPending", defaultValue = "false") Boolean showPending, @RequestParam(value = "showCanceled", defaultValue = "false") Boolean showCanceled, @RequestParam(value = "showRejected", defaultValue = "false") Boolean showRejected) { LocalDate startDate = LocalDate.parse(start, DateTimeFormatter.ofPattern("yyyy-MM-dd")); LocalDate endDate = LocalDate.parse(end, DateTimeFormatter.ofPattern("yyyy-MM-dd")); LOG.debug("Selecting vacation data from " + startDate + " to " + endDate); List<State> states = new ArrayList<State>(); if (showApproved) { states.add(State.APPROVED); } if (showPending) { states.add(State.WAITING_FOR_APPROVEMENT); states.add(State.REQUESTED_SUBSTITUTE); } if (showCanceled) { states.add(State.CANCELED); } if (showRejected) { states.add(State.REJECTED); } List<Vacation> vacations = this.vacationRepository .findVacationByFromBetweenAndStateInOrToBetweenAndStateIn(startDate, endDate, states, startDate, endDate, states); List<CalendarEvent> calendarEvents = vacations.stream().map(vacation -> { CalendarEvent calendarEvent = new CalendarEvent(vacation); LOG.debug( "added CalendarEvent '" + calendarEvent.getTitle() + "' [start: " + calendarEvent .getStart() + " - end: " + calendarEvent.getEnd() + "] - "+calendarEvent.getState()); return calendarEvent; }).collect(toList()); return calendarEvents; } }
package de.slackspace.openkeepass.domain; import java.util.ArrayList; import java.util.List; import java.util.UUID; public class GroupBuilder implements GroupContract { private UUID uuid; private String name; private int iconId = 49; private Times times; private boolean isExpanded; private byte[] iconData; private UUID customIconUuid; private List<Entry> entries = new ArrayList<Entry>(); private List<Group> groups = new ArrayList<Group>(); public GroupBuilder() { this.uuid = UUID.randomUUID(); } public GroupBuilder(String name) { this(); this.name = name; } public GroupBuilder(Group group) { if (group == null) { throw new IllegalArgumentException("Parameter group must not be null"); } this.uuid = group.getUuid(); this.name = group.getName(); this.iconId = group.getIconId(); this.iconData = group.getIconData(); this.customIconUuid = group.getCustomIconUuid(); this.times = group.getTimes(); this.isExpanded = group.isExpanded(); this.groups = group.getGroups(); this.entries = group.getEntries(); } public GroupBuilder name(String name) { this.name = name; return this; } public GroupBuilder iconId(int iconId) { this.iconId = iconId; return this; } public GroupBuilder iconData(byte[] iconData) { this.iconData = iconData; return this; } public GroupBuilder customIconUuid(UUID uuid) { this.customIconUuid = uuid; return this; } public GroupBuilder times(Times times) { this.times = times; return this; } public GroupBuilder isExpanded(boolean isExpanded) { this.isExpanded = isExpanded; return this; } public GroupBuilder addEntry(Entry entry) { entries.add(entry); return this; } public GroupBuilder addEntries(List<Entry> entryList) { entries.addAll(entryList); return this; } public GroupBuilder addGroup(Group group) { groups.add(group); return this; } public GroupBuilder removeGroup(Group group) { groups.remove(group); return this; } public GroupBuilder removeEntry(Entry entry) { entries.remove(entry); return this; } public GroupBuilder removeEntries(List<Entry> entryList) { entries.removeAll(entryList); return this; } public Group build() { return new Group(this); } @Override public UUID getUuid() { return uuid; } @Override public String getName() { return name; } @Override public int getIconId() { return iconId; } @Override public Times getTimes() { return times; } @Override public boolean isExpanded() { return isExpanded; } @Override public byte[] getIconData() { return iconData; } @Override public UUID getCustomIconUuid() { return customIconUuid; } @Override public List<Entry> getEntries() { return entries; } @Override public List<Group> getGroups() { return groups; } }
package edu.harvard.iq.dataverse.export; import edu.harvard.iq.dataverse.Dataset; import edu.harvard.iq.dataverse.DatasetVersion; import edu.harvard.iq.dataverse.DvObject; import static edu.harvard.iq.dataverse.GlobalIdServiceBean.logger; import edu.harvard.iq.dataverse.dataaccess.DataAccess; import static edu.harvard.iq.dataverse.dataaccess.DataAccess.getStorageIO; import edu.harvard.iq.dataverse.dataaccess.DataAccessOption; import edu.harvard.iq.dataverse.dataaccess.StorageIO; import static edu.harvard.iq.dataverse.dataset.DatasetUtil.datasetLogoThumbnail; import static edu.harvard.iq.dataverse.dataset.DatasetUtil.thumb48addedByImageThumbConverter; import edu.harvard.iq.dataverse.export.spi.Exporter; import edu.harvard.iq.dataverse.settings.SettingsServiceBean; import edu.harvard.iq.dataverse.util.json.JsonPrinter; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.nio.channels.Channel; import java.nio.channels.Channels; import java.nio.channels.WritableByteChannel; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.ServiceConfigurationError; import java.util.ServiceLoader; import java.util.logging.Level; import java.util.logging.Logger; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; /** * * @author skraffmi */ public class ExportService { private static ExportService service; private ServiceLoader<Exporter> loader; static SettingsServiceBean settingsService; private ExportService() { loader = ServiceLoader.load(Exporter.class); } /** * @deprecated Use `getInstance(SettingsServiceBean settingsService)` * instead. For privacy reasons, we need to pass in settingsService so that * we can make a decision whether not not to exclude email addresses. No new * code should call this method and it would be nice to remove calls from * existing code. */ @Deprecated public static synchronized ExportService getInstance() { return getInstance(null); } public static synchronized ExportService getInstance(SettingsServiceBean settingsService) { ExportService.settingsService = settingsService; if (service == null) { service = new ExportService(); } return service; } public List< String[]> getExportersLabels() { List<String[]> retList = new ArrayList<>(); Iterator<Exporter> exporters = ExportService.getInstance(null).loader.iterator(); while (exporters.hasNext()) { Exporter e = exporters.next(); String[] temp = new String[2]; temp[0] = e.getDisplayName(); temp[1] = e.getProviderName(); retList.add(temp); } return retList; } public InputStream getExport(Dataset dataset, String formatName) throws ExportException, IOException { // first we will try to locate an already existing, cached export // for this format: InputStream exportInputStream = getCachedExportFormat(dataset, formatName); if (exportInputStream != null) { return exportInputStream; } // if it doesn't exist, we'll try to run the export: exportFormat(dataset, formatName); // and then try again: exportInputStream = getCachedExportFormat(dataset, formatName); if (exportInputStream != null) { return exportInputStream; } // if there is no cached export still - we have to give up and throw // an exception! throw new ExportException("Failed to export the dataset as " + formatName); } public String getExportAsString(Dataset dataset, String formatName) { InputStream inputStream = null; try { inputStream = getExport(dataset, formatName); if (inputStream != null) { BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF8")); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line); sb.append('\n'); } br.close(); return sb.toString(); } } catch (ExportException | IOException ex) { //ex.printStackTrace(); return null; } finally { try{inputStream.close();} catch(IOException ic){} } return null; } // This method goes through all the Exporters and calls // the "chacheExport()" method that will save the produced output // in a file in the dataset directory, on each Exporter available. public void exportAllFormats(Dataset dataset) throws ExportException { try { clearAllCachedFormats(dataset); } catch (IOException ex) { Logger.getLogger(ExportService.class.getName()).log(Level.SEVERE, null, ex); } try { DatasetVersion releasedVersion = dataset.getReleasedVersion(); if (releasedVersion == null) { throw new ExportException("No released version for dataset " + dataset.getGlobalIdString()); } JsonPrinter jsonPrinter = new JsonPrinter(settingsService); final JsonObjectBuilder datasetAsJsonBuilder = jsonPrinter.jsonAsDatasetDto(releasedVersion); JsonObject datasetAsJson = datasetAsJsonBuilder.build(); Iterator<Exporter> exporters = loader.iterator(); while (exporters.hasNext()) { Exporter e = exporters.next(); String formatName = e.getProviderName(); cacheExport(releasedVersion, formatName, datasetAsJson, e); } } catch (ServiceConfigurationError serviceError) { throw new ExportException("Service configuration error during export. " + serviceError.getMessage()); } // Finally, if we have been able to successfully export in all available // formats, we'll increment the "last exported" time stamp: dataset.setLastExportTime(new Timestamp(new Date().getTime())); } public void clearAllCachedFormats(Dataset dataset) throws IOException { try { Iterator<Exporter> exporters = loader.iterator(); while (exporters.hasNext()) { Exporter e = exporters.next(); String formatName = e.getProviderName(); clearCachedExport(dataset, formatName); } dataset.setLastExportTime(null); } catch (IOException ex) { //not fatal } } // This method finds the exporter for the format requested, // then produces the dataset metadata as a JsonObject, then calls // the "cacheExport()" method that will save the produced output // in a file in the dataset directory. public void exportFormat(Dataset dataset, String formatName) throws ExportException { try { Iterator<Exporter> exporters = loader.iterator(); while (exporters.hasNext()) { Exporter e = exporters.next(); if (e.getProviderName().equals(formatName)) { DatasetVersion releasedVersion = dataset.getReleasedVersion(); if (releasedVersion == null) { throw new IllegalStateException("No Released Version"); } JsonPrinter jsonPrinter = new JsonPrinter(settingsService); final JsonObjectBuilder datasetAsJsonBuilder = jsonPrinter.jsonAsDatasetDto(releasedVersion); cacheExport(releasedVersion, formatName, datasetAsJsonBuilder.build(), e); } } } catch (ServiceConfigurationError serviceError) { throw new ExportException("Service configuration error during export. " + serviceError.getMessage()); } catch (IllegalStateException e) { throw new ExportException("No published version found during export. " + dataset.getGlobalIdString()); } } public Exporter getExporter(String formatName) throws ExportException { try { Iterator<Exporter> exporters = loader.iterator(); while (exporters.hasNext()) { Exporter e = exporters.next(); if (e.getProviderName().equals(formatName)) { return e; } } } catch (ServiceConfigurationError serviceError) { throw new ExportException("Service configuration error during export. " + serviceError.getMessage()); } catch (Exception ex) { throw new ExportException("Could not find Exporter \"" + formatName + "\", unknown exception"); } throw new ExportException("No such Exporter: " + formatName); } // This method runs the selected metadata exporter, caching the output // in a file in the dataset directory / container based on its DOI: private void cacheExport(DatasetVersion version, String format, JsonObject datasetAsJson, Exporter exporter) throws ExportException { boolean tempFileRequired = false; File tempFile = null; OutputStream outputStream = null; Dataset dataset = version.getDataset(); StorageIO<Dataset> storageIO = null; try { // With some storage drivers, we can open a WritableChannel, or OutputStream // to directly write the generated metadata export that we want to cache; // Some drivers (like Swift) do not support that, and will give us an // "operation not supported" exception. If that's the case, we'll have // to save the output into a temp file, and then copy it over to the // permanent storage using the IO "save" command: try { storageIO = DataAccess.createNewStorageIO(dataset, "placeholder"); Channel outputChannel = storageIO.openAuxChannel("export_" + format + ".cached", DataAccessOption.WRITE_ACCESS); outputStream = Channels.newOutputStream((WritableByteChannel) outputChannel); } catch (IOException ioex) { tempFileRequired = true; tempFile = File.createTempFile("tempFileToExport", ".tmp"); outputStream = new FileOutputStream(tempFile); } try { Path cachedMetadataFilePath = Paths.get(version.getDataset().getFileSystemDirectory().toString(), "export_" + format + ".cached"); if (!tempFileRequired) { FileOutputStream cachedExportOutputStream = new FileOutputStream(cachedMetadataFilePath.toFile()); exporter.exportDataset(version, datasetAsJson, cachedExportOutputStream); cachedExportOutputStream.flush(); cachedExportOutputStream.close(); outputStream.close(); } else { // this method copies a local filesystem Path into this DataAccess Auxiliary location: exporter.exportDataset(version, datasetAsJson, outputStream); outputStream.flush(); outputStream.close(); logger.fine("Saving path as aux for temp file in: " + Paths.get(tempFile.getAbsolutePath())); storageIO.savePathAsAux(Paths.get(tempFile.getAbsolutePath()), "export_" + format + ".cached"); boolean tempFileDeleted = tempFile.delete(); logger.fine("tempFileDeleted: " + tempFileDeleted); } } catch (IOException ioex) { throw new ExportException("IO Exception thrown exporting as " + "export_" + format + ".cached"); } } catch (IOException ioex) { throw new ExportException("IO Exception thrown exporting as " + "export_" + format + ".cached"); } finally { if(null!=outputStream) { try{ outputStream.close(); } catch(IOException ic){} } } } private void clearCachedExport(Dataset dataset, String format) throws IOException { try { StorageIO<Dataset> storageIO = getStorageIO(dataset); storageIO.deleteAuxObject("export_" + format + ".cached"); } catch (IOException ex) { throw new IOException("IO Exception thrown exporting as " + "export_" + format + ".cached"); } } // This method checks if the metadata has already been exported in this // format and cached on disk. If it has, it'll open the file and retun // the file input stream. If not, it'll return null. private InputStream getCachedExportFormat(Dataset dataset, String formatName) throws ExportException, IOException { StorageIO<Dataset> dataAccess = null; try { dataAccess = DataAccess.getStorageIO(dataset); } catch (IOException ioex) { throw new IOException("IO Exception thrown exporting as " + "export_" + formatName + ".cached"); } InputStream cachedExportInputStream = null; try { if (dataAccess.getAuxFileAsInputStream("export_" + formatName + ".cached") != null) { cachedExportInputStream = dataAccess.getAuxFileAsInputStream("export_" + formatName + ".cached"); return cachedExportInputStream; } } catch (IOException ioex) { throw new IOException("IO Exception thrown exporting as " + "export_" + formatName + ".cached"); } return null; } /*The below method, getCachedExportSize(), is not currently used. *An exercise for the reader could be to refactor it if it's needed *to be compatible with storage drivers other than local filesystem. *Files.exists() would need to be discarded. * -- L.A. 4.8 */ // public Long getCachedExportSize(Dataset dataset, String formatName) { // try { // if (dataset.getFileSystemDirectory() != null) { // Path cachedMetadataFilePath = Paths.get(dataset.getFileSystemDirectory().toString(), "export_" + formatName + ".cached"); // if (Files.exists(cachedMetadataFilePath)) { // return cachedMetadataFilePath.toFile().length(); // } catch (Exception ioex) { // // don't do anything - we'll just return null // return null; public Boolean isXMLFormat(String provider) { try { Iterator<Exporter> exporters = loader.iterator(); while (exporters.hasNext()) { Exporter e = exporters.next(); if (e.getProviderName().equals(provider)) { return e.isXMLFormat(); } } } catch (ServiceConfigurationError serviceError) { serviceError.printStackTrace(); } return null; } }
package gr.iti.mklab.reveal.summarization; import org.mongodb.morphia.annotations.Id; public class RankedImage implements Comparable<RankedImage> { public RankedImage() { } public RankedImage(String id, double score) { this.id = id; this.score = score; } @Id protected String id; protected double score; public String getId() { return id; } public void setId(String id) { this.id = id; } public double getScore() { return score; } public void setScore(double score) { this.score = score; } @Override public int compareTo(RankedImage other) { if(this.score == other.score) { return 0; } return this.score>other.score ? -1 : 1; } }
package harmony.mastermind.logic.commands; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashSet; import java.util.Optional; import java.util.Set; import java.util.regex.Pattern; import harmony.mastermind.commons.core.Messages; import harmony.mastermind.commons.core.UnmodifiableObservableList; import harmony.mastermind.commons.exceptions.IllegalValueException; import harmony.mastermind.model.tag.Tag; import harmony.mastermind.model.tag.UniqueTagList; import harmony.mastermind.model.task.ReadOnlyTask; import harmony.mastermind.model.task.Task; import harmony.mastermind.model.task.UniqueTaskList; import harmony.mastermind.model.task.UniqueTaskList.DuplicateTaskException; import harmony.mastermind.model.task.UniqueTaskList.TaskNotFoundException; /** * Edits a task in task manager * */ public class EditCommand extends Command implements Undoable, Redoable { public static final String COMMAND_KEYWORD_EDIT = "edit"; public static final String COMMAND_KEYWORD_UPDATE = "update"; public static final String COMMAND_ARGUMENTS_REGEX = "(?=(?<index>\\d+))" + "(?=(?:.*?r\\/'(?<recur>.+?)')?)" + "(?=(?:.*?\\s\\'(?<name>.+?)')?)" + "(?=(?:.*?sd\\/'(?<startDate>.+?)')?)" + "(?=(?:.*?ed\\/'(?<endDate>.+?)')?)" + "(?=(?:.*t\\/'(?<tags>\\w+(?:,\\w+)*)?')?)" + ".*"; public static final Pattern COMMAND_ARGUMENTS_PATTERN = Pattern.compile(COMMAND_ARGUMENTS_REGEX); public static final String COMMAND_SUMMARY = "Editting a task:" + "\n" + "(" + COMMAND_KEYWORD_EDIT + " | " + COMMAND_KEYWORD_UPDATE + ") " + "<index> ['<task_name>'] [sd/'<start_date>'] [ed/<end_date>'] [t/'<comma_spearated_tags>']"; public static final String MESSAGE_USAGE = COMMAND_SUMMARY + "\n" + "Edits the task identified by the index number used in the last task listing.\n" + "Example: " + COMMAND_KEYWORD_EDIT + " 1 'I change the task name to this, unspecified field are preserved.'"; public static final String MESSAGE_EDIT_TASK_PROMPT = "Edit the following task: %1$s"; public static final String MESSAGE_EDIT_TASK_SUCCESS = "Task successfully edited: %1$s"; public static final String MESSAGE_UNDO_SUCCESS = "[Undo Edit Command] Task reverted: %1$s"; public static final String MESSAGE_REDO_SUCCESS = "[Redo Edit Command] Edit the following task: %1$s"; // private MainWindow window; private ReadOnlyTask originalTask; private Task editedTask; private final int targetIndex; private Optional<String> name; private Optional<String> startDate; private Optional<String> endDate; private Optional<String> recur; private Optional<Set<String>> tags; public EditCommand(int targetIndex, Optional<String> name, Optional<String> startDate, Optional<String> endDate, Optional<Set<String>> tags, Optional<String> recur) throws IllegalValueException, ParseException { this.targetIndex = targetIndex; this.name = name; this.startDate = startDate; this.endDate = endDate; this.recur = recur; this.tags = tags; } @Override public CommandResult execute() { try { // grabbing the origin task (before edit) executeEdit(); model.pushToUndoHistory(this); // this is a new command entered by user (not undo/redo) // need to clear the redoHistory Stack model.clearRedoHistory(); return new CommandResult(COMMAND_KEYWORD_EDIT, String.format(MESSAGE_EDIT_TASK_PROMPT, originalTask)); } catch (TaskNotFoundException | DuplicateTaskException | IndexOutOfBoundsException ie) { return new CommandResult(COMMAND_KEYWORD_EDIT, Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX); } } @Override // @@author A0138862W public CommandResult undo() { try { // remove the task that's previously edited model.deleteTask(editedTask); // add back the original task model.addTask((Task) originalTask); model.pushToRedoHistory(this); return new CommandResult(COMMAND_KEYWORD_EDIT, String.format(MESSAGE_UNDO_SUCCESS, originalTask)); } catch (UniqueTaskList.TaskNotFoundException pne) { return new CommandResult(COMMAND_KEYWORD_EDIT, Messages.MESSAGE_TASK_NOT_IN_MASTERMIND); } catch (DuplicateTaskException e) { return new CommandResult(COMMAND_KEYWORD_EDIT, AddCommand.MESSAGE_DUPLICATE_TASK); } } @Override // @@author A0138862W public CommandResult redo() { try { executeEdit(); model.pushToUndoHistory(this); return new CommandResult(COMMAND_KEYWORD_EDIT, String.format(MESSAGE_REDO_SUCCESS, originalTask)); } catch (TaskNotFoundException | DuplicateTaskException | IndexOutOfBoundsException ie) { return new CommandResult(COMMAND_KEYWORD_EDIT, Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX); } } private void executeEdit() throws TaskNotFoundException, DuplicateTaskException, IndexOutOfBoundsException { UnmodifiableObservableList<ReadOnlyTask> lastShownList = model.getFilteredTaskList(); if (lastShownList.size() < targetIndex) { indicateAttemptToExecuteIncorrectCommand(); throw new IndexOutOfBoundsException(); } if (originalTask == null) { originalTask = lastShownList.get(targetIndex - 1); } // if user provides explicit field and value, we change them // otherwise, all user omitted field are preserve from the original // before edit String toEditName = name.map(val -> val).orElse(originalTask.getName()); Date toEditStartDate = startDate.map(val -> prettyTimeParser.parse(val).get(0)).orElse(originalTask.getStartDate()); Date toEditEndDate = endDate.map(val -> prettyTimeParser.parse(val).get(0)).orElse(originalTask.getEndDate()); String toEditRecur = recur.map(val -> val).orElse(originalTask.getRecur()); UniqueTagList toEditTags = new UniqueTagList(tags.map(val -> { final Set<Tag> tagSet = new HashSet<>(); for (String tagName : val) { try { tagSet.add(new Tag(tagName)); } catch (IllegalValueException e) { e.printStackTrace(); } } return tagSet; }).orElse(originalTask.getTags().toSet())); // initialize the new task with edited values if (editedTask == null) { editedTask = new Task(toEditName, toEditStartDate, toEditEndDate, toEditTags, toEditRecur); } model.deleteTask(originalTask); model.addTask(editedTask); } }
package hudson.plugins.warnings.parser; import hudson.plugins.warnings.util.model.FileAnnotation; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Registry for the active parsers in this plug-in. * * @author Ulli Hafner */ public class ParserRegistry { /** The available parsers of this plug-in. */ private final List<AnnotationParser> parsers = new ArrayList<AnnotationParser>(); /** * Creates a new instance of <code>ParserRegistry</code>. */ public ParserRegistry() { parsers.add(new HpiCompileParser()); parsers.add(new JavacParser()); parsers.add(new MsBuildParser()); } /** * Iterates over the available parsers and parses the specified file with each parser. * Returns all found warnings. * * @param file the input stream * @return all found warnings * * @throws IOException Signals that an I/O exception has occurred. */ public Collection<FileAnnotation> parse(final File file) throws IOException { List<FileAnnotation> annotations = new ArrayList<FileAnnotation>(); for (AnnotationParser parser : parsers) { annotations.addAll(parser.parse(createInputStream(file))); } return annotations; } /** * Creates the input stream to parse from the specified file. * * @param file the file to parse * @return the input stream * @throws FileNotFoundException */ protected InputStream createInputStream(final File file) throws FileNotFoundException { return new FileInputStream(file); } }
package info.faceland.loot.listeners; import info.faceland.hilt.HiltItemStack; import info.faceland.loot.LootPlugin; import info.faceland.loot.api.enchantments.EnchantmentStone; import info.faceland.loot.api.sockets.SocketGem; import info.faceland.loot.math.LootRandom; import info.faceland.loot.utils.StringListUtils; import info.faceland.loot.utils.messaging.Chatty; import info.faceland.utils.TextUtils; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.inventory.EnchantingInventory; import java.util.ArrayList; import java.util.List; public final class InteractListener implements Listener { private final LootPlugin plugin; private LootRandom random; public InteractListener(LootPlugin plugin) { this.plugin = plugin; this.random = new LootRandom(System.currentTimeMillis()); } @EventHandler(priority = EventPriority.LOWEST) public void onInventoryOpenEvent(InventoryOpenEvent event) { if (event.getInventory() instanceof EnchantingInventory) { event.setCancelled(true); } } @EventHandler(priority = EventPriority.LOWEST) public void onInventoryClick(InventoryClickEvent event) { if (event.getCurrentItem() == null || event.getCursor() == null || event.getCurrentItem().getType() == Material.AIR || event.getCursor().getType() == Material.AIR || !(event.getWhoClicked() instanceof Player)) { return; } Player player = (Player) event.getWhoClicked(); HiltItemStack currentItem = new HiltItemStack(event.getCurrentItem()); HiltItemStack cursor = new HiltItemStack(event.getCursor()); if (cursor.getName().startsWith(ChatColor.GOLD + "Socket Gem - ")) { String gemName = ChatColor.stripColor(cursor.getName().replace(ChatColor.GOLD + "Socket Gem - ", "")); SocketGem gem = plugin.getSocketGemManager().getSocketGem(gemName); if (gem == null) { return; } if (!plugin.getItemGroupManager().getMatchingItemGroups(currentItem.getType()).containsAll( gem.getItemGroups())) { Chatty.sendMessage(player, plugin.getSettings().getString("language.socket.failure", "")); player.playSound(player.getEyeLocation(), Sound.LAVA_POP, 1F, 0.5F); return; } List<String> lore = currentItem.getLore(); List<String> strippedLore = StringListUtils.stripColor(lore); if (!strippedLore.contains("(Socket)")) { Chatty.sendMessage(player, plugin.getSettings().getString("language.socket.needs-sockets", "")); player.playSound(player.getEyeLocation(), Sound.LAVA_POP, 1F, 0.5F); return; } int index = strippedLore.indexOf("(Socket)"); if (gem.isTriggerable()) { lore.set(index, ChatColor.GOLD + gem.getName()); lore.addAll(index + 1, TextUtils.color(gem.getLore())); } else { lore.remove(index); lore.addAll(index, TextUtils.color(gem.getLore())); } currentItem.setLore(lore); String name = currentItem.getName(); ChatColor start = getFirstColor(name); if (start != null) { name = start + gem.getPrefix() + " " + name + " " + gem.getSuffix() + ChatColor.getLastColors(name); } else { name = gem.getPrefix() + " " + name + " " + gem.getSuffix() + ChatColor.getLastColors(name); } currentItem.setName(name); Chatty.sendMessage(player, plugin.getSettings().getString("language.socket.success", "")); player.playSound(player.getEyeLocation(), Sound.ORB_PICKUP, 1L, 2.0F); } else if (cursor.getName().startsWith(ChatColor.BLUE + "Enchantment Tome - ")) { String stoneName = ChatColor.stripColor( cursor.getName().replace(ChatColor.BLUE + "Enchantment Tome - ", "")); EnchantmentStone stone = plugin.getEnchantmentStoneManager().getEnchantmentStone(stoneName); if (!isBlockWithinRadius(Material.ENCHANTMENT_TABLE, event.getWhoClicked().getLocation(), 5)) { Chatty.sendMessage(player, plugin.getSettings().getString("language.enchant.no-enchantment-table", "")); player.playSound(player.getEyeLocation(), Sound.LAVA_POP, 1F, 0.5F); return; } if (stone == null) { return; } if (!plugin.getItemGroupManager().getMatchingItemGroups(currentItem.getType()).containsAll( stone.getItemGroups())) { Chatty.sendMessage(player, plugin.getSettings().getString("language.enchant.failure", "")); player.playSound(player.getEyeLocation(), Sound.LAVA_POP, 1F, 0.5F); return; } List<String> lore = currentItem.getLore(); List<String> strippedLore = StringListUtils.stripColor(lore); if (!strippedLore.contains("(Enchantable)")) { Chatty.sendMessage(player, plugin.getSettings().getString("language.enchant.needs-enchantable", "")); player.playSound(player.getEyeLocation(), Sound.LAVA_POP, 1F, 0.5F); return; } int index = strippedLore.indexOf("(Enchantable)"); List<String> added = new ArrayList<>(); for (int i = 0; i < random.nextIntRange(stone.getMinStats(), stone.getMaxStats()); i++) { added.add(stone.getLore().get(random.nextInt(stone.getLore().size()))); } lore.remove(index); lore.addAll(index, TextUtils.color(added)); currentItem.setLore(lore); Chatty.sendMessage(player, plugin.getSettings().getString("language.enchant.success", "")); player.playSound(player.getEyeLocation(), Sound.PORTAL_TRAVEL, 1L, 2.0F); } else { return; } event.setCurrentItem(currentItem); cursor.setAmount(cursor.getAmount() - 1); event.setCursor(cursor.getAmount() == 0 ? null : cursor); event.setCancelled(true); event.setResult(Event.Result.DENY); } private boolean isBlockWithinRadius(Material material, Location location, int radius) { int minX = location.getBlockX() - radius; int maxX = location.getBlockX() + radius; int minY = location.getBlockY() - radius; int maxY = location.getBlockY() + radius; int minZ = location.getBlockZ() - radius; int maxZ = location.getBlockZ() + radius; for (int x = minX; x < maxX; x++) { for (int y = minY; y < maxY; y++) { for (int z = minZ; z < maxZ; z++) { Block block = location.getWorld().getBlockAt(x, y, z); if (block.getType() == material) { return true; } } } } return false; } private ChatColor getFirstColor(String s) { for (int i = 0; i < s.length() - 1; i++) { if (!s.substring(i, i + 1).equals(ChatColor.COLOR_CHAR + "")) { continue; } ChatColor c = ChatColor.getByChar(s.substring(i + 1, i + 2)); if (c != null) { return c; } } return null; } }
package io.fabric8.che.starter.client; import java.io.IOException; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import io.fabric8.che.starter.client.keycloak.KeycloakRestTemplate; import io.fabric8.che.starter.exception.StackNotFoundException; import io.fabric8.che.starter.exception.WorkspaceNotFound; import io.fabric8.che.starter.model.workspace.Workspace; import io.fabric8.che.starter.model.workspace.WorkspaceConfig; import io.fabric8.che.starter.model.workspace.WorkspaceState; import io.fabric8.che.starter.model.workspace.WorkspaceStatus; import io.fabric8.che.starter.openshift.OpenShiftClientWrapper; import io.fabric8.che.starter.util.WorkspaceHelper; import io.fabric8.kubernetes.api.model.Pod; import io.fabric8.kubernetes.api.model.PodList; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.Watch; import io.fabric8.kubernetes.client.Watcher; import io.fabric8.kubernetes.client.dsl.FilterWatchListDeletable; import io.fabric8.openshift.client.OpenShiftClient; @Component public class WorkspaceClient { private static final Logger LOG = LoggerFactory.getLogger(WorkspaceClient.class); @Value("${che.workspace.start.timeout}") private long workspaceStartTimeout; @Value("${che.workspace.stop.timeout}") private long workspaceStopTimeout; @Autowired private WorkspaceHelper workspaceHelper; @Autowired private StackClient stackClient; @Autowired OpenShiftClientWrapper openshiftClientWrapper; @Value("${che.openshift.start.timeout}") private String startTimeout; @Value("${che.openshift.deploymentconfig}") private String deploymentConfigName; public void waitUntilWorkspaceIsRunning(String cheServerURL, Workspace workspace, String keycloakToken) { WorkspaceStatus status = getWorkspaceStatus(cheServerURL, workspace.getId(), keycloakToken); long currentTime = System.currentTimeMillis(); while (!WorkspaceState.RUNNING.toString().equals(status.getWorkspaceStatus()) && System.currentTimeMillis() < (currentTime + workspaceStartTimeout)) { try { Thread.sleep(1000); LOG.info("Polling workspace '{}' status...", workspace.getConfig().getName()); } catch (InterruptedException e) { LOG.error("Error while polling for workspace status", e); break; } status = getWorkspaceStatus(cheServerURL, workspace.getId(), keycloakToken); } LOG.info("Workspace '{}' is running", workspace.getConfig().getName()); } /** * This method blocks execution until the specified workspace has been stopped and its resources * made available again. * * @param masterUrl The master URL for the OpenShift API * @param namespace The OpenShift namespace * @param openShiftToken The OpenShift token * @param cheServerURL Che server URL * @param workspace The workspace to stop * @param keycloakToken The KeyCloak token */ public void waitUntilWorkspaceIsStopped(String masterUrl, String namespace, String openShiftToken, String cheServerURL, Workspace workspace, String keycloakToken) { try (OpenShiftClient client = openshiftClientWrapper.get(masterUrl, openShiftToken)) { String resourceName = "che-ws-" + workspace.getId().replace("workspace", ""); LOG.info("Resource name {}", resourceName); FilterWatchListDeletable<Pod, PodList, Boolean, Watch, Watcher<Pod>> pods = client.pods().inNamespace(namespace).withLabel("deployment", resourceName); int numberOfPodsToStop = pods.list().getItems().size(); LOG.info("Number of workspace pods to stop {}", numberOfPodsToStop); if (numberOfPodsToStop > 0) { final CountDownLatch podCount = new CountDownLatch(numberOfPodsToStop); pods.watch(new Watcher<Pod>() { @Override public void eventReceived(Action action, Pod pod) { try { switch (action) { case ADDED: case MODIFIED: case ERROR: break; case DELETED: LOG.info("Pod {} deleted", pod.getMetadata().getName()); podCount.countDown(); break; } } catch (Exception ex) { LOG.error("Failed to process {} on Pod {}. Error: ", action, pod, ex); } } @Override public void onClose(KubernetesClientException ex) { } }); WorkspaceStatus status = getWorkspaceStatus(cheServerURL, workspace.getId(), keycloakToken); long currentTime = System.currentTimeMillis(); // Poll the Che server until it returns a status of 'STOPPED' for the workspace while (!WorkspaceState.STOPPED.toString().equals(status.getWorkspaceStatus()) && System.currentTimeMillis() < (currentTime + workspaceStopTimeout)) { try { Thread.sleep(1000); LOG.info("Polling Che server for workspace '{}' status...", workspace.getConfig().getName()); } catch (InterruptedException e) { LOG.error("Error while polling for workspace status", e); break; } status = getWorkspaceStatus(cheServerURL, workspace.getId(), keycloakToken); } currentTime = System.currentTimeMillis(); try { LOG.info("Waiting for all pods to be deleted for workspace '{}'", workspace.getConfig().getName()); podCount.await(workspaceStopTimeout, TimeUnit.MILLISECONDS); } catch (InterruptedException ex) { LOG.error("Exception while waiting for pods to be deleted", ex); } } } } public List<Workspace> listWorkspaces(String cheServerUrl, String keycloakToken) { String url = CheRestEndpoints.LIST_WORKSPACES.generateUrl(cheServerUrl); RestTemplate template = new KeycloakRestTemplate(keycloakToken); ResponseEntity<List<Workspace>> response = template.exchange(url, HttpMethod.GET, null, new ParameterizedTypeReference<List<Workspace>>() { }); return response.getBody(); } public List<Workspace> listWorkspacesPerRepository(String cheServerUrl, String repository, String keycloakToken) { List<Workspace> workspaces = listWorkspaces(cheServerUrl, keycloakToken); return workspaceHelper.filterByRepository(workspaces, repository); } /** * Create workspace on the Che server with given URL. * * @param cheServerUrl * @param keycloakToken * @param name * @param stackId * @param repo * @param branch * @return * @throws StackNotFoundException * @throws IOException */ public Workspace createWorkspace(String cheServerURL, String keycloakToken, String stackId, String repo, String branch, String description) throws StackNotFoundException, IOException { // The first step is to create the workspace String url = CheRestEndpoints.CREATE_WORKSPACE.generateUrl(cheServerURL); WorkspaceConfig wsConfig = stackClient.getStack(cheServerURL, stackId, keycloakToken).getWorkspaceConfig(); wsConfig.setName(workspaceHelper.generateName()); wsConfig.setDescription(description); RestTemplate template = new KeycloakRestTemplate(keycloakToken); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<WorkspaceConfig> entity = new HttpEntity<WorkspaceConfig>(wsConfig, headers); ResponseEntity<Workspace> workspaceResponse = template.exchange(url, HttpMethod.POST, entity, Workspace.class); Workspace workspace = workspaceResponse.getBody(); LOG.info("Workspace has been created: {}", workspace); return workspace; } public Workspace getWorkspaceById(String cheServerURL, String workspaceId, String keycloakToken) { String url = CheRestEndpoints.GET_WORKSPACE_BY_ID.generateUrl(cheServerURL, workspaceId); RestTemplate template = new KeycloakRestTemplate(keycloakToken); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> entity = new HttpEntity<String>(headers); return template.exchange(url, HttpMethod.GET, entity, Workspace.class).getBody(); } public Workspace getWorkspaceByName(String cheServerURL, String workspaceName, String keycloakToken) throws WorkspaceNotFound { List<Workspace> workspaces = listWorkspaces(cheServerURL, keycloakToken); for (Workspace workspace : workspaces) { if (workspace.getConfig().getName().equals(workspaceName)) { return getWorkspaceById(cheServerURL, workspace.getId(), keycloakToken); } } throw new WorkspaceNotFound("Workspace '" + workspaceName + "' was not found"); } /** Deletes a workspace. Workspace must be stopped before invoking its deletion. * * @param cheServerURL Che server URL * @param workspaceId workspace ID * @throws WorkspaceNotFound if workspace does not exists */ public void deleteWorkspace(String cheServerURL, String workspaceId, String keycloakToken) throws WorkspaceNotFound { String url = CheRestEndpoints.DELETE_WORKSPACE.generateUrl(cheServerURL, workspaceId); RestTemplate template = new KeycloakRestTemplate(keycloakToken); template.delete(url); } /** * Starts and gets a workspace by its name. * * @param cheServerURL * Che server URL * @param workspaceName * name of workspace to start * @return started workspace * @throws WorkspaceNotFound */ public Workspace startWorkspace(String cheServerURL, String workspaceName, String masterUrl, String namespace, String openShiftToken, String keycloakToken) throws WorkspaceNotFound { List<Workspace> workspaces = listWorkspaces(cheServerURL, keycloakToken); boolean alreadyStarted = false; Workspace workspaceToStart = null; for (Workspace workspace : workspaces) { if (workspace.getConfig().getName().equals(workspaceName)) { workspaceToStart = workspace; if (WorkspaceState.RUNNING.toString().equals(workspace.getStatus()) || WorkspaceState.STARTING.toString().equals(workspace.getStatus())) { alreadyStarted = true; } } else if (!WorkspaceState.STOPPED.toString().equals(workspace.getStatus())) { stopWorkspace(cheServerURL, workspace, keycloakToken); waitUntilWorkspaceIsStopped(masterUrl, namespace, openShiftToken, cheServerURL, workspace, keycloakToken); } } if (workspaceToStart == null) { throw new WorkspaceNotFound("Workspace '" + workspaceName + "' does not exist."); } if (!alreadyStarted) { String url = CheRestEndpoints.START_WORKSPACE.generateUrl(cheServerURL, workspaceToStart.getId()); RestTemplate template = new KeycloakRestTemplate(keycloakToken); template.postForLocation(url, null); } return workspaceToStart; } /** * Gets started/starting workspace. * * @param cheServerUrl * url of che server * @return started workspace or null if there is no running/starting * workspace */ public Workspace getStartedWorkspace(String cheServerURL, String keycloakToken) { List<Workspace> workspaces = listWorkspaces(cheServerURL, keycloakToken); for (Workspace workspace : workspaces) { if (WorkspaceState.RUNNING.toString().equals(workspace.getStatus()) || WorkspaceState.STARTING.toString().equals(workspace.getStatus())) { return workspace; } } return null; } /** * Gets workspace status * * @param cheServerURL * Che server URL * @param workspaceId * workspace ID * @return workspace status */ public WorkspaceStatus getWorkspaceStatus(String cheServerURL, String workspaceId, String keycloakToken) { String url = CheRestEndpoints.CHECK_WORKSPACE.generateUrl(cheServerURL, workspaceId); RestTemplate template = new KeycloakRestTemplate(keycloakToken); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> entity = new HttpEntity<String>(headers); ResponseEntity<WorkspaceStatus> status = template.exchange(url, HttpMethod.GET, entity, WorkspaceStatus.class); return status.getBody(); } /** * Stops a running workspace. */ public void stopWorkspace(String cheServerURL, Workspace workspace, String keycloakToken) { LOG.info("Stopping workspace {}", workspace.getId()); String url = CheRestEndpoints.STOP_WORKSPACE.generateUrl(cheServerURL, workspace.getId()); RestTemplate template = new KeycloakRestTemplate(keycloakToken); template.delete(url); } }
package io.korobi.mongotoelastic.mongo; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase; import io.korobi.mongotoelastic.exception.UserIsAtFaultException; import io.korobi.mongotoelastic.logging.InjectLogger; import io.korobi.mongotoelastic.opt.IOptions; import io.korobi.mongotoelastic.processor.IDocumentProcessor; import io.korobi.mongotoelastic.processor.RunnableProcessor; import io.korobi.mongotoelastic.util.NumberUtil; import org.apache.logging.log4j.Logger; import org.bson.Document; import javax.inject.Inject; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; public class MongoRetriever { @InjectLogger private Logger logger; private MongoDatabase database; private IOptions opts; private IDocumentProcessor processor; private int itemsPerThread; @Inject public MongoRetriever(MongoDatabase database, IOptions opts, IDocumentProcessor processor) { this.database = database; this.opts = opts; this.processor = processor; this.checkUserThreadParameters(); } private void checkUserThreadParameters() { double itemsPerThread = this.opts.getBatchSize() / (double) this.opts.getThreadCap(); if (NumberUtil.isValueFractional(itemsPerThread)) { throw new UserIsAtFaultException("Disallowing poor thread-related option choice."); } this.itemsPerThread = (int) itemsPerThread; } public void processData() { MongoCollection<Document> collection = this.database.getCollection("chats"); logger.info("There are " + String.valueOf(collection.count()) + " chats!"); List<Document> currentBatch; FindIterable<Document> iterable = collection.find(); iterable.batchSize(this.opts.getBatchSize()); MongoCursor<Document> cursor = iterable.iterator(); logger.info("Done with that"); while (!(currentBatch = this.buildBatch(cursor)).isEmpty()) { // great! We have a bunch of documents in RAM now :D CountDownLatch latch = new CountDownLatch(this.opts.getThreadCap()); logger.info(String.format("Got a new batch of %d documents", currentBatch.size())); if (currentBatch.size() != this.opts.getBatchSize()) { logger.info("Last batch!"); } for (int threadNumber = 1; threadNumber <= this.opts.getThreadCap(); threadNumber++) { int fromIndex = (threadNumber - 1) * this.itemsPerThread; int endIndex = fromIndex + this.itemsPerThread; int lastIndexInBatch = currentBatch.size() - 1; if (endIndex > lastIndexInBatch) { endIndex = lastIndexInBatch; } List<Document> forThread = currentBatch.subList(fromIndex, endIndex); Thread thread = new Thread(new RunnableProcessor(forThread, this.processor, latch)); thread.start(); logger.info(String.format("Spawned thread %d", threadNumber)); } logger.info("Awaiting current batch end..."); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } } cursor.close(); } private List<Document> buildBatch(MongoCursor<Document> cursor) { logger.info("Hello from buildBatch!"); List<Document> currentBatch = new ArrayList<>(this.opts.getBatchSize()); logger.info("Instantiated ArrayList :)"); while (cursor.hasNext() && currentBatch.size() < this.opts.getBatchSize()) { currentBatch.add(cursor.next()); // yield return cursor.next() :( } return currentBatch; } }
package io.seqware.pancancer; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.List; import java.util.Map; import net.sourceforge.seqware.pipeline.workflowV2.AbstractWorkflowDataModel; import net.sourceforge.seqware.pipeline.workflowV2.model.Job; import net.sourceforge.seqware.pipeline.workflowV2.model.SqwFile; import org.apache.commons.lang.StringUtils; public class CgpCnIndelSnvStrWorkflow extends AbstractWorkflowDataModel { private static String OUTDIR = "outdir"; private static String TIMEDIR; private static String COUNTDIR; private static String BBDIR; private boolean testMode=false; private boolean cleanup = false; // datetime all upload files will be named with DateFormat df = new SimpleDateFormat("yyyyMMdd"); String dateString = df.format(Calendar.getInstance().getTime()); private String workflowName = "svcp_1-0-0"; // MEMORY variables // private String memBasFileGet, memGnosDownload, memPackageResults, memMarkTime, memQcMetrics, memUpload, memGetTbi, memPicnicCounts, memPicnicMerge, memUnpack, memBbMerge, // ascat memory memAlleleCount, memAscat, memAscatFinalise, // pindel memory memPindelInput, memPindel, memPindelVcf, memPindelMerge , memPindelFlag, // brass memory memBrassInput, memBrassGroup, memBrassFilter, memBrassSplit, memBrassAssemble, memBrassGrass, memBrassTabix, // caveman memory memCaveCnPrep, memCavemanSetup, memCavemanSplit, memCavemanSplitConcat, memCavemanMstep, memCavemanMerge, memCavemanEstep, memCavemanMergeResults, memCavemanAddIds, memCavemanFlag, memCavemanTbiClean ; // workflow variables private String // reference variables species, assembly, // sequencing type/protocol seqType, seqProtocol, //GNOS identifiers pemFile, gnosServer, uploadServer, // ascat variables gender, // pindel variables refExclude, pindelGermline, //caveman variables tabixSrvUri, //general variables installBase, refBase, genomeFaGz, testBase; private int coresAddressable; private void init() { try { //optional properties String outDir = OUTDIR; String outPrefix = ""; if (hasPropertyAndNotNull("output_dir")) { outDir = getProperty("output_dir"); } if (hasPropertyAndNotNull("output_prefix")) { outPrefix = getProperty("output_prefix"); } if (!"".equals(outPrefix)) { if (outPrefix.endsWith("/")) { OUTDIR = outPrefix+outDir; } else { OUTDIR = outPrefix + "/" + outDir; } } } catch (Exception e) { throw new RuntimeException(e); } TIMEDIR = OUTDIR + "/timings"; COUNTDIR = OUTDIR + "/ngsCounts"; BBDIR = OUTDIR + "/bbCounts"; } @Override public void setupDirectory() { //since setupDirectory is the first method run, we use it to initialize variables too. init(); // creates a dir1 directory in the current working directory where the workflow runs addDirectory(OUTDIR); addDirectory(TIMEDIR); addDirectory(COUNTDIR); addDirectory(BBDIR); } @Override public Map<String, SqwFile> setupFiles() { try { if(hasPropertyAndNotNull("cleanup")) { cleanup = Boolean.valueOf(getProperty("cleanup")); } if(hasPropertyAndNotNull("testMode")) { testMode=Boolean.valueOf(getProperty("testMode")); System.err.println("WARNING\n\tRunning in test mode, direct access BAM files will be used, change 'testMode' in ini file to disable\n"); } if(hasPropertyAndNotNull("uploadServer")) { uploadServer = getProperty("uploadServer"); } else { System.err.println("WARNING\n\t'uploadServer' not defined in workflow.ini, no VCF upload will be attempted\n"); } if(testMode && uploadServer != null) { System.err.println("WARNING\n\t'uploadServer' has been cleared as testMode is in effect\n"); uploadServer = null; } // used by steps that can use all available cores coresAddressable = Integer.valueOf(getProperty("coresAddressable")); // MEMORY // memBasFileGet = getProperty("memBasFileGet"); memGnosDownload = getProperty("memGnosDownload"); memPackageResults = getProperty("memPackageResults"); memMarkTime = getProperty("memMarkTime"); memQcMetrics = getProperty("memQcMetrics"); memUpload = getProperty("memUpload"); memGetTbi = getProperty("memGetTbi"); memPicnicCounts = getProperty("memPicnicCounts"); memPicnicMerge = getProperty("memPicnicMerge"); memUnpack = getProperty("memUnpack"); memBbMerge = getProperty("memBbMerge"); memAlleleCount = getProperty("memAlleleCount"); memAscat = getProperty("memAscat"); memAscatFinalise = getProperty("memAscatFinalise"); memPindelInput = getProperty("memPindelInput"); memPindel = getProperty("memPindel"); memPindelVcf = getProperty("memPindelVcf"); memPindelMerge = getProperty("memPindelMerge"); memPindelFlag = getProperty("memPindelFlag"); memBrassInput = getProperty("memBrassInput"); memBrassGroup = getProperty("memBrassGroup"); memBrassFilter = getProperty("memBrassFilter"); memBrassSplit = getProperty("memBrassSplit"); memBrassAssemble = getProperty("memBrassAssemble"); memBrassGrass = getProperty("memBrassGrass"); memBrassTabix = getProperty("memBrassTabix"); memCaveCnPrep = getProperty("memCaveCnPrep"); memCavemanSetup = getProperty("memCavemanSetup"); memCavemanSplit = getProperty("memCavemanSplit"); memCavemanSplitConcat = getProperty("memCavemanSplitConcat"); memCavemanMstep = getProperty("memCavemanMstep"); memCavemanMerge = getProperty("memCavemanMerge"); memCavemanEstep = getProperty("memCavemanEstep"); memCavemanMergeResults = getProperty("memCavemanMergeResults"); memCavemanAddIds = getProperty("memCavemanAddIds"); memCavemanFlag = getProperty("memCavemanFlag"); memCavemanTbiClean = getProperty("memCavemanTbiClean"); // REFERENCE INFO // species = getProperty("species"); assembly = getProperty("assembly"); // Sequencing info seqType = getProperty("seqType"); if(seqType.equals("WGS")) { seqProtocol = "genomic"; } // Specific to ASCAT workflow // gender = getProperty("gender"); // Specific to Caveman workflow // tabixSrvUri = getProperty("tabixSrvUri"); // pindel specific refExclude = getProperty("refExclude"); // used for upload too so always get it if(hasPropertyAndNotNull("gnosServer")) { gnosServer = getProperty("gnosServer"); } // test mode if(!testMode || (hasPropertyAndNotNull("upload-test") && Boolean.valueOf(getProperty("upload-test")))) { pemFile = getProperty("pemFile"); } //environment installBase = getWorkflowBaseDir() + "/bin/opt"; refBase = getWorkflowBaseDir() + "/data/reference/cgp_reference"; testBase = getWorkflowBaseDir() + "/data/testdata"; genomeFaGz = getWorkflowBaseDir() + "/data/reference/genome.fa.gz"; } catch (Exception ex) { throw new RuntimeException(ex); } return getFiles(); } private Job bamProvision(String analysisId, String bamFile, Job startTiming) { Job basJob = null; if(testMode == false) { Job gnosDownload = gnosDownloadBaseJob(analysisId); gnosDownload.setMaxMemory(memGnosDownload); gnosDownload.addParent(startTiming); // the file needs to end up in tumourBam/controlBam // get the BAS files basJob = basFileBaseJob(analysisId, bamFile); basJob.setMaxMemory(memBasFileGet); basJob.addParent(gnosDownload); } return basJob; } @Override public void buildWorkflow() { Job controlBasJob = null; String controlBam; List<String> tumourBams = new ArrayList<String>(); List<Job> tumourBasJobs = new ArrayList<Job>(); List<String> tumourAnalysisIds = new ArrayList<String>(); List<String> tumourAliquotIds = new ArrayList<String>(); String controlAnalysisId = new String(); Job startWorkflow = markTime("start"); startWorkflow.setMaxMemory(memMarkTime); try { if(testMode) { controlBam = OUTDIR + "/HCC1143_BL.bam"; controlAnalysisId = "HCC1143_BL"; tumourBams.add(OUTDIR + "/HCC1143.bam"); tumourAnalysisIds.add("HCC1143"); tumourAliquotIds.add("HCC1143"); controlBasJob = prepareTestData("HCC1143_BL"); controlBasJob.setMaxMemory("4000"); controlBasJob.setThreads(2); controlBasJob.addParent(startWorkflow); Job prepTum = prepareTestData("HCC1143"); prepTum.setMaxMemory("4000"); prepTum.setThreads(2); prepTum.addParent(startWorkflow); tumourBasJobs.add(prepTum); } else { controlAnalysisId = getProperty("controlAnalysisId"); controlBasJob = bamProvision(controlAnalysisId, getProperty("controlBam"), startWorkflow); controlBam = controlAnalysisId + "/" + getProperty("controlBam"); tumourAnalysisIds = Arrays.asList(getProperty("tumourAnalysisIds").split(":")); tumourAliquotIds = Arrays.asList(getProperty("tumourAliquotIds").split(":")); List<String> rawBams = Arrays.asList(getProperty("tumourBams").split(":")); if(rawBams.size() != tumourAnalysisIds.size()) { throw new RuntimeException("Properties tumourAnalysisId and tumourBam decode to lists of different sizes"); } if(rawBams.size() != tumourAliquotIds.size()) { throw new RuntimeException("Properties tumourAliquotIds and tumourBam decode to lists of different sizes"); } for(int i=0; i<rawBams.size(); i++) { Job tumourBasJob = bamProvision(tumourAnalysisIds.get(i), rawBams.get(i), startWorkflow); tumourBasJobs.add(tumourBasJob); String tumourBam = tumourAnalysisIds.get(i) + "/" + rawBams.get(i); tumourBams.add(tumourBam); } } } catch(Exception e) { throw new RuntimeException(e); } Job getTbiJob = stageTbi(); getTbiJob.setMaxMemory(memGetTbi); getTbiJob.addParent(startWorkflow); getTbiJob.addParent(controlBasJob); for(Job job : tumourBasJobs) { getTbiJob.addParent(job); } // these are not paired but per individual sample List<Job> ngsCountJobs = new ArrayList<Job>(); for(int i=1; i<=24; i++) { for(int j=0; j<tumourBams.size(); j++) { Job ngsCountJob = ngsCount(i, tumourBams.get(j), "tumour"+j, i); ngsCountJob.setMaxMemory(memPicnicCounts); ngsCountJob.addParent(getTbiJob); ngsCountJobs.add(ngsCountJob); } Job ngsCountJob = ngsCount(i, controlBam, "control", i); ngsCountJob.setMaxMemory(memPicnicCounts); ngsCountJob.addParent(getTbiJob); ngsCountJobs.add(ngsCountJob); } Job ngsCountMergeJob = ngsCountMerge(controlBam); ngsCountMergeJob.setMaxMemory(memPicnicMerge); for(Job j : ngsCountJobs) { ngsCountMergeJob.addParent(j); } List<Job> bbAlleleCountJobs = new ArrayList<Job>(); for(int i=0; i<23; i++) { // not 1-22+X for(int j=0; j<tumourBams.size(); j++) { Job bbAlleleCountJob = bbAlleleCount(i, tumourBams.get(j), "tumour"+j, i); bbAlleleCountJob.setMaxMemory(memAlleleCount); bbAlleleCountJob.addParent(getTbiJob); bbAlleleCountJobs.add(bbAlleleCountJob); } Job bbAlleleCountJob = bbAlleleCount(i, controlBam, "control", i); bbAlleleCountJob.setMaxMemory(memAlleleCount); bbAlleleCountJob.addParent(getTbiJob); bbAlleleCountJobs.add(bbAlleleCountJob); } Job bbAlleleMergeJob = bbAlleleMerge(controlBam); bbAlleleMergeJob.setMaxMemory(memBbMerge); for(Job j : bbAlleleCountJobs) { bbAlleleMergeJob.addParent(j); } Job[] cavemanFlagJobs = new Job [tumourBams.size()]; for(int i=0; i<tumourBams.size(); i++) { Job cavemanFlagJob = buildPairWorkflow(getTbiJob, controlBam, tumourBams.get(i), i); cavemanFlagJobs[i] = cavemanFlagJob; } Job cavemanTbiCleanJob = cavemanTbiCleanJob(); cavemanTbiCleanJob.setMaxMemory(memCavemanTbiClean); for(Job cavemanFlagJob : cavemanFlagJobs) { cavemanTbiCleanJob.addParent(cavemanFlagJob); } Job endWorkflow = markTime("end"); endWorkflow.setMaxMemory(memMarkTime); endWorkflow.addParent(cavemanTbiCleanJob); Job metricsJob = getMetricsJob(tumourBams); metricsJob.setMaxMemory(memQcMetrics); metricsJob.addParent(endWorkflow); Job renameImputeJob = renameSampleFile(tumourBams, OUTDIR, "imputeCounts.tar.gz"); renameImputeJob.setMaxMemory("3000"); renameImputeJob.addParent(bbAlleleMergeJob); Job renameCountsJob = renameSampleFile(tumourBams, OUTDIR, "binnedReadCounts.tar.gz"); renameCountsJob.setMaxMemory("3000"); renameCountsJob.addParent(ngsCountMergeJob); if(uploadServer != null) { String[] resultTypes = {"snv_mnv","cnv","sv","indel"}; Job uploadJob = vcfUpload(resultTypes, controlAnalysisId, tumourAnalysisIds, tumourAliquotIds); uploadJob.setMaxMemory(memUpload); uploadJob.addParent(metricsJob); uploadJob.addParent(renameImputeJob); uploadJob.addParent(ngsCountMergeJob); if (cleanup) { // if we upload to GNOS then go ahead and delete all the large files Job cleanJob = postUploadCleanJob(); cleanJob.addParent(uploadJob); } } else { // delete just the BAM inputs and not the output dir if (cleanup) { Job cleanInputsJob = cleanInputsJob(); cleanInputsJob.addParent(metricsJob); } } } /** * This builds the workflow for a pair of samples * The generic buildWorkflow section will choose the pair to be processed and * setup the control sample download */ private Job buildPairWorkflow(Job getTbiJob, String controlBam, String tumourBam, int tumourCount) { /** * ASCAT - Copynumber * Depends on * - tumour/control BAMs * - Gender, will attempt to determine if not specified */ Job[] alleleCountJobs = new Job[2]; for(int i=0; i<2; i++) { Job alleleCountJob = cgpAscatBaseJob(tumourCount, tumourBam, controlBam, "ASCAT", "allele_count", i+1); alleleCountJob.setMaxMemory(memAlleleCount); alleleCountJob.addParent(getTbiJob); alleleCountJobs[i] = alleleCountJob; } Job ascatJob = cgpAscatBaseJob(tumourCount, tumourBam, controlBam, "ASCAT", "ascat", 1); ascatJob.setMaxMemory(memAscat); ascatJob.addParent(alleleCountJobs[0]); ascatJob.addParent(alleleCountJobs[1]); Job ascatFinaliseJob = cgpAscatBaseJob(tumourCount, tumourBam, controlBam, "ASCAT", "finalise", 1); ascatFinaliseJob.setMaxMemory(memAscatFinalise); ascatFinaliseJob.addParent(ascatJob); Job ascatPackage = packageResults(tumourCount, "ascat", "cnv", tumourBam, "copynumber.caveman.vcf.gz", workflowName, "somatic", dateString); ascatPackage.setMaxMemory(memPackageResults); ascatPackage.addParent(ascatFinaliseJob); /** * CaVEMan setup is here to allow better workflow graph * Messy but necessary */ Job caveCnPrepJobs[] = new Job[2]; for(int i=0; i<2; i++) { Job caveCnPrepJob; if(i==0) { caveCnPrepJob = caveCnPrep(tumourCount, "tumour"); } else { caveCnPrepJob = caveCnPrep(tumourCount, "normal"); } caveCnPrepJob.addParent(getTbiJob); caveCnPrepJob.addParent(ascatFinaliseJob); // ASCAT dependency!!! caveCnPrepJobs[i] = caveCnPrepJob; } Job cavemanSetupJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "setup", 1); cavemanSetupJob.setMaxMemory(memCavemanSetup); cavemanSetupJob.addParent(caveCnPrepJobs[0]); cavemanSetupJob.addParent(caveCnPrepJobs[1]); // some dependencies handled by ascat step /** * Pindel - InDel calling * Depends on: * - tumour/control BAMs */ Job[] pindelInputJobs = new Job[2]; for(int i=0; i<2; i++) { Job inputParse = pindelBaseJob(tumourCount, tumourBam, controlBam, "cgpPindel", "input", i+1); inputParse.setMaxMemory(memPindelInput); inputParse.addParent(getTbiJob); pindelInputJobs[i] = inputParse; } // determine number of refs to process // we know that this is static for PanCancer so be lazy 24 jobs (1-22,X,Y) // but pindel needs to know the exclude list so hard code this Job pinVcfJobs[] = new Job[24]; for(int i=0; i<24; i++) { Job pindelJob = pindelBaseJob(tumourCount, tumourBam, controlBam, "cgpPindel", "pindel", i+1); pindelJob.setMaxMemory(memPindel); pindelJob.addParent(pindelInputJobs[0]); pindelJob.addParent(pindelInputJobs[1]); Job pinVcfJob = pindelBaseJob(tumourCount, tumourBam, controlBam, "cgpPindel", "pin2vcf", i+1); pinVcfJob.setMaxMemory(memPindelVcf); pinVcfJob.addParent(pindelJob); // pinVcf depends on pindelJob so only need have dependency on the pinVcf pinVcfJobs[i] = pinVcfJob; } Job pindelMergeJob = pindelBaseJob(tumourCount, tumourBam, controlBam, "cgpPindel", "merge", 1); pindelMergeJob.setMaxMemory(memPindelMerge); for (Job parent : pinVcfJobs) { pindelMergeJob.addParent(parent); } Job pindelFlagJob = pindelBaseJob(tumourCount, tumourBam, controlBam, "cgpPindel", "flag", 1); pindelFlagJob.setMaxMemory(memPindelFlag); pindelFlagJob.addParent(pindelMergeJob); pindelFlagJob.addParent(cavemanSetupJob); Job pindelPackage = packageResults(tumourCount, "pindel", "indel", tumourBam, "flagged.vcf.gz", workflowName, "somatic", dateString); pindelPackage.setMaxMemory(memPackageResults); pindelPackage.addParent(pindelFlagJob); /** * BRASS - BReakpoint AnalySiS * Depends on: * - tumour/control BAMs * - ASCAT output at filter step */ Job brassInputJobs[] = new Job[2]; for(int i=0; i<2; i++) { Job brassInputJob = brassBaseJob(tumourCount, tumourBam, controlBam, "BRASS", "input", i+1); brassInputJob.setMaxMemory(memBrassInput); brassInputJob.addParent(getTbiJob); brassInputJobs[i] = brassInputJob; } Job brassGroupJob = brassBaseJob(tumourCount, tumourBam, controlBam, "BRASS", "group", 1); brassGroupJob.setMaxMemory(memBrassGroup); brassGroupJob.addParent(brassInputJobs[0]); brassGroupJob.addParent(brassInputJobs[1]); Job brassFilterJob = brassBaseJob(tumourCount, tumourBam, controlBam, "BRASS", "filter", 1); brassFilterJob.setMaxMemory(memBrassFilter); brassFilterJob.addParent(brassGroupJob); brassFilterJob.addParent(ascatFinaliseJob); // NOTE: dependency on ASCAT!! Job brassSplitJob = brassBaseJob(tumourCount, tumourBam, controlBam, "BRASS", "split", 1); brassSplitJob.setMaxMemory(memBrassSplit); brassSplitJob.addParent(brassFilterJob); List<Job> brassAssembleJobs = new ArrayList<Job>(); for(int i=0; i<coresAddressable; i++) { Job brassAssembleJob = brassBaseJob(tumourCount, tumourBam, controlBam, "BRASS", "assemble", i+1); brassAssembleJob.setMaxMemory(memBrassAssemble); brassAssembleJob.addParent(brassSplitJob); brassAssembleJobs.add(brassAssembleJob); } Job brassGrassJob = brassBaseJob(tumourCount, tumourBam, controlBam, "BRASS", "grass", 1); brassGrassJob.setMaxMemory(memBrassGrass); for(Job brassAssembleJob : brassAssembleJobs) { brassGrassJob.addParent(brassAssembleJob); } Job brassTabixJob = brassBaseJob(tumourCount, tumourBam, controlBam, "BRASS", "tabix", 1); brassTabixJob.setMaxMemory(memBrassTabix); brassTabixJob.addParent(brassGrassJob); Job brassPackage = packageResults(tumourCount, "brass", "sv", tumourBam, "annot.vcf.gz", workflowName, "somatic", dateString); brassPackage.setMaxMemory(memPackageResults); brassPackage.addParent(brassTabixJob); /** * CaVEMan - SNV analysis * !! see above as setup done earlier to help with workflow structure !! * Depends on: * - tumour/control BAMs (but depend on BAS for better workflow) * - ASCAT from outset * - pindel at flag step */ // should really line count the fai file Job cavemanSplitJobs[] = new Job[86]; for(int i=0; i<86; i++) { Job cavemanSplitJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "split", i+1); cavemanSplitJob.setMaxMemory(memCavemanSplit); cavemanSplitJob.addParent(cavemanSetupJob); cavemanSplitJobs[i] = cavemanSplitJob; } Job cavemanSplitConcatJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "split_concat", 1); cavemanSplitConcatJob.setMaxMemory(memCavemanSplitConcat); for (Job cavemanSplitJob : cavemanSplitJobs) { cavemanSplitConcatJob.addParent(cavemanSplitJob); } List<Job> cavemanMstepJobs = new ArrayList<Job>(); for(int i=0; i<coresAddressable; i++) { Job cavemanMstepJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "mstep", i+1); cavemanMstepJob.setMaxMemory(memCavemanMstep); cavemanMstepJob.addParent(cavemanSplitConcatJob); cavemanMstepJobs.add(cavemanMstepJob); } Job cavemanMergeJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "merge", 1); cavemanMergeJob.setMaxMemory(memCavemanMerge); for(Job cavemanMstepJob : cavemanMstepJobs) { cavemanMergeJob.addParent(cavemanMstepJob); } List<Job> cavemanEstepJobs = new ArrayList<Job>(); for(int i=0; i<coresAddressable; i++) { Job cavemanEstepJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "estep", i+1); cavemanEstepJob.setMaxMemory(memCavemanEstep); cavemanEstepJob.addParent(cavemanMergeJob); cavemanEstepJobs.add(cavemanEstepJob); } Job cavemanMergeResultsJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "merge_results", 1); cavemanMergeResultsJob.setMaxMemory(memCavemanMergeResults); for(Job cavemanEstepJob : cavemanEstepJobs) { cavemanMergeResultsJob.addParent(cavemanEstepJob); } Job cavemanAddIdsJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "add_ids", 1); cavemanAddIdsJob.setMaxMemory(memCavemanAddIds); cavemanAddIdsJob.addParent(cavemanMergeResultsJob); Job cavemanFlagJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "flag", 1); cavemanFlagJob.setMaxMemory(memCavemanFlag); cavemanFlagJob.addParent(getTbiJob); cavemanFlagJob.addParent(pindelFlagJob); // PINDEL dependency cavemanFlagJob.addParent(cavemanAddIdsJob); Job cavemanPackage = packageResults(tumourCount, "caveman", "snv_mnv", tumourBam, "flagged.muts.vcf.gz", workflowName, "somatic", dateString); cavemanPackage.setMaxMemory(memPackageResults); cavemanPackage.addParent(cavemanFlagJob); return cavemanFlagJob; } private Job prepareTestData(String sample) { Job thisJob = getWorkflow().createBashJob("prepTest"); thisJob.getCommand() .addArgument(getWorkflowBaseDir()+ "/bin/wrapper.sh") .addArgument(installBase) // the cram file is missing the sample name for some reason // this fixes it temporarily // regen the header first .addArgument("scramble -I cram -O bam") .addArgument("-r " + testBase + "/genome.fa") .addArgument(testBase + "/" + sample + ".cram") .addArgument("samtools view -H - |") .addArgument("perl -ane 'if($_ =~ m/^\\@RG/) {chomp $_; $_ .= q{\\tSM:HCC1147\\n};} print $_;'") .addArgument(OUTDIR + "/" + sample + "_head.sam") // then send all data through samtools reheader .addArgument("; scramble -I cram -O bam") .addArgument("-r " + testBase + "/genome.fa") .addArgument("-t 2") // threads .addArgument("-m") // generate MD/NM .addArgument(testBase + "/" + sample + ".cram") .addArgument("samtools reheader "+ OUTDIR + "/" + sample + "_head.sam -") .addArgument("> " + OUTDIR + "/" + sample + ".bam") .addArgument("; cp " + testBase + "/" + sample + ".bam.bas") .addArgument(OUTDIR + "/.") .addArgument("; samtools index " + OUTDIR + "/" + sample + ".bam") ; return thisJob; } private Job ngsCountMerge(String controlBam) { Job thisJob = prepTimedJob(0, "binCount", "merge", 0); thisJob.getCommand() .addArgument(getWorkflowBaseDir()+ "/bin/wrapper.sh") .addArgument(installBase) .addArgument("ngs_bin_allele_merge.pl") .addArgument(controlBam) .addArgument(COUNTDIR) ; return thisJob; } private Job ngsCount(int sampleIndex, String bam, String process, int index) { String chr = Integer.toString(index+1); if(index+1 == 23) { chr = "X"; } else if(index+1 == 24) { chr = "Y"; } Job thisJob = prepTimedJob(sampleIndex, "binCounts", process, index); thisJob.getCommand() .addArgument(getWorkflowBaseDir()+ "/bin/wrapper.sh") .addArgument(installBase) .addArgument("ngs_bin_allele.pl") .addArgument(refBase + "/picnic/cn_bins.csv.gz") .addArgument(refBase + "/picnic/snp6.csv.gz") .addArgument(COUNTDIR) .addArgument(bam) .addArgument(chr) ; return thisJob; } private Job bbAlleleCount(int sampleIndex, String bam, String process, int index) { Job thisJob = prepTimedJob(sampleIndex, "bbAllele", process, index); int chr = index+1; thisJob.getCommand() .addArgument(getWorkflowBaseDir()+ "/bin/wrapper.sh") .addArgument(installBase) .addArgument(getWorkflowBaseDir()+ "/bin/execute_with_sample.pl " + bam) .addArgument("alleleCounter") .addArgument("-l " + refBase + "/battenberg/1000genomesloci/1000genomesloci2012_chr" + chr + ".txt") .addArgument("-o " + BBDIR + "/%SM%." + chr + ".tsv") .addArgument("-b " + bam) ; return thisJob; } private Job bbAlleleMerge(String controlBam) { Job thisJob = prepTimedJob(0, "bbAllele", "merge", 0); thisJob.getCommand() .addArgument(getWorkflowBaseDir()+ "/bin/wrapper.sh") .addArgument(installBase) .addArgument(getWorkflowBaseDir()+ "/bin/packageImpute.pl") .addArgument(controlBam) .addArgument(BBDIR) ; return thisJob; } private Job renameSampleFile(List<String> bams, String dir, String extension) { Job thisJob = getWorkflow().createBashJob("renameSampleFile"); for(String bam : bams) { thisJob.getCommand() .addArgument(getWorkflowBaseDir()+ "/bin/wrapper.sh") .addArgument(installBase) .addArgument(getWorkflowBaseDir()+ "/bin/execute_with_sample.pl " + bam) .addArgument(dir + "/" + "%SM%." + extension) .addArgument(OUTDIR + "/" + "%SM%." + workflowName + "." + dateString + ".somatic." + extension) .addArgument(";") ; } return thisJob; } private Job vcfUpload(String[] types, String controlAnalysisId, List<String> tumourAnalysisIds, List<String> tumourAliquotIds) { Job thisJob = getWorkflow().createBashJob("vcfUpload"); String metadataUrls = new String(); metadataUrls = metadataUrls.concat(gnosServer) .concat("/cghub/metadata/analysisFull/") .concat(controlAnalysisId); for(String tumourAnalysisId : tumourAnalysisIds) { metadataUrls = metadataUrls.concat(",") .concat(gnosServer) .concat("/cghub/metadata/analysisFull/") .concat(tumourAnalysisId); } String vcfs = new String(); String tbis = new String(); String tars = new String(); String vcfmd5s = new String(); String tbimd5s = new String(); String tarmd5s = new String(); for(String type: types) { for(String tumourAliquotId : tumourAliquotIds) { // TODO: Hardcoded somatic here, is that correct? String baseFile = OUTDIR + "/" + tumourAliquotId + "." + workflowName + "." + dateString + ".somatic." + type; if(vcfs.length() > 0) { vcfs = vcfs.concat(","); tbis = tbis.concat(","); tars = tars.concat(","); vcfmd5s = vcfmd5s.concat(","); tbimd5s = tbimd5s.concat(","); tarmd5s = tarmd5s.concat(","); } vcfs = vcfs.concat(baseFile + ".vcf.gz"); tbis = tbis.concat(baseFile + ".vcf.gz.tbi"); tars = tars.concat(baseFile + ".tar.gz"); vcfmd5s = vcfmd5s.concat(baseFile + ".vcf.gz.md5"); tbimd5s = tbimd5s.concat(baseFile + ".vcf.gz.tbi.md5"); tarmd5s = tarmd5s.concat(baseFile + ".tar.gz.md5"); } } // specific to CGP data for(String tumourAliquotId : tumourAliquotIds) { String baseFile = OUTDIR + "/" + tumourAliquotId + "." + workflowName + "." + dateString + ".somatic."; tars = tars.concat("," + baseFile + "imputeCounts.tar.gz"); tars = tars.concat("," + baseFile + "binnedReadCounts.tar.gz"); tarmd5s = tarmd5s.concat("," + baseFile + "imputeCounts.tar.gz.md5"); tarmd5s = tarmd5s.concat("," + baseFile + "binnedReadCounts.tar.gz.md5"); } thisJob.getCommand() .addArgument("perl " + getWorkflowBaseDir()+ "/bin/gnos_upload_vcf.pl") .addArgument("--metadata-urls " + metadataUrls) .addArgument("--vcfs " + vcfs) .addArgument("--vcf-md5sum-files " + vcfmd5s) .addArgument("--vcf-idxs " + tbis) .addArgument("--vcf-idx-md5sum-files " + tbimd5s) .addArgument("--tarballs " + tars) .addArgument("--tarball-md5sum-files " + tarmd5s) .addArgument("--outdir " + OUTDIR + "/upload") .addArgument("--key " + pemFile) .addArgument("--upload-url " + uploadServer) .addArgument("--qc-metrics-json " + OUTDIR + "/qc_metrics.json") .addArgument("--timing-metrics-json " + OUTDIR + "/process_metrics.json") ; try { if(hasPropertyAndNotNull("study-refname-override")) { thisJob.getCommand().addArgument("--study-refname-override " + getProperty("study-refname-override")); } if(hasPropertyAndNotNull("analysis-center-override")) { thisJob.getCommand().addArgument("--analysis-center-override " + getProperty("analysis-center-override")); } if(hasPropertyAndNotNull("upload-test") && Boolean.valueOf(getProperty("upload-test"))) { thisJob.getCommand().addArgument("--test "); } if(hasPropertyAndNotNull("upload-skip")) { thisJob.getCommand().addArgument("--skip-upload"); } } catch (Exception e) { throw new RuntimeException(e); } return thisJob; } private Job packageResults(int tumourCount, String algName, String resultType, String tumourBam, String baseVcf, String workflowName, String somaticOrGermline, String date) { //#packageResults.pl outdir 0772aed3-4df7-403f-802a-808df2935cd1/c007f362d965b32174ec030825262714.bam outdir/caveman snv_mnv flagged.muts.vcf.gz Job thisJob = getWorkflow().createBashJob("packageResults"); thisJob.getCommand() .addArgument(getWorkflowBaseDir()+ "/bin/wrapper.sh") .addArgument(installBase) .addArgument(getWorkflowBaseDir() + "/bin/packageResults.pl") .addArgument(OUTDIR) .addArgument(tumourBam) .addArgument(OUTDIR + "/" + tumourCount + "/" + algName) .addArgument(resultType) .addArgument(baseVcf) .addArgument(workflowName) .addArgument(somaticOrGermline) .addArgument(date) ; return thisJob; } private Job gnosDownloadBaseJob(String analysisId) { Job thisJob = getWorkflow().createBashJob("GNOSDownload"); thisJob.getCommand() .addArgument("gtdownload -c " + pemFile) .addArgument("-v " + gnosServer + "/cghub/data/analysis/download/" + analysisId); return thisJob; } private Job basFileBaseJob(String analysisId, String sampleBam) { Job thisJob = getWorkflow().createBashJob("basFileGet"); thisJob.getCommand() .addArgument(getWorkflowBaseDir()+ "/bin/wrapper.sh") .addArgument(installBase) .addArgument("xml_to_bas.pl") .addArgument("-d " + gnosServer + "/cghub/metadata/analysisFull/" + analysisId) .addArgument("-o " + analysisId + "/" + sampleBam + ".bas") ; return thisJob; } private Job getMetricsJob(List<String> tumourBams) { //die "USAGE: rootOfOutdir ordered.bam [ordered.bam2]"; Job thisJob = getWorkflow().createBashJob("metrics"); thisJob.getCommand() .addArgument(getWorkflowBaseDir()+ "/bin/wrapper.sh") .addArgument(installBase) .addArgument(getWorkflowBaseDir()+ "/bin/qc_and_metrics.pl") .addArgument(OUTDIR); for(String bam : tumourBams) { thisJob.getCommand().addArgument(bam); } return thisJob; } private Job caveCnPrep(int tumourCount, String type) { thisJob.getCommand().addArgument("rm -rf ./*/*.bam " + OUTDIR); thisJob.getCommand().addArgument("rm -f ./*/*.bam");
package io.seqware.pancancer; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.List; import java.util.Map; import net.sourceforge.seqware.pipeline.workflowV2.AbstractWorkflowDataModel; import net.sourceforge.seqware.pipeline.workflowV2.model.Job; import net.sourceforge.seqware.pipeline.workflowV2.model.SqwFile; import org.apache.commons.lang.StringUtils; public class CgpCnIndelSnvStrWorkflow extends AbstractWorkflowDataModel { private static String OUTDIR = "outdir"; private static String TIMEDIR; private static String COUNTDIR; private static String BBDIR; private boolean testMode=false; private boolean cleanup = false; // datetime all upload files will be named with DateFormat df = new SimpleDateFormat("yyyyMMdd"); String dateString = df.format(Calendar.getInstance().getTime()); private String workflowName = "svcp_1-0-0"; // MEMORY variables // private String memBasFileGet, memGnosDownload, memPackageResults, memMarkTime, memQcMetrics, memUpload, memGetTbi, memPicnicCounts, memPicnicMerge, memUnpack, memBbMerge, // ascat memory memAlleleCount, memAscat, memAscatFinalise, // pindel memory memPindelInput, memPindel, memPindelVcf, memPindelMerge , memPindelFlag, // brass memory memBrassInput, memBrassGroup, memBrassFilter, memBrassSplit, memBrassAssemble, memBrassGrass, memBrassTabix, // caveman memory memCaveCnPrep, memCavemanSetup, memCavemanSplit, memCavemanSplitConcat, memCavemanMstep, memCavemanMerge, memCavemanEstep, memCavemanMergeResults, memCavemanAddIds, memCavemanFlag, memCavemanTbiClean ; // workflow variables private String // reference variables species, assembly, // sequencing type/protocol seqType, seqProtocol, //GNOS identifiers pemFile, gnosServer, uploadServer, // ascat variables gender, // pindel variables refExclude, pindelGermline, //caveman variables tabixSrvUri, //general variables installBase, refBase, genomeFaGz; private int coresAddressable; private void init() { try { //optional properties String outDir = OUTDIR; String outPrefix = ""; if (hasPropertyAndNotNull("output_dir")) { outDir = getProperty("output_dir"); } if (hasPropertyAndNotNull("output_prefix")) { outPrefix = getProperty("output_prefix"); } if (!"".equals(outPrefix)) { if (outPrefix.endsWith("/")) { OUTDIR = outPrefix+outDir; } else { OUTDIR = outPrefix + "/" + outDir; } } } catch (Exception e) { throw new RuntimeException(e); } TIMEDIR = OUTDIR + "/timings"; COUNTDIR = OUTDIR + "/ngsCounts"; BBDIR = OUTDIR + "/bbCounts"; } @Override public void setupDirectory() { //since setupDirectory is the first method run, we use it to initialize variables too. init(); // creates a dir1 directory in the current working directory where the workflow runs addDirectory(OUTDIR); addDirectory(TIMEDIR); addDirectory(COUNTDIR); addDirectory(BBDIR); } @Override public Map<String, SqwFile> setupFiles() { try { if(hasPropertyAndNotNull("cleanup")) { cleanup = Boolean.valueOf(getProperty("cleanup")); } if(hasPropertyAndNotNull("testMode")) { testMode=Boolean.valueOf(getProperty("testMode")); System.err.println("WARNING\n\tRunning in test mode, direct access BAM files will be used, change 'testMode' in ini file to disable\n"); } if(hasPropertyAndNotNull("uploadServer")) { uploadServer = getProperty("uploadServer"); } else { System.err.println("WARNING\n\t'uploadServer' not defined in workflow.ini, no VCF upload will be attempted\n"); } // used by steps that can use all available cores coresAddressable = Integer.valueOf(getProperty("coresAddressable")); // MEMORY // memBasFileGet = getProperty("memBasFileGet"); memGnosDownload = getProperty("memGnosDownload"); memPackageResults = getProperty("memPackageResults"); memMarkTime = getProperty("memMarkTime"); memQcMetrics = getProperty("memQcMetrics"); memUpload = getProperty("memUpload"); memGetTbi = getProperty("memGetTbi"); memPicnicCounts = getProperty("memPicnicCounts"); memPicnicMerge = getProperty("memPicnicMerge"); memUnpack = getProperty("memUnpack"); memBbMerge = getProperty("memBbMerge"); memAlleleCount = getProperty("memAlleleCount"); memAscat = getProperty("memAscat"); memAscatFinalise = getProperty("memAscatFinalise"); memPindelInput = getProperty("memPindelInput"); memPindel = getProperty("memPindel"); memPindelVcf = getProperty("memPindelVcf"); memPindelMerge = getProperty("memPindelMerge"); memPindelFlag = getProperty("memPindelFlag"); memBrassInput = getProperty("memBrassInput"); memBrassGroup = getProperty("memBrassGroup"); memBrassFilter = getProperty("memBrassFilter"); memBrassSplit = getProperty("memBrassSplit"); memBrassAssemble = getProperty("memBrassAssemble"); memBrassGrass = getProperty("memBrassGrass"); memBrassTabix = getProperty("memBrassTabix"); memCaveCnPrep = getProperty("memCaveCnPrep"); memCavemanSetup = getProperty("memCavemanSetup"); memCavemanSplit = getProperty("memCavemanSplit"); memCavemanSplitConcat = getProperty("memCavemanSplitConcat"); memCavemanMstep = getProperty("memCavemanMstep"); memCavemanMerge = getProperty("memCavemanMerge"); memCavemanEstep = getProperty("memCavemanEstep"); memCavemanMergeResults = getProperty("memCavemanMergeResults"); memCavemanAddIds = getProperty("memCavemanAddIds"); memCavemanFlag = getProperty("memCavemanFlag"); memCavemanTbiClean = getProperty("memCavemanTbiClean"); // REFERENCE INFO // species = getProperty("species"); assembly = getProperty("assembly"); // Sequencing info seqType = getProperty("seqType"); if(seqType.equals("WGS")) { seqProtocol = "genomic"; } // Specific to ASCAT workflow // gender = getProperty("gender"); // Specific to Caveman workflow // tabixSrvUri = getProperty("tabixSrvUri"); // pindel specific refExclude = getProperty("refExclude"); // used for upload too so always get it if(hasPropertyAndNotNull("gnosServer")) { gnosServer = getProperty("gnosServer"); } // test mode if(!testMode || (hasPropertyAndNotNull("upload-test") && Boolean.valueOf(getProperty("upload-test")))) { pemFile = getProperty("pemFile"); } //environment installBase = getWorkflowBaseDir() + "/bin/opt"; refBase = getWorkflowBaseDir() + "/data/reference/cgp_reference"; genomeFaGz = getWorkflowBaseDir() + "/data/reference/genome.fa.gz"; } catch (Exception ex) { throw new RuntimeException(ex); } return getFiles(); } private Job bamProvision(String analysisId, String bamFile, Job startTiming) { Job basJob = null; if(testMode == false) { Job gnosDownload = gnosDownloadBaseJob(analysisId); gnosDownload.setMaxMemory(memGnosDownload); gnosDownload.addParent(startTiming); // the file needs to end up in tumourBam/controlBam // get the BAS files basJob = basFileBaseJob(analysisId, bamFile); basJob.setMaxMemory(memBasFileGet); basJob.addParent(gnosDownload); } return basJob; } @Override public void buildWorkflow() { Job controlBasJob = null; String controlBam; List<String> tumourBams = new ArrayList<String>(); List<Job> tumourBasJobs = new ArrayList<Job>(); List<String> tumourAnalysisIds = new ArrayList<String>(); List<String> tumourAliquotIds = new ArrayList<String>(); String controlAnalysisId = new String(); Job startWorkflow = markTime("start"); startWorkflow.setMaxMemory(memMarkTime); try { if(testMode) { controlBam = getProperty("controlBamT"); tumourBams = Arrays.asList(getProperty("tumourBamT").split(":")); // only do this if test mode but upload is enabled, we're cheating a bit here but need the values defined with something to do the test upload controlAnalysisId = getProperty("controlAnalysisId"); tumourAnalysisIds = Arrays.asList(getProperty("tumourAnalysisIds").split(":")); tumourAliquotIds = Arrays.asList(getProperty("tumourAliquotIds").split(":")); } else { controlAnalysisId = getProperty("controlAnalysisId"); controlBasJob = bamProvision(controlAnalysisId, getProperty("controlBam"), startWorkflow); controlBam = controlAnalysisId + "/" + getProperty("controlBam"); tumourAnalysisIds = Arrays.asList(getProperty("tumourAnalysisIds").split(":")); tumourAliquotIds = Arrays.asList(getProperty("tumourAliquotIds").split(":")); List<String> rawBams = Arrays.asList(getProperty("tumourBams").split(":")); if(rawBams.size() != tumourAnalysisIds.size()) { throw new RuntimeException("Properties tumourAnalysisId and tumourBam decode to lists of different sizes"); } if(rawBams.size() != tumourAliquotIds.size()) { throw new RuntimeException("Properties tumourAliquotIds and tumourBam decode to lists of different sizes"); } for(int i=0; i<rawBams.size(); i++) { Job tumourBasJob = bamProvision(tumourAnalysisIds.get(i), rawBams.get(i), startWorkflow); tumourBasJobs.add(tumourBasJob); String tumourBam = tumourAnalysisIds.get(i) + "/" + rawBams.get(i); tumourBams.add(tumourBam); } } } catch(Exception e) { throw new RuntimeException(e); } Job getTbiJob = stageTbi(); getTbiJob.setMaxMemory(memGetTbi); getTbiJob.addParent(startWorkflow); if(controlBasJob != null) { getTbiJob.addParent(controlBasJob); for(Job job : tumourBasJobs) { getTbiJob.addParent(job); } } // these are not paired but per individual sample List<Job> ngsCountJobs = new ArrayList<Job>(); for(int i=1; i<=24; i++) { for(int j=0; j<tumourBams.size(); j++) { Job ngsCountJob = ngsCount(i, tumourBams.get(j), "tumour"+j, i); ngsCountJob.setMaxMemory(memPicnicCounts); ngsCountJob.addParent(getTbiJob); ngsCountJobs.add(ngsCountJob); } Job ngsCountJob = ngsCount(i, controlBam, "control", i); ngsCountJob.setMaxMemory(memPicnicCounts); ngsCountJob.addParent(getTbiJob); ngsCountJobs.add(ngsCountJob); } Job ngsCountMergeJob = ngsCountMerge(controlBam); ngsCountMergeJob.setMaxMemory(memPicnicMerge); for(Job j : ngsCountJobs) { ngsCountMergeJob.addParent(j); } List<Job> bbAlleleCountJobs = new ArrayList<Job>(); for(int i=0; i<23; i++) { // not 1-22+X for(int j=0; j<tumourBams.size(); j++) { Job bbAlleleCountJob = bbAlleleCount(i, tumourBams.get(j), "tumour"+j, i); bbAlleleCountJob.setMaxMemory(memAlleleCount); bbAlleleCountJob.addParent(getTbiJob); bbAlleleCountJobs.add(bbAlleleCountJob); } Job bbAlleleCountJob = bbAlleleCount(i, controlBam, "control", i); bbAlleleCountJob.setMaxMemory(memAlleleCount); bbAlleleCountJob.addParent(getTbiJob); bbAlleleCountJobs.add(bbAlleleCountJob); } Job bbAlleleMergeJob = bbAlleleMerge(controlBam); bbAlleleMergeJob.setMaxMemory(memBbMerge); for(Job j : bbAlleleCountJobs) { bbAlleleMergeJob.addParent(j); } Job[] cavemanFlagJobs = new Job [tumourBams.size()]; for(int i=0; i<tumourBams.size(); i++) { Job cavemanFlagJob = buildPairWorkflow(getTbiJob, controlBam, tumourBams.get(i), i); cavemanFlagJobs[i] = cavemanFlagJob; } Job cavemanTbiCleanJob = cavemanTbiCleanJob(); cavemanTbiCleanJob.setMaxMemory(memCavemanTbiClean); for(Job cavemanFlagJob : cavemanFlagJobs) { cavemanTbiCleanJob.addParent(cavemanFlagJob); } Job endWorkflow = markTime("end"); endWorkflow.setMaxMemory(memMarkTime); endWorkflow.addParent(cavemanTbiCleanJob); Job metricsJob = getMetricsJob(tumourBams); metricsJob.setMaxMemory(memQcMetrics); metricsJob.addParent(endWorkflow); if(uploadServer != null) { String[] resultTypes = {"snv_mnv","cnv","sv","indel"}; Job uploadJob = vcfUpload(resultTypes, controlAnalysisId, tumourAnalysisIds, tumourAliquotIds); uploadJob.setMaxMemory(memUpload); uploadJob.addParent(metricsJob); if (cleanup) { // if we upload to GNOS then go ahead and delete all the large files Job cleanJob = postUploadCleanJob(); cleanJob.addParent(uploadJob); } } else { // delete just the BAM inputs and not the output dir if (cleanup) { Job cleanInputsJob = cleanInputsJob(); cleanInputsJob.addParent(metricsJob); } } } /** * This builds the workflow for a pair of samples * The generic buildWorkflow section will choose the pair to be processed and * setup the control sample download */ private Job buildPairWorkflow(Job getTbiJob, String controlBam, String tumourBam, int tumourCount) { /** * ASCAT - Copynumber * Depends on * - tumour/control BAMs * - Gender, will attempt to determine if not specified */ Job[] alleleCountJobs = new Job[2]; for(int i=0; i<2; i++) { Job alleleCountJob = cgpAscatBaseJob(tumourCount, tumourBam, controlBam, "ASCAT", "allele_count", i+1); alleleCountJob.setMaxMemory(memAlleleCount); alleleCountJob.addParent(getTbiJob); alleleCountJobs[i] = alleleCountJob; } Job ascatJob = cgpAscatBaseJob(tumourCount, tumourBam, controlBam, "ASCAT", "ascat", 1); ascatJob.setMaxMemory(memAscat); ascatJob.addParent(alleleCountJobs[0]); ascatJob.addParent(alleleCountJobs[1]); Job ascatFinaliseJob = cgpAscatBaseJob(tumourCount, tumourBam, controlBam, "ASCAT", "finalise", 1); ascatFinaliseJob.setMaxMemory(memAscatFinalise); ascatFinaliseJob.addParent(ascatJob); Job ascatPackage = packageResults(tumourCount, "ascat", "cnv", tumourBam, "copynumber.caveman.vcf.gz", workflowName, "somatic", dateString); ascatPackage.setMaxMemory(memPackageResults); ascatPackage.addParent(ascatFinaliseJob); /** * CaVEMan setup is here to allow better workflow graph * Messy but necessary */ Job caveCnPrepJobs[] = new Job[2]; for(int i=0; i<2; i++) { Job caveCnPrepJob; if(i==0) { caveCnPrepJob = caveCnPrep(tumourCount, "tumour"); } else { caveCnPrepJob = caveCnPrep(tumourCount, "normal"); } caveCnPrepJob.addParent(getTbiJob); caveCnPrepJob.addParent(ascatFinaliseJob); // ASCAT dependency!!! caveCnPrepJobs[i] = caveCnPrepJob; } Job cavemanSetupJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "setup", 1); cavemanSetupJob.setMaxMemory(memCavemanSetup); cavemanSetupJob.addParent(caveCnPrepJobs[0]); cavemanSetupJob.addParent(caveCnPrepJobs[1]); // some dependencies handled by ascat step /** * Pindel - InDel calling * Depends on: * - tumour/control BAMs */ Job[] pindelInputJobs = new Job[2]; for(int i=0; i<2; i++) { Job inputParse = pindelBaseJob(tumourCount, tumourBam, controlBam, "cgpPindel", "input", i+1); inputParse.setMaxMemory(memPindelInput); inputParse.addParent(getTbiJob); pindelInputJobs[i] = inputParse; } // determine number of refs to process // we know that this is static for PanCancer so be lazy 24 jobs (1-22,X,Y) // but pindel needs to know the exclude list so hard code this Job pinVcfJobs[] = new Job[24]; for(int i=0; i<24; i++) { Job pindelJob = pindelBaseJob(tumourCount, tumourBam, controlBam, "cgpPindel", "pindel", i+1); pindelJob.setMaxMemory(memPindel); pindelJob.addParent(pindelInputJobs[0]); pindelJob.addParent(pindelInputJobs[1]); Job pinVcfJob = pindelBaseJob(tumourCount, tumourBam, controlBam, "cgpPindel", "pin2vcf", i+1); pinVcfJob.setMaxMemory(memPindelVcf); pinVcfJob.addParent(pindelJob); // pinVcf depends on pindelJob so only need have dependency on the pinVcf pinVcfJobs[i] = pinVcfJob; } Job pindelMergeJob = pindelBaseJob(tumourCount, tumourBam, controlBam, "cgpPindel", "merge", 1); pindelMergeJob.setMaxMemory(memPindelMerge); for (Job parent : pinVcfJobs) { pindelMergeJob.addParent(parent); } Job pindelFlagJob = pindelBaseJob(tumourCount, tumourBam, controlBam, "cgpPindel", "flag", 1); pindelFlagJob.setMaxMemory(memPindelFlag); pindelFlagJob.addParent(pindelMergeJob); pindelFlagJob.addParent(cavemanSetupJob); Job pindelPackage = packageResults(tumourCount, "pindel", "indel", tumourBam, "flagged.vcf.gz", workflowName, "somatic", dateString); pindelPackage.setMaxMemory(memPackageResults); pindelPackage.addParent(pindelFlagJob); /** * BRASS - BReakpoint AnalySiS * Depends on: * - tumour/control BAMs * - ASCAT output at filter step */ Job brassInputJobs[] = new Job[2]; for(int i=0; i<2; i++) { Job brassInputJob = brassBaseJob(tumourCount, tumourBam, controlBam, "BRASS", "input", i+1); brassInputJob.setMaxMemory(memBrassInput); brassInputJob.addParent(getTbiJob); brassInputJobs[i] = brassInputJob; } Job brassGroupJob = brassBaseJob(tumourCount, tumourBam, controlBam, "BRASS", "group", 1); brassGroupJob.setMaxMemory(memBrassGroup); brassGroupJob.addParent(brassInputJobs[0]); brassGroupJob.addParent(brassInputJobs[1]); Job brassFilterJob = brassBaseJob(tumourCount, tumourBam, controlBam, "BRASS", "filter", 1); brassFilterJob.setMaxMemory(memBrassFilter); brassFilterJob.addParent(brassGroupJob); brassFilterJob.addParent(ascatFinaliseJob); // NOTE: dependency on ASCAT!! Job brassSplitJob = brassBaseJob(tumourCount, tumourBam, controlBam, "BRASS", "split", 1); brassSplitJob.setMaxMemory(memBrassSplit); brassSplitJob.addParent(brassFilterJob); List<Job> brassAssembleJobs = new ArrayList<Job>(); for(int i=0; i<coresAddressable; i++) { Job brassAssembleJob = brassBaseJob(tumourCount, tumourBam, controlBam, "BRASS", "assemble", i+1); brassAssembleJob.setMaxMemory(memBrassAssemble); brassAssembleJob.addParent(brassSplitJob); brassAssembleJobs.add(brassAssembleJob); } Job brassGrassJob = brassBaseJob(tumourCount, tumourBam, controlBam, "BRASS", "grass", 1); brassGrassJob.setMaxMemory(memBrassGrass); for(Job brassAssembleJob : brassAssembleJobs) { brassGrassJob.addParent(brassAssembleJob); } Job brassTabixJob = brassBaseJob(tumourCount, tumourBam, controlBam, "BRASS", "tabix", 1); brassTabixJob.setMaxMemory(memBrassTabix); brassTabixJob.addParent(brassGrassJob); Job brassPackage = packageResults(tumourCount, "brass", "sv", tumourBam, "annot.vcf.gz", workflowName, "somatic", dateString); brassPackage.setMaxMemory(memPackageResults); brassPackage.addParent(brassTabixJob); /** * CaVEMan - SNV analysis * !! see above as setup done earlier to help with workflow structure !! * Depends on: * - tumour/control BAMs (but depend on BAS for better workflow) * - ASCAT from outset * - pindel at flag step */ // should really line count the fai file Job cavemanSplitJobs[] = new Job[86]; for(int i=0; i<86; i++) { Job cavemanSplitJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "split", i+1); cavemanSplitJob.setMaxMemory(memCavemanSplit); cavemanSplitJob.addParent(cavemanSetupJob); cavemanSplitJobs[i] = cavemanSplitJob; } Job cavemanSplitConcatJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "split_concat", 1); cavemanSplitConcatJob.setMaxMemory(memCavemanSplitConcat); for (Job cavemanSplitJob : cavemanSplitJobs) { cavemanSplitConcatJob.addParent(cavemanSplitJob); } List<Job> cavemanMstepJobs = new ArrayList<Job>(); for(int i=0; i<coresAddressable; i++) { Job cavemanMstepJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "mstep", i+1); cavemanMstepJob.setMaxMemory(memCavemanMstep); cavemanMstepJob.addParent(cavemanSplitConcatJob); cavemanMstepJobs.add(cavemanMstepJob); } Job cavemanMergeJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "merge", 1); cavemanMergeJob.setMaxMemory(memCavemanMerge); for(Job cavemanMstepJob : cavemanMstepJobs) { cavemanMergeJob.addParent(cavemanMstepJob); } List<Job> cavemanEstepJobs = new ArrayList<Job>(); for(int i=0; i<coresAddressable; i++) { Job cavemanEstepJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "estep", i+1); cavemanEstepJob.setMaxMemory(memCavemanEstep); cavemanEstepJob.addParent(cavemanMergeJob); cavemanEstepJobs.add(cavemanEstepJob); } Job cavemanMergeResultsJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "merge_results", 1); cavemanMergeResultsJob.setMaxMemory(memCavemanMergeResults); for(Job cavemanEstepJob : cavemanEstepJobs) { cavemanMergeResultsJob.addParent(cavemanEstepJob); } Job cavemanAddIdsJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "add_ids", 1); cavemanAddIdsJob.setMaxMemory(memCavemanAddIds); cavemanAddIdsJob.addParent(cavemanMergeResultsJob); Job cavemanFlagJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "flag", 1); cavemanFlagJob.setMaxMemory(memCavemanFlag); cavemanFlagJob.addParent(getTbiJob); cavemanFlagJob.addParent(pindelFlagJob); // PINDEL dependency cavemanFlagJob.addParent(cavemanAddIdsJob); Job cavemanPackage = packageResults(tumourCount, "caveman", "snv_mnv", tumourBam, "flagged.muts.vcf.gz", workflowName, "somatic", dateString); cavemanPackage.setMaxMemory(memPackageResults); cavemanPackage.addParent(cavemanFlagJob); return cavemanFlagJob; } private Job ngsCountMerge(String controlBam) { Job thisJob = prepTimedJob(0, "binCount", "merge", 0); thisJob.getCommand() .addArgument(getWorkflowBaseDir()+ "/bin/wrapper.sh") .addArgument(installBase) .addArgument("ngs_bin_allele_merge.pl") .addArgument(controlBam) .addArgument(COUNTDIR) ; return thisJob; } private Job ngsCount(int sampleIndex, String bam, String process, int index) { String chr = Integer.toString(index+1); if(index+1 == 23) { chr = "X"; } else if(index+1 == 24) { chr = "Y"; } Job thisJob = prepTimedJob(sampleIndex, "binCounts", process, index); thisJob.getCommand() .addArgument(getWorkflowBaseDir()+ "/bin/wrapper.sh") .addArgument(installBase) .addArgument("ngs_bin_allele.pl") .addArgument(refBase + "/picnic/cn_bins.csv.gz") .addArgument(refBase + "/picnic/snp6.csv.gz") .addArgument(COUNTDIR) .addArgument(bam) .addArgument(chr) ; return thisJob; } private Job bbAlleleCount(int sampleIndex, String bam, String process, int index) { Job thisJob = prepTimedJob(sampleIndex, "bbAllele", process, index-1); thisJob.getCommand() .addArgument(getWorkflowBaseDir()+ "/bin/wrapper.sh") .addArgument(installBase) .addArgument(getWorkflowBaseDir()+ "/bin/execute_with_sample.pl " + bam) .addArgument(installBase) .addArgument("alleleCounter") .addArgument("-l " + refBase + "/battenberg/1000genomesloci/1000genomesloci2012_chr" + index + ".txt") .addArgument("-o " + BBDIR + "/%SM%." + index + ".tsv") .addArgument("-b " + bam) ; return thisJob; } private Job bbAlleleMerge(String controlBam) { Job thisJob = prepTimedJob(0, "bbAllele", "merge", 0); thisJob.getCommand() .addArgument(getWorkflowBaseDir()+ "/bin/wrapper.sh") .addArgument(installBase) .addArgument("packageImpute.pl") .addArgument(controlBam) .addArgument(BBDIR) .addArgument(";rm -f " + BBDIR + "/1000genomesloci2012_chr*.txt") ; return thisJob; } private Job vcfUpload(String[] types, String controlAnalysisId, List<String> tumourAnalysisIds, List<String> tumourAliquotIds) { Job thisJob = getWorkflow().createBashJob("vcfUpload"); String metadataUrls = new String(); metadataUrls = metadataUrls.concat(gnosServer) .concat("/cghub/metadata/analysisFull/") .concat(controlAnalysisId); for(String tumourAnalysisId : tumourAnalysisIds) { metadataUrls = metadataUrls.concat(",") .concat(gnosServer) .concat("/cghub/metadata/analysisFull/") .concat(tumourAnalysisId); } String vcfs = new String(); String tbis = new String(); String tars = new String(); String vcfmd5s = new String(); String tbimd5s = new String(); String tarmd5s = new String(); for(String type: types) { for(String tumourAliquotId : tumourAliquotIds) { // TODO: Hardcoded somatic here, is that correct? String baseFile = OUTDIR + "/" + tumourAliquotId + "." + workflowName + "." + dateString + ".somatic." + type; if(vcfs.length() > 0) { vcfs = vcfs.concat(","); tbis = tbis.concat(","); tars = tars.concat(","); vcfmd5s = vcfmd5s.concat(","); tbimd5s = tbimd5s.concat(","); tarmd5s = tarmd5s.concat(","); } vcfs = vcfs.concat(baseFile + ".vcf.gz"); tbis = tbis.concat(baseFile + ".vcf.gz.tbi"); tars = tars.concat(baseFile + ".tar.gz"); vcfmd5s = vcfmd5s.concat(baseFile + ".vcf.gz.md5"); tbimd5s = tbimd5s.concat(baseFile + ".vcf.gz.tbi.md5"); tarmd5s = tarmd5s.concat(baseFile + ".tar.gz.md5"); } } thisJob.getCommand() .addArgument("perl " + getWorkflowBaseDir()+ "/bin/gnos_upload_vcf.pl") .addArgument("--metadata-urls " + metadataUrls) .addArgument("--vcfs " + vcfs) .addArgument("--vcf-md5sum-files " + vcfmd5s) .addArgument("--vcf-idxs " + tbis) .addArgument("--vcf-idx-md5sum-files " + tbimd5s) .addArgument("--tarballs " + tars) .addArgument("--tarball-md5sum-files " + tarmd5s) .addArgument("--outdir " + OUTDIR + "/upload") .addArgument("--key " + pemFile) .addArgument("--upload-url " + uploadServer) .addArgument("--qc-metrics-json " + OUTDIR + "/qc_metrics.json") .addArgument("--timing-metrics-json " + OUTDIR + "/process_metrics.json") ; try { if(hasPropertyAndNotNull("study-refname-override")) { thisJob.getCommand().addArgument("--study-refname-override " + getProperty("study-refname-override")); } if(hasPropertyAndNotNull("analysis-center-override")) { thisJob.getCommand().addArgument("--analysis-center-override " + getProperty("analysis-center-override")); } if(hasPropertyAndNotNull("upload-test") && Boolean.valueOf(getProperty("upload-test"))) { thisJob.getCommand().addArgument("--test "); } if(hasPropertyAndNotNull("upload-skip")) { thisJob.getCommand().addArgument("--skip-upload"); } } catch (Exception e) { throw new RuntimeException(e); } return thisJob; } private Job packageResults(int tumourCount, String algName, String resultType, String tumourBam, String baseVcf, String workflowName, String somaticOrGermline, String date) { //#packageResults.pl outdir 0772aed3-4df7-403f-802a-808df2935cd1/c007f362d965b32174ec030825262714.bam outdir/caveman snv_mnv flagged.muts.vcf.gz Job thisJob = getWorkflow().createBashJob("packageResults"); thisJob.getCommand() .addArgument(getWorkflowBaseDir()+ "/bin/wrapper.sh") .addArgument(installBase) .addArgument(getWorkflowBaseDir() + "/bin/packageResults.pl") .addArgument(OUTDIR) .addArgument(tumourBam) .addArgument(OUTDIR + "/" + tumourCount + "/" + algName) .addArgument(resultType) .addArgument(baseVcf) .addArgument(workflowName) .addArgument(somaticOrGermline) .addArgument(date) ; return thisJob; } private Job gnosDownloadBaseJob(String analysisId) { Job thisJob = getWorkflow().createBashJob("GNOSDownload"); thisJob.getCommand() .addArgument("gtdownload -c " + pemFile) .addArgument("-v " + gnosServer + "/cghub/data/analysis/download/" + analysisId); return thisJob; } private Job basFileBaseJob(String analysisId, String sampleBam) { Job thisJob = getWorkflow().createBashJob("basFileGet"); thisJob.getCommand() .addArgument(getWorkflowBaseDir()+ "/bin/wrapper.sh") .addArgument(installBase) .addArgument("xml_to_bas.pl") .addArgument("-d " + gnosServer + "/cghub/metadata/analysisFull/" + analysisId) .addArgument("-o " + analysisId + "/" + sampleBam + ".bas") ; return thisJob; } private Job getMetricsJob(List<String> tumourBams) { //die "USAGE: rootOfOutdir ordered.bam [ordered.bam2]"; Job thisJob = getWorkflow().createBashJob("metrics"); thisJob.getCommand() .addArgument(getWorkflowBaseDir()+ "/bin/wrapper.sh") .addArgument(installBase) .addArgument(getWorkflowBaseDir()+ "/bin/qc_and_metrics.pl") .addArgument(OUTDIR); for(String bam : tumourBams) { thisJob.getCommand().addArgument(bam); } return thisJob; } private Job caveCnPrep(int tumourCount, String type) { thisJob.getCommand().addArgument("rm -rf ./*/*.bam " + OUTDIR); thisJob.getCommand().addArgument("rm -f ./*/*.bam");
package io.seqware.pancancer; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.List; import java.util.Map; import net.sourceforge.seqware.pipeline.workflowV2.AbstractWorkflowDataModel; import net.sourceforge.seqware.pipeline.workflowV2.model.Job; import net.sourceforge.seqware.pipeline.workflowV2.model.SqwFile; import org.apache.commons.lang.StringUtils; public class CgpCnIndelSnvStrWorkflow extends AbstractWorkflowDataModel { private static String OUTDIR = "outdir"; private static String TIMEDIR; private static String COUNTDIR; private static String BBDIR; private boolean testMode=false; private boolean cleanup = false; // datetime all upload files will be named with DateFormat df = new SimpleDateFormat("yyyyMMdd"); String dateString = df.format(Calendar.getInstance().getTime()); private String workflowName = "svcp_1-0-0"; // MEMORY variables // private String memBasFileGet, memGnosDownload, memPackageResults, memMarkTime, memQcMetrics, memUpload, memGetTbi, memPicnicCounts, memPicnicMerge, memUnpack, memBbMerge, // ascat memory memAlleleCount, memAscat, memAscatFinalise, // pindel memory memPindelInput, memPindel, memPindelVcf, memPindelMerge , memPindelFlag, // brass memory memBrassInput, memBrassGroup, memBrassFilter, memBrassSplit, memBrassAssemble, memBrassGrass, memBrassTabix, // caveman memory memCaveCnPrep, memCavemanSetup, memCavemanSplit, memCavemanSplitConcat, memCavemanMstep, memCavemanMerge, memCavemanEstep, memCavemanMergeResults, memCavemanAddIds, memCavemanFlag, memCavemanTbiClean ; // workflow variables private String // reference variables species, assembly, // sequencing type/protocol seqType, seqProtocol, //GNOS identifiers pemFile, gnosServer, uploadServer, // ascat variables gender, // pindel variables refExclude, pindelGermline, //caveman variables tabixSrvUri, //general variables installBase, refBase, genomeFaGz, testBase; private int coresAddressable; private void init() { try { //optional properties String outDir = OUTDIR; String outPrefix = ""; if (hasPropertyAndNotNull("output_dir")) { outDir = getProperty("output_dir"); } if (hasPropertyAndNotNull("output_prefix")) { outPrefix = getProperty("output_prefix"); } if (!"".equals(outPrefix)) { if (outPrefix.endsWith("/")) { OUTDIR = outPrefix+outDir; } else { OUTDIR = outPrefix + "/" + outDir; } } } catch (Exception e) { throw new RuntimeException(e); } TIMEDIR = OUTDIR + "/timings"; COUNTDIR = OUTDIR + "/ngsCounts"; BBDIR = OUTDIR + "/bbCounts"; } @Override public void setupDirectory() { //since setupDirectory is the first method run, we use it to initialize variables too. init(); // creates a dir1 directory in the current working directory where the workflow runs addDirectory(OUTDIR); addDirectory(TIMEDIR); addDirectory(COUNTDIR); addDirectory(BBDIR); } @Override public Map<String, SqwFile> setupFiles() { try { if(hasPropertyAndNotNull("cleanup")) { cleanup = Boolean.valueOf(getProperty("cleanup")); } if(hasPropertyAndNotNull("testMode")) { testMode=Boolean.valueOf(getProperty("testMode")); System.err.println("WARNING\n\tRunning in test mode, direct access BAM files will be used, change 'testMode' in ini file to disable\n"); } if(hasPropertyAndNotNull("uploadServer")) { uploadServer = getProperty("uploadServer"); } else { System.err.println("WARNING\n\t'uploadServer' not defined in workflow.ini, no VCF upload will be attempted\n"); } if(testMode && uploadServer != null) { System.err.println("WARNING\n\t'uploadServer' has been cleared as testMode is in effect\n"); uploadServer = null; } // used by steps that can use all available cores coresAddressable = Integer.valueOf(getProperty("coresAddressable")); // MEMORY // memBasFileGet = getProperty("memBasFileGet"); memGnosDownload = getProperty("memGnosDownload"); memPackageResults = getProperty("memPackageResults"); memMarkTime = getProperty("memMarkTime"); memQcMetrics = getProperty("memQcMetrics"); memUpload = getProperty("memUpload"); memGetTbi = getProperty("memGetTbi"); memPicnicCounts = getProperty("memPicnicCounts"); memPicnicMerge = getProperty("memPicnicMerge"); memUnpack = getProperty("memUnpack"); memBbMerge = getProperty("memBbMerge"); memAlleleCount = getProperty("memAlleleCount"); memAscat = getProperty("memAscat"); memAscatFinalise = getProperty("memAscatFinalise"); memPindelInput = getProperty("memPindelInput"); memPindel = getProperty("memPindel"); memPindelVcf = getProperty("memPindelVcf"); memPindelMerge = getProperty("memPindelMerge"); memPindelFlag = getProperty("memPindelFlag"); memBrassInput = getProperty("memBrassInput"); memBrassGroup = getProperty("memBrassGroup"); memBrassFilter = getProperty("memBrassFilter"); memBrassSplit = getProperty("memBrassSplit"); memBrassAssemble = getProperty("memBrassAssemble"); memBrassGrass = getProperty("memBrassGrass"); memBrassTabix = getProperty("memBrassTabix"); memCaveCnPrep = getProperty("memCaveCnPrep"); memCavemanSetup = getProperty("memCavemanSetup"); memCavemanSplit = getProperty("memCavemanSplit"); memCavemanSplitConcat = getProperty("memCavemanSplitConcat"); memCavemanMstep = getProperty("memCavemanMstep"); memCavemanMerge = getProperty("memCavemanMerge"); memCavemanEstep = getProperty("memCavemanEstep"); memCavemanMergeResults = getProperty("memCavemanMergeResults"); memCavemanAddIds = getProperty("memCavemanAddIds"); memCavemanFlag = getProperty("memCavemanFlag"); memCavemanTbiClean = getProperty("memCavemanTbiClean"); // REFERENCE INFO // species = getProperty("species"); assembly = getProperty("assembly"); // Sequencing info seqType = getProperty("seqType"); if(seqType.equals("WGS")) { seqProtocol = "genomic"; } // Specific to ASCAT workflow // gender = getProperty("gender"); // Specific to Caveman workflow // tabixSrvUri = getProperty("tabixSrvUri"); // pindel specific refExclude = getProperty("refExclude"); // used for upload too so always get it if(hasPropertyAndNotNull("gnosServer")) { gnosServer = getProperty("gnosServer"); } // test mode if(!testMode || (hasPropertyAndNotNull("upload-test") && Boolean.valueOf(getProperty("upload-test")))) { pemFile = getProperty("pemFile"); } //environment installBase = getWorkflowBaseDir() + "/bin/opt"; refBase = getWorkflowBaseDir() + "/data/reference/cgp_reference"; testBase = getWorkflowBaseDir() + "/data/testdata"; genomeFaGz = getWorkflowBaseDir() + "/data/reference/genome.fa.gz"; } catch (Exception ex) { throw new RuntimeException(ex); } return getFiles(); } private Job bamProvision(String analysisId, String bamFile, Job startTiming) { Job basJob = null; if(testMode == false) { Job gnosDownload = gnosDownloadBaseJob(analysisId); gnosDownload.setMaxMemory(memGnosDownload); gnosDownload.addParent(startTiming); // the file needs to end up in tumourBam/controlBam // get the BAS files basJob = basFileBaseJob(analysisId, bamFile); basJob.setMaxMemory(memBasFileGet); basJob.addParent(gnosDownload); } return basJob; } @Override public void buildWorkflow() { Job controlBasJob = null; String controlBam; List<String> tumourBams = new ArrayList<String>(); List<Job> tumourBasJobs = new ArrayList<Job>(); List<String> tumourAnalysisIds = new ArrayList<String>(); List<String> tumourAliquotIds = new ArrayList<String>(); String controlAnalysisId = new String(); Job startWorkflow = markTime("start"); startWorkflow.setMaxMemory(memMarkTime); try { if(testMode) { controlBam = OUTDIR + "/HCC1143_BL.bam"; controlAnalysisId = "HCC1143_BL"; tumourBams.add(OUTDIR + "/HCC1143.bam"); tumourAnalysisIds.add("HCC1143"); tumourAliquotIds.add("HCC1143"); controlBasJob = prepareTestData("HCC1143_BL"); controlBasJob.setMaxMemory("4000"); controlBasJob.setThreads(2); controlBasJob.addParent(startWorkflow); Job prepTum = prepareTestData("HCC1143"); prepTum.setMaxMemory("4000"); prepTum.setThreads(2); prepTum.addParent(startWorkflow); tumourBasJobs.add(prepTum); } else { controlAnalysisId = getProperty("controlAnalysisId"); controlBasJob = bamProvision(controlAnalysisId, getProperty("controlBam"), startWorkflow); controlBam = controlAnalysisId + "/" + getProperty("controlBam"); tumourAnalysisIds = Arrays.asList(getProperty("tumourAnalysisIds").split(":")); tumourAliquotIds = Arrays.asList(getProperty("tumourAliquotIds").split(":")); List<String> rawBams = Arrays.asList(getProperty("tumourBams").split(":")); if(rawBams.size() != tumourAnalysisIds.size()) { throw new RuntimeException("Properties tumourAnalysisId and tumourBam decode to lists of different sizes"); } if(rawBams.size() != tumourAliquotIds.size()) { throw new RuntimeException("Properties tumourAliquotIds and tumourBam decode to lists of different sizes"); } for(int i=0; i<rawBams.size(); i++) { Job tumourBasJob = bamProvision(tumourAnalysisIds.get(i), rawBams.get(i), startWorkflow); tumourBasJobs.add(tumourBasJob); String tumourBam = tumourAnalysisIds.get(i) + "/" + rawBams.get(i); tumourBams.add(tumourBam); } } } catch(Exception e) { throw new RuntimeException(e); } Job getTbiJob = stageTbi(); getTbiJob.setMaxMemory(memGetTbi); getTbiJob.addParent(startWorkflow); getTbiJob.addParent(controlBasJob); for(Job job : tumourBasJobs) { getTbiJob.addParent(job); } // these are not paired but per individual sample List<Job> ngsCountJobs = new ArrayList<Job>(); for(int i=1; i<=24; i++) { for(int j=0; j<tumourBams.size(); j++) { Job ngsCountJob = ngsCount(i, tumourBams.get(j), "tumour"+j, i); ngsCountJob.setMaxMemory(memPicnicCounts); ngsCountJob.addParent(getTbiJob); ngsCountJobs.add(ngsCountJob); } Job ngsCountJob = ngsCount(i, controlBam, "control", i); ngsCountJob.setMaxMemory(memPicnicCounts); ngsCountJob.addParent(getTbiJob); ngsCountJobs.add(ngsCountJob); } Job ngsCountMergeJob = ngsCountMerge(controlBam); ngsCountMergeJob.setMaxMemory(memPicnicMerge); for(Job j : ngsCountJobs) { ngsCountMergeJob.addParent(j); } List<Job> bbAlleleCountJobs = new ArrayList<Job>(); for(int i=0; i<23; i++) { // not 1-22+X for(int j=0; j<tumourBams.size(); j++) { Job bbAlleleCountJob = bbAlleleCount(i, tumourBams.get(j), "tumour"+j, i); bbAlleleCountJob.setMaxMemory(memAlleleCount); bbAlleleCountJob.addParent(getTbiJob); bbAlleleCountJobs.add(bbAlleleCountJob); } Job bbAlleleCountJob = bbAlleleCount(i, controlBam, "control", i); bbAlleleCountJob.setMaxMemory(memAlleleCount); bbAlleleCountJob.addParent(getTbiJob); bbAlleleCountJobs.add(bbAlleleCountJob); } Job bbAlleleMergeJob = bbAlleleMerge(controlBam); bbAlleleMergeJob.setMaxMemory(memBbMerge); for(Job j : bbAlleleCountJobs) { bbAlleleMergeJob.addParent(j); } Job[] cavemanFlagJobs = new Job [tumourBams.size()]; for(int i=0; i<tumourBams.size(); i++) { Job cavemanFlagJob = buildPairWorkflow(getTbiJob, controlBam, tumourBams.get(i), i); cavemanFlagJobs[i] = cavemanFlagJob; } Job cavemanTbiCleanJob = cavemanTbiCleanJob(); cavemanTbiCleanJob.setMaxMemory(memCavemanTbiClean); for(Job cavemanFlagJob : cavemanFlagJobs) { cavemanTbiCleanJob.addParent(cavemanFlagJob); } Job endWorkflow = markTime("end"); endWorkflow.setMaxMemory(memMarkTime); endWorkflow.addParent(cavemanTbiCleanJob); Job metricsJob = getMetricsJob(tumourBams); metricsJob.setMaxMemory(memQcMetrics); metricsJob.addParent(endWorkflow); Job renameImputeJob = renameSampleFile(tumourBams, OUTDIR + "/bbCounts", "imputeCounts.tar.gz"); renameImputeJob.setMaxMemory("4000"); renameImputeJob.addParent(bbAlleleMergeJob); Job renameImputeMd5Job = renameSampleFile(tumourBams, OUTDIR + "/bbCounts", "imputeCounts.tar.gz.md5"); renameImputeMd5Job.setMaxMemory("4000"); renameImputeMd5Job.addParent(bbAlleleMergeJob); Job renameCountsJob = renameSampleFile(tumourBams, OUTDIR + "/ngsCounts", "binnedReadCounts.tar.gz"); renameCountsJob.setMaxMemory("4000"); renameCountsJob.addParent(ngsCountMergeJob); Job renameCountsMd5Job = renameSampleFile(tumourBams, OUTDIR + "/ngsCounts", "binnedReadCounts.tar.gz.md5"); renameCountsMd5Job.setMaxMemory("4000"); renameCountsMd5Job.addParent(ngsCountMergeJob); if(uploadServer != null) { String[] resultTypes = {"snv_mnv","cnv","sv","indel"}; Job uploadJob = vcfUpload(resultTypes, controlAnalysisId, tumourAnalysisIds, tumourAliquotIds); uploadJob.setMaxMemory(memUpload); uploadJob.addParent(metricsJob); uploadJob.addParent(renameImputeJob); uploadJob.addParent(renameImputeMd5Job); uploadJob.addParent(renameCountsJob); uploadJob.addParent(renameCountsMd5Job); if (cleanup) { // if we upload to GNOS then go ahead and delete all the large files Job cleanJob = postUploadCleanJob(); cleanJob.addParent(uploadJob); } } else { // delete just the BAM inputs and not the output dir if (cleanup) { Job cleanInputsJob = cleanInputsJob(); cleanInputsJob.addParent(metricsJob); } } } /** * This builds the workflow for a pair of samples * The generic buildWorkflow section will choose the pair to be processed and * setup the control sample download */ private Job buildPairWorkflow(Job getTbiJob, String controlBam, String tumourBam, int tumourCount) { /** * ASCAT - Copynumber * Depends on * - tumour/control BAMs * - Gender, will attempt to determine if not specified */ Job[] alleleCountJobs = new Job[2]; for(int i=0; i<2; i++) { Job alleleCountJob = cgpAscatBaseJob(tumourCount, tumourBam, controlBam, "ASCAT", "allele_count", i+1); alleleCountJob.setMaxMemory(memAlleleCount); alleleCountJob.addParent(getTbiJob); alleleCountJobs[i] = alleleCountJob; } Job ascatJob = cgpAscatBaseJob(tumourCount, tumourBam, controlBam, "ASCAT", "ascat", 1); ascatJob.setMaxMemory(memAscat); ascatJob.addParent(alleleCountJobs[0]); ascatJob.addParent(alleleCountJobs[1]); Job ascatFinaliseJob = cgpAscatBaseJob(tumourCount, tumourBam, controlBam, "ASCAT", "finalise", 1); ascatFinaliseJob.setMaxMemory(memAscatFinalise); ascatFinaliseJob.addParent(ascatJob); Job ascatPackage = packageResults(tumourCount, "ascat", "cnv", tumourBam, "copynumber.caveman.vcf.gz", workflowName, "somatic", dateString); ascatPackage.setMaxMemory(memPackageResults); ascatPackage.addParent(ascatFinaliseJob); /** * CaVEMan setup is here to allow better workflow graph * Messy but necessary */ Job caveCnPrepJobs[] = new Job[2]; for(int i=0; i<2; i++) { Job caveCnPrepJob; if(i==0) { caveCnPrepJob = caveCnPrep(tumourCount, "tumour"); } else { caveCnPrepJob = caveCnPrep(tumourCount, "normal"); } caveCnPrepJob.addParent(getTbiJob); caveCnPrepJob.addParent(ascatFinaliseJob); // ASCAT dependency!!! caveCnPrepJobs[i] = caveCnPrepJob; } Job cavemanSetupJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "setup", 1); cavemanSetupJob.setMaxMemory(memCavemanSetup); cavemanSetupJob.addParent(caveCnPrepJobs[0]); cavemanSetupJob.addParent(caveCnPrepJobs[1]); // some dependencies handled by ascat step /** * Pindel - InDel calling * Depends on: * - tumour/control BAMs */ Job[] pindelInputJobs = new Job[2]; for(int i=0; i<2; i++) { Job inputParse = pindelBaseJob(tumourCount, tumourBam, controlBam, "cgpPindel", "input", i+1); inputParse.setMaxMemory(memPindelInput); inputParse.addParent(getTbiJob); pindelInputJobs[i] = inputParse; } // determine number of refs to process // we know that this is static for PanCancer so be lazy 24 jobs (1-22,X,Y) // but pindel needs to know the exclude list so hard code this Job pinVcfJobs[] = new Job[24]; for(int i=0; i<24; i++) { Job pindelJob = pindelBaseJob(tumourCount, tumourBam, controlBam, "cgpPindel", "pindel", i+1); pindelJob.setMaxMemory(memPindel); pindelJob.addParent(pindelInputJobs[0]); pindelJob.addParent(pindelInputJobs[1]); Job pinVcfJob = pindelBaseJob(tumourCount, tumourBam, controlBam, "cgpPindel", "pin2vcf", i+1); pinVcfJob.setMaxMemory(memPindelVcf); pinVcfJob.addParent(pindelJob); // pinVcf depends on pindelJob so only need have dependency on the pinVcf pinVcfJobs[i] = pinVcfJob; } Job pindelMergeJob = pindelBaseJob(tumourCount, tumourBam, controlBam, "cgpPindel", "merge", 1); pindelMergeJob.setMaxMemory(memPindelMerge); for (Job parent : pinVcfJobs) { pindelMergeJob.addParent(parent); } Job pindelFlagJob = pindelBaseJob(tumourCount, tumourBam, controlBam, "cgpPindel", "flag", 1); pindelFlagJob.setMaxMemory(memPindelFlag); pindelFlagJob.addParent(pindelMergeJob); pindelFlagJob.addParent(cavemanSetupJob); Job pindelPackage = packageResults(tumourCount, "pindel", "indel", tumourBam, "flagged.vcf.gz", workflowName, "somatic", dateString); pindelPackage.setMaxMemory(memPackageResults); pindelPackage.addParent(pindelFlagJob); /** * BRASS - BReakpoint AnalySiS * Depends on: * - tumour/control BAMs * - ASCAT output at filter step */ Job brassInputJobs[] = new Job[2]; for(int i=0; i<2; i++) { Job brassInputJob = brassBaseJob(tumourCount, tumourBam, controlBam, "BRASS", "input", i+1); brassInputJob.setMaxMemory(memBrassInput); brassInputJob.addParent(getTbiJob); brassInputJobs[i] = brassInputJob; } Job brassGroupJob = brassBaseJob(tumourCount, tumourBam, controlBam, "BRASS", "group", 1); brassGroupJob.setMaxMemory(memBrassGroup); brassGroupJob.addParent(brassInputJobs[0]); brassGroupJob.addParent(brassInputJobs[1]); Job brassFilterJob = brassBaseJob(tumourCount, tumourBam, controlBam, "BRASS", "filter", 1); brassFilterJob.setMaxMemory(memBrassFilter); brassFilterJob.addParent(brassGroupJob); brassFilterJob.addParent(ascatFinaliseJob); // NOTE: dependency on ASCAT!! Job brassSplitJob = brassBaseJob(tumourCount, tumourBam, controlBam, "BRASS", "split", 1); brassSplitJob.setMaxMemory(memBrassSplit); brassSplitJob.addParent(brassFilterJob); List<Job> brassAssembleJobs = new ArrayList<Job>(); for(int i=0; i<coresAddressable; i++) { Job brassAssembleJob = brassBaseJob(tumourCount, tumourBam, controlBam, "BRASS", "assemble", i+1); brassAssembleJob.setMaxMemory(memBrassAssemble); brassAssembleJob.addParent(brassSplitJob); brassAssembleJobs.add(brassAssembleJob); } Job brassGrassJob = brassBaseJob(tumourCount, tumourBam, controlBam, "BRASS", "grass", 1); brassGrassJob.setMaxMemory(memBrassGrass); for(Job brassAssembleJob : brassAssembleJobs) { brassGrassJob.addParent(brassAssembleJob); } Job brassTabixJob = brassBaseJob(tumourCount, tumourBam, controlBam, "BRASS", "tabix", 1); brassTabixJob.setMaxMemory(memBrassTabix); brassTabixJob.addParent(brassGrassJob); Job brassPackage = packageResults(tumourCount, "brass", "sv", tumourBam, "annot.vcf.gz", workflowName, "somatic", dateString); brassPackage.setMaxMemory(memPackageResults); brassPackage.addParent(brassTabixJob); /** * CaVEMan - SNV analysis * !! see above as setup done earlier to help with workflow structure !! * Depends on: * - tumour/control BAMs (but depend on BAS for better workflow) * - ASCAT from outset * - pindel at flag step */ // should really line count the fai file Job cavemanSplitJobs[] = new Job[86]; for(int i=0; i<86; i++) { Job cavemanSplitJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "split", i+1); cavemanSplitJob.setMaxMemory(memCavemanSplit); cavemanSplitJob.addParent(cavemanSetupJob); cavemanSplitJobs[i] = cavemanSplitJob; } Job cavemanSplitConcatJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "split_concat", 1); cavemanSplitConcatJob.setMaxMemory(memCavemanSplitConcat); for (Job cavemanSplitJob : cavemanSplitJobs) { cavemanSplitConcatJob.addParent(cavemanSplitJob); } List<Job> cavemanMstepJobs = new ArrayList<Job>(); for(int i=0; i<coresAddressable; i++) { Job cavemanMstepJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "mstep", i+1); cavemanMstepJob.setMaxMemory(memCavemanMstep); cavemanMstepJob.addParent(cavemanSplitConcatJob); cavemanMstepJobs.add(cavemanMstepJob); } Job cavemanMergeJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "merge", 1); cavemanMergeJob.setMaxMemory(memCavemanMerge); for(Job cavemanMstepJob : cavemanMstepJobs) { cavemanMergeJob.addParent(cavemanMstepJob); } List<Job> cavemanEstepJobs = new ArrayList<Job>(); for(int i=0; i<coresAddressable; i++) { Job cavemanEstepJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "estep", i+1); cavemanEstepJob.setMaxMemory(memCavemanEstep); cavemanEstepJob.addParent(cavemanMergeJob); cavemanEstepJobs.add(cavemanEstepJob); } Job cavemanMergeResultsJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "merge_results", 1); cavemanMergeResultsJob.setMaxMemory(memCavemanMergeResults); for(Job cavemanEstepJob : cavemanEstepJobs) { cavemanMergeResultsJob.addParent(cavemanEstepJob); } Job cavemanAddIdsJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "add_ids", 1); cavemanAddIdsJob.setMaxMemory(memCavemanAddIds); cavemanAddIdsJob.addParent(cavemanMergeResultsJob); Job cavemanFlagJob = cavemanBaseJob(tumourCount, tumourBam, controlBam, "CaVEMan", "flag", 1); cavemanFlagJob.setMaxMemory(memCavemanFlag); cavemanFlagJob.addParent(getTbiJob); cavemanFlagJob.addParent(pindelFlagJob); // PINDEL dependency cavemanFlagJob.addParent(cavemanAddIdsJob); Job cavemanPackage = packageResults(tumourCount, "caveman", "snv_mnv", tumourBam, "flagged.muts.vcf.gz", workflowName, "somatic", dateString); cavemanPackage.setMaxMemory(memPackageResults); cavemanPackage.addParent(cavemanFlagJob); return cavemanFlagJob; } private Job prepareTestData(String sample) { Job thisJob = getWorkflow().createBashJob("prepTest"); thisJob.getCommand() .addArgument(getWorkflowBaseDir()+ "/bin/wrapper.sh") .addArgument(installBase) .addArgument("scramble -I cram -O bam") .addArgument("-r " + testBase + "/genome.fa") .addArgument("-t 2") .addArgument(testBase + "/" + sample + ".cram") .addArgument(OUTDIR + "/" + sample + ".bam") .addArgument("; cp " + testBase + "/" + sample + ".bam.bas") .addArgument(OUTDIR + "/.") .addArgument("; samtools index " + OUTDIR + "/" + sample + ".bam") ; return thisJob; } private Job ngsCountMerge(String controlBam) { Job thisJob = prepTimedJob(0, "binCount", "merge", 0); thisJob.getCommand() .addArgument(getWorkflowBaseDir()+ "/bin/wrapper.sh") .addArgument(installBase) .addArgument("ngs_bin_allele_merge.pl") .addArgument(controlBam) .addArgument(COUNTDIR) ; return thisJob; } private Job ngsCount(int sampleIndex, String bam, String process, int index) { String chr = Integer.toString(index+1); if(index+1 == 23) { chr = "X"; } else if(index+1 == 24) { chr = "Y"; } Job thisJob = prepTimedJob(sampleIndex, "binCounts", process, index); thisJob.getCommand() .addArgument(getWorkflowBaseDir()+ "/bin/wrapper.sh") .addArgument(installBase) .addArgument("ngs_bin_allele.pl") .addArgument(refBase + "/picnic/cn_bins.csv.gz") .addArgument(refBase + "/picnic/snp6.csv.gz") .addArgument(COUNTDIR) .addArgument(bam) .addArgument(chr) ; return thisJob; } private Job bbAlleleCount(int sampleIndex, String bam, String process, int index) { Job thisJob = prepTimedJob(sampleIndex, "bbAllele", process, index); int chr = index+1; thisJob.getCommand() .addArgument(getWorkflowBaseDir()+ "/bin/wrapper.sh") .addArgument(installBase) .addArgument(getWorkflowBaseDir()+ "/bin/execute_with_sample.pl " + bam) .addArgument("alleleCounter") .addArgument("-l " + refBase + "/battenberg/1000genomesloci/1000genomesloci2012_chr" + chr + ".txt") .addArgument("-o " + BBDIR + "/%SM%." + chr + ".tsv") .addArgument("-b " + bam) ; return thisJob; } private Job bbAlleleMerge(String controlBam) { Job thisJob = prepTimedJob(0, "bbAllele", "merge", 0); thisJob.getCommand() .addArgument(getWorkflowBaseDir()+ "/bin/wrapper.sh") .addArgument(installBase) .addArgument(getWorkflowBaseDir()+ "/bin/packageImpute.pl") .addArgument(controlBam) .addArgument(BBDIR) ; return thisJob; } private Job renameSampleFile(List<String> bams, String dir, String extension) { Job thisJob = getWorkflow().createBashJob("renameSampleFile"); for(String bam : bams) { thisJob.getCommand() .addArgument(getWorkflowBaseDir()+ "/bin/wrapper.sh") .addArgument(installBase) .addArgument(getWorkflowBaseDir()+ "/bin/execute_with_sample.pl " + bam) .addArgument("cp " + dir + "/" + "%SM%." + extension) .addArgument(OUTDIR + "/" + "%SM%." + workflowName + "." + dateString + ".somatic." + extension) ; } return thisJob; } private Job vcfUpload(String[] types, String controlAnalysisId, List<String> tumourAnalysisIds, List<String> tumourAliquotIds) { Job thisJob = getWorkflow().createBashJob("vcfUpload"); String metadataUrls = new String(); metadataUrls = metadataUrls.concat(gnosServer) .concat("/cghub/metadata/analysisFull/") .concat(controlAnalysisId); for(String tumourAnalysisId : tumourAnalysisIds) { metadataUrls = metadataUrls.concat(",") .concat(gnosServer) .concat("/cghub/metadata/analysisFull/") .concat(tumourAnalysisId); } String vcfs = new String(); String tbis = new String(); String tars = new String(); String vcfmd5s = new String(); String tbimd5s = new String(); String tarmd5s = new String(); for(String type: types) { for(String tumourAliquotId : tumourAliquotIds) { // TODO: Hardcoded somatic here, is that correct? String baseFile = OUTDIR + "/" + tumourAliquotId + "." + workflowName + "." + dateString + ".somatic." + type; if(vcfs.length() > 0) { vcfs = vcfs.concat(","); tbis = tbis.concat(","); tars = tars.concat(","); vcfmd5s = vcfmd5s.concat(","); tbimd5s = tbimd5s.concat(","); tarmd5s = tarmd5s.concat(","); } vcfs = vcfs.concat(baseFile + ".vcf.gz"); tbis = tbis.concat(baseFile + ".vcf.gz.tbi"); tars = tars.concat(baseFile + ".tar.gz"); vcfmd5s = vcfmd5s.concat(baseFile + ".vcf.gz.md5"); tbimd5s = tbimd5s.concat(baseFile + ".vcf.gz.tbi.md5"); tarmd5s = tarmd5s.concat(baseFile + ".tar.gz.md5"); } } // specific to CGP data for(String tumourAliquotId : tumourAliquotIds) { String baseFile = OUTDIR + "/" + tumourAliquotId + "." + workflowName + "." + dateString + ".somatic."; tars = tars.concat("," + baseFile + "imputeCounts.tar.gz"); tars = tars.concat("," + baseFile + "binnedReadCounts.tar.gz"); tarmd5s = tarmd5s.concat("," + baseFile + "imputeCounts.tar.gz.md5"); tarmd5s = tarmd5s.concat("," + baseFile + "binnedReadCounts.tar.gz.md5"); } thisJob.getCommand() .addArgument("perl " + getWorkflowBaseDir()+ "/bin/gnos_upload_vcf.pl") .addArgument("--metadata-urls " + metadataUrls) .addArgument("--vcfs " + vcfs) .addArgument("--vcf-md5sum-files " + vcfmd5s) .addArgument("--vcf-idxs " + tbis) .addArgument("--vcf-idx-md5sum-files " + tbimd5s) .addArgument("--tarballs " + tars) .addArgument("--tarball-md5sum-files " + tarmd5s) .addArgument("--outdir " + OUTDIR + "/upload") .addArgument("--key " + pemFile) .addArgument("--upload-url " + uploadServer) .addArgument("--qc-metrics-json " + OUTDIR + "/qc_metrics.json") .addArgument("--timing-metrics-json " + OUTDIR + "/process_metrics.json") ; try { if(hasPropertyAndNotNull("study-refname-override")) { thisJob.getCommand().addArgument("--study-refname-override " + getProperty("study-refname-override")); } if(hasPropertyAndNotNull("analysis-center-override")) { thisJob.getCommand().addArgument("--analysis-center-override " + getProperty("analysis-center-override")); } if(hasPropertyAndNotNull("upload-test") && Boolean.valueOf(getProperty("upload-test"))) { thisJob.getCommand().addArgument("--test "); } if(hasPropertyAndNotNull("upload-skip")) { thisJob.getCommand().addArgument("--skip-upload"); } } catch (Exception e) { throw new RuntimeException(e); } return thisJob; } private Job packageResults(int tumourCount, String algName, String resultType, String tumourBam, String baseVcf, String workflowName, String somaticOrGermline, String date) { //#packageResults.pl outdir 0772aed3-4df7-403f-802a-808df2935cd1/c007f362d965b32174ec030825262714.bam outdir/caveman snv_mnv flagged.muts.vcf.gz Job thisJob = getWorkflow().createBashJob("packageResults"); thisJob.getCommand() .addArgument(getWorkflowBaseDir()+ "/bin/wrapper.sh") .addArgument(installBase) .addArgument(getWorkflowBaseDir() + "/bin/packageResults.pl") .addArgument(OUTDIR) .addArgument(tumourBam) .addArgument(OUTDIR + "/" + tumourCount + "/" + algName) .addArgument(resultType) .addArgument(baseVcf) .addArgument(workflowName) .addArgument(somaticOrGermline) .addArgument(date) ; return thisJob; } private Job gnosDownloadBaseJob(String analysisId) { Job thisJob = getWorkflow().createBashJob("GNOSDownload"); thisJob.getCommand() .addArgument("gtdownload -c " + pemFile) .addArgument("-v " + gnosServer + "/cghub/data/analysis/download/" + analysisId); return thisJob; } private Job basFileBaseJob(String analysisId, String sampleBam) { Job thisJob = getWorkflow().createBashJob("basFileGet"); thisJob.getCommand() .addArgument(getWorkflowBaseDir()+ "/bin/wrapper.sh") .addArgument(installBase) .addArgument("xml_to_bas.pl") .addArgument("-d " + gnosServer + "/cghub/metadata/analysisFull/" + analysisId) .addArgument("-o " + analysisId + "/" + sampleBam + ".bas") ; return thisJob; } private Job getMetricsJob(List<String> tumourBams) { //die "USAGE: rootOfOutdir ordered.bam [ordered.bam2]"; Job thisJob = getWorkflow().createBashJob("metrics"); thisJob.getCommand() .addArgument(getWorkflowBaseDir()+ "/bin/wrapper.sh") .addArgument(installBase) .addArgument(getWorkflowBaseDir()+ "/bin/qc_and_metrics.pl") .addArgument(OUTDIR); for(String bam : tumourBams) { thisJob.getCommand().addArgument(bam); } return thisJob; } private Job caveCnPrep(int tumourCount, String type) { thisJob.getCommand().addArgument("rm -rf ./*/*.bam " + OUTDIR); thisJob.getCommand().addArgument("rm -f ./*/*.bam");
package me.nallar.javatransformer.api; import com.github.javaparser.JavaParser; import com.github.javaparser.ParseException; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; import com.github.javaparser.ast.body.TypeDeclaration; import lombok.*; import me.nallar.javatransformer.internal.ByteCodeInfo; import me.nallar.javatransformer.internal.SourceInfo; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.tree.ClassNode; import java.io.*; import java.nio.charset.*; import java.nio.file.*; import java.nio.file.attribute.*; import java.util.*; import java.util.function.*; import java.util.zip.*; @Getter @Setter @ToString public class JavaTransformer { private final List<Transformer> transformers = new ArrayList<>(); private final SimpleMultiMap<String, Transformer> classTransformers = new SimpleMultiMap<>(); private final Map<String, byte[]> transformedFiles = new HashMap<>(); private static byte[] readFully(InputStream is) { byte[] output = {}; int position = 0; while (true) { int bytesToRead; if (position >= output.length) { bytesToRead = output.length + 4096; if (output.length < position + bytesToRead) { output = Arrays.copyOf(output, position + bytesToRead); } } else { bytesToRead = output.length - position; } int bytesRead; try { bytesRead = is.read(output, position, bytesToRead); } catch (IOException e) { throw new IOError(e); } if (bytesRead < 0) { if (output.length != position) { output = Arrays.copyOf(output, position); } break; } position += bytesRead; } return output; } private Map<String, List<Transformer>> getClassTransformers() { return Collections.unmodifiableMap(classTransformers.map); } public void save(@NonNull Path path) { switch (PathType.of(path)) { case JAR: saveJar(path); break; case FOLDER: saveFolder(path); break; } } public void load(@NonNull Path path) { load(path, true); } public void parse(@NonNull Path path) { load(path, false); } private void load(@NonNull Path path, boolean saveTransformedResults) { switch (PathType.of(path)) { case JAR: loadJar(path, saveTransformedResults); break; case FOLDER: loadFolder(path, saveTransformedResults); break; } } public void transform(@NonNull Path load, @NonNull Path save) { load(load, true); save(save); clear(); } private void loadFolder(Path input, boolean saveTransformedResults) { try { Files.walkFileTree(input, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { val relativeName = input.relativize(file).toString(); val supplier = transformBytes(relativeName, () -> { try { return Files.readAllBytes(file); } catch (IOException e) { throw new IOError(e); } }); saveTransformedResult(relativeName, supplier, saveTransformedResults); return FileVisitResult.CONTINUE; } }); } catch (IOException e) { throw new IOError(e); } } private void loadJar(Path p, boolean saveTransformedResults) { ZipEntry entry; try (ZipInputStream is = new ZipInputStream(new BufferedInputStream(new FileInputStream(p.toFile())))) { while ((entry = is.getNextEntry()) != null) { saveTransformedResult(entry.getName(), transformBytes(entry.getName(), () -> readFully(is)), saveTransformedResults); } } catch (IOException e) { throw new IOError(e); } } private void saveTransformedResult(String relativeName, Supplier<byte[]> supplier, boolean saveTransformedResults) { if (saveTransformedResults) transformedFiles.put(relativeName, supplier.get()); } private void saveFolder(Path output) { transformedFiles.forEach(((fileName, bytes) -> { Path outputFile = output.resolve(fileName); try { if (Files.exists(outputFile)) { throw new IOException("Output file already exists: " + outputFile); } Files.createDirectories(outputFile.getParent()); Files.write(outputFile, bytes); } catch (IOException e) { throw new IOError(e); } })); } private void saveJar(Path jar) { try (ZipOutputStream os = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(jar.toFile())))) { transformedFiles.forEach(((relativeName, bytes) -> { try { os.putNextEntry(new ZipEntry(relativeName)); os.write(bytes); } catch (IOException e) { throw new IOError(e); } })); } catch (IOException e) { e.printStackTrace(); } } public void clear() { transformedFiles.clear(); } public void addTransformer(@NonNull Transformer.TargetedTransformer t) { if (transformers.contains(t)) { throw new IllegalArgumentException("Transformer " + t + " has already been added"); } for (String name : t.getTargetClasses()) { classTransformers.put(name, t); } } public void addTransformer(@NonNull String s, @NonNull Transformer t) { if (!t.shouldTransform(s)) { throw new IllegalArgumentException("Transformer " + t + " must transform class of name " + s); } if (classTransformers.get(s).contains(t)) { throw new IllegalArgumentException("Transformer " + t + " has already been added for class " + s); } classTransformers.put(s, t); } public void addTransformer(@NonNull Transformer t) { if (t instanceof Transformer.TargetedTransformer) { addTransformer((Transformer.TargetedTransformer) t); return; } if (transformers.contains(t)) { throw new IllegalArgumentException("Transformer " + t + " has already been added"); } transformers.add(t); } public Supplier<byte[]> transformJava(@NonNull Supplier<byte[]> data, @NonNull String name) { if (!shouldTransform(name)) return data; CompilationUnit cu; try { cu = JavaParser.parse(new ByteArrayInputStream(data.get())); } catch (ParseException e) { throw new RuntimeException(e); } String packageName = cu.getPackage().getName().getName(); for (TypeDeclaration typeDeclaration : cu.getTypes()) { if (!(typeDeclaration instanceof ClassOrInterfaceDeclaration)) { continue; } val classDeclaration = (ClassOrInterfaceDeclaration) typeDeclaration; String shortClassName = classDeclaration.getName(); if ((packageName + '.' + shortClassName).equalsIgnoreCase(name)) { transformJar(new SourceInfo(classDeclaration)); } } return () -> cu.toString().getBytes(Charset.forName("UTF-8")); } public Supplier<byte[]> transformClass(@NonNull Supplier<byte[]> data, @NonNull String name) { if (!shouldTransform(name)) return data; ClassNode node = new ClassNode(); ClassReader reader = new ClassReader(data.get()); reader.accept(node, ClassReader.EXPAND_FRAMES); transformJar(new ByteCodeInfo(node)); ClassWriter classWriter = new ClassWriter(reader, 0); node.accept(classWriter); return classWriter::toByteArray; } private void transformJar(ClassInfo editor) { val name = editor.getName(); transformers.forEach((x) -> { if (x.shouldTransform(name)) { x.transform(editor); } }); classTransformers.get(name).forEach((it) -> it.transform(editor)); } private boolean shouldTransform(String className) { if (!classTransformers.get(className).isEmpty()) return true; for (Transformer transformer : transformers) { if (transformer.shouldTransform(className)) return true; } return false; } private Supplier<byte[]> transformBytes(String relativeName, Supplier<byte[]> dataSupplier) { if (relativeName.endsWith(".java")) { String clazzName = relativeName.substring(0, relativeName.length() - 5).replace('/', '.'); if (clazzName.startsWith(".")) { clazzName = clazzName.substring(1); } return transformJava(dataSupplier, clazzName); } else if (relativeName.endsWith(".class")) { String clazzName = relativeName.substring(0, relativeName.length() - 6).replace('/', '.'); if (clazzName.startsWith(".")) { clazzName = clazzName.substring(1); } return transformClass(dataSupplier, clazzName); } return dataSupplier; } private enum PathType { JAR, FOLDER; static PathType of(Path p) { if (!p.getFileName().toString().contains(".")) { if (Files.exists(p) && !Files.isDirectory(p)) { throw new RuntimeException("Path " + p + " should be a directory or not already exist"); } return FOLDER; } if (Files.isDirectory(p)) { throw new RuntimeException("Path " + p + " should be a file or not already exist"); } return JAR; } } private static class SimpleMultiMap<K, T> { private final Map<K, List<T>> map = new HashMap<>(); public void put(K key, T value) { List<T> values = map.get(key); if (values == null) { values = new ArrayList<>(); map.put(key, values); } values.add(value); } public List<T> get(K key) { List<T> values = map.get(key); return values == null ? Collections.emptyList() : values; } public String toString() { return map.toString(); } } }
package mx.nic.rdap.server.renderer.json; import java.net.IDN; import java.util.List; import java.util.Map; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonArrayBuilder; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import mx.nic.rdap.core.db.Domain; import mx.nic.rdap.db.model.ZoneModel; import mx.nic.rdap.server.PrivacyStatus; import mx.nic.rdap.server.PrivacyUtil; public class DomainParser { public static JsonArray getJsonArray(List<Domain> domains, boolean isAuthenticated, boolean isOwner) { JsonArrayBuilder builder = Json.createArrayBuilder(); for (Domain domain : domains) { builder.add(getJson(domain, isAuthenticated, isOwner)); } return builder.build(); } public static JsonObject getJson(Domain domain, boolean isAuthenticated, boolean isOwner) { Map<String, PrivacyStatus> settings = PrivacyUtil.getDomainPrivacySettings(); JsonObjectBuilder builder = Json.createObjectBuilder(); builder.add("objectClassName", "domain"); JsonUtil.fillCommonRdapJsonObject(builder, domain, isAuthenticated, isOwner, settings, PrivacyUtil.getDomainRemarkPrivacySettings(), PrivacyUtil.getDomainLinkPrivacySettings(), PrivacyUtil.getDomainEventPrivacySettings()); String key = "ldhName"; String value = domain.getLdhName() + "." + ZoneModel.getZoneNameById(domain.getZoneId()); if (PrivacyUtil.isObjectVisible(value, key, settings.get(key), isAuthenticated, isOwner)) builder.add(key, value); key = "unicodeName"; value = domain.getUnicodeName() + "." + ZoneModel.getZoneNameById(domain.getZoneId()); if (PrivacyUtil.isObjectVisible(value, key, settings.get(key), isAuthenticated, isOwner)) builder.add(key, value); key = "variants"; if (PrivacyUtil.isObjectVisible(domain.getVariants(), key, settings.get(key), isAuthenticated, isOwner)) builder.add(key, VariantParser.getJsonArray(domain.getVariants(), isAuthenticated, isOwner)); key = "publicIds"; if (PrivacyUtil.isObjectVisible(domain.getPublicIds(), key, settings.get(key), isAuthenticated, isOwner)) { builder.add(key, PublicIdParser.getJsonArray(domain.getPublicIds(), isAuthenticated, isOwner, PrivacyUtil.getDomainPublicIdsPrivacySettings())); } key = "nameservers"; if (PrivacyUtil.isObjectVisible(domain.getNameServers(), key, settings.get(key), isAuthenticated, isOwner)) builder.add(key, NameserverParser.getJsonArray(domain.getNameServers(), isAuthenticated, isOwner)); key = "secureDNS"; if (PrivacyUtil.isObjectVisible(domain.getSecureDNS(), key, settings.get(key), isAuthenticated, isOwner)) builder.add(key, SecureDNSParser.getJsonObject(domain.getSecureDNS(), isAuthenticated, isOwner)); return builder.build(); } }
package net.alpenblock.bungeeperms; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.UUID; import lombok.Getter; import lombok.Setter; import net.alpenblock.bungeeperms.Lang.MessageType; import net.alpenblock.bungeeperms.io.BackEnd; import net.alpenblock.bungeeperms.io.BackEndType; import net.alpenblock.bungeeperms.io.MySQL2BackEnd; import net.alpenblock.bungeeperms.io.MySQLBackEnd; import net.alpenblock.bungeeperms.io.MySQLUUIDPlayerDB; import net.alpenblock.bungeeperms.io.NoneUUIDPlayerDB; import net.alpenblock.bungeeperms.io.UUIDPlayerDB; import net.alpenblock.bungeeperms.io.UUIDPlayerDBType; import net.alpenblock.bungeeperms.io.YAMLBackEnd; import net.alpenblock.bungeeperms.io.YAMLUUIDPlayerDB; import net.alpenblock.bungeeperms.io.migrate.Migrate2MySQL; import net.alpenblock.bungeeperms.io.migrate.Migrate2MySQL2; import net.alpenblock.bungeeperms.io.migrate.Migrate2YAML; import net.alpenblock.bungeeperms.io.migrate.Migrator; import net.alpenblock.bungeeperms.platform.PlatformPlugin; import net.alpenblock.bungeeperms.platform.Sender; import net.alpenblock.bungeeperms.util.ConcurrentList; public class PermissionsManager { private final PlatformPlugin plugin; private final BPConfig config; private final Debug debug; private boolean enabled = false; @Getter @Setter private BackEnd backEnd; @Getter private UUIDPlayerDB UUIDPlayerDB; private List<Group> groups; private List<User> users; private int permsversion; public PermissionsManager(PlatformPlugin p, BPConfig conf, Debug d) { plugin = p; config = conf; debug = d; //config loadConfig(); //perms loadPerms(); } /** * Loads the configuration of the plugin from the config.yml file. */ public final void loadConfig() { BackEndType bet = config.getBackEndType(); if (bet == BackEndType.YAML) { backEnd = new YAMLBackEnd(); } else if (bet == BackEndType.MySQL) { backEnd = new MySQLBackEnd(); } else if (bet == BackEndType.MySQL2) { backEnd = new MySQL2BackEnd(); } UUIDPlayerDBType updbt = config.getUUIDPlayerDBType(); if (updbt == UUIDPlayerDBType.None) { UUIDPlayerDB = new NoneUUIDPlayerDB(); } else if (updbt == UUIDPlayerDBType.YAML) { UUIDPlayerDB = new YAMLUUIDPlayerDB(); } else if (updbt == UUIDPlayerDBType.MySQL) { UUIDPlayerDB = new MySQLUUIDPlayerDB(); } } /** * (Re)loads the all groups and online players from file/table. */ public final void loadPerms() { BungeePerms.getLogger().info(Lang.translate(MessageType.PERMISSIONS_LOADING)); //load database backEnd.load(); //load all groups groups = backEnd.loadGroups(); users = new ConcurrentList<>(); //load permsversion permsversion = backEnd.loadVersion(); BungeePerms.getLogger().info(Lang.translate(MessageType.PERMISSIONS_LOADED)); } public void enable() { if (enabled) { return; } //load online players; allows reload for (Sender s : BungeePerms.getInstance().getPlugin().getPlayers()) { if (config.isUseUUIDs()) { getUser(s.getUUID()); } else { getUser(s.getName()); } } enabled = true; } public void disable() { if (!enabled) { return; } enabled = false; } public void reload() { disable(); //config loadConfig(); //perms loadPerms(); enable(); } /** * Validates all loaded groups and users and fixes invalid objects. */ public synchronized void validateUsersGroups() { //group check - remove inheritances for (int i = 0; i < groups.size(); i++) { Group group = groups.get(i); List<String> inheritances = group.getInheritances(); for (int j = 0; j < inheritances.size(); j++) { if (getGroup(inheritances.get(j)) == null) { inheritances.remove(j); j } } backEnd.saveGroupInheritances(group); } //perms recalc and bukkit perms update for (Group g : groups) { g.recalcPerms(); //send bukkit update info BungeePerms.getInstance().getNetworkNotifier().reloadGroup(g, null); } //user check for (int i = 0; i < users.size(); i++) { User u = users.get(i); for (int j = 0; j < u.getGroups().size(); j++) { if (getGroup(u.getGroups().get(j).getName()) == null) { u.getGroups().remove(j); j } } backEnd.saveUserGroups(u); } //perms recalc and bukkit perms update for (User u : users) { u.recalcPerms(); //send bukkit update info BungeePerms.getInstance().getNetworkNotifier().reloadUser(u, null); } //user groups check - backEnd List<User> backendusers = backEnd.loadUsers(); for (int i = 0; i < backendusers.size(); i++) { User u = backendusers.get(i); for (int j = 0; j < u.getGroups().size(); j++) { if (getGroup(u.getGroups().get(j).getName()) == null) { u.getGroups().remove(j); j } } backEnd.saveUserGroups(u); } } /** * Get the group of the player with the highesst rank. Do not to be confused with the rank property. The higher the rank the smaller the rank property. (1 is highest rank; 1000 is a low rank) * * @param player the user to get the main group of * @return the main group of the user (highest rank) * @throws NullPointerException if player is null */ public synchronized Group getMainGroup(User player) { if (player == null) { throw new NullPointerException("player is null"); } if (player.getGroups().isEmpty()) { return null; } Group ret = player.getGroups().get(0); for (int i = 1; i < player.getGroups().size(); i++) { if (player.getGroups().get(i).getWeight() < ret.getWeight()) { ret = player.getGroups().get(i); } } return ret; } public synchronized Group getNextGroup(Group group) { List<Group> laddergroups = getLadderGroups(group.getLadder()); for (int i = 0; i < laddergroups.size(); i++) { if (laddergroups.get(i).getRank() == group.getRank()) { if (i + 1 < laddergroups.size()) { return laddergroups.get(i + 1); } else { return null; } } } throw new IllegalArgumentException("group ladder does not exist (anymore)"); } public synchronized Group getPreviousGroup(Group group) { List<Group> laddergroups = getLadderGroups(group.getLadder()); for (int i = 0; i < laddergroups.size(); i++) { if (laddergroups.get(i).getRank() == group.getRank()) { if (i > 0) { return laddergroups.get(i - 1); } else { return null; } } } throw new IllegalArgumentException("group ladder does not exist (anymore)"); } /** * Gets all groups of the given ladder. * * @param ladder the ladder of the groups to get * @return a sorted list of all matched groups */ public synchronized List<Group> getLadderGroups(String ladder) { List<Group> ret = new ArrayList<>(); for (Group g : groups) { if (g.getLadder().equalsIgnoreCase(ladder)) { ret.add(g); } } Collections.sort(ret); return ret; } /** * Gets a list of all existing ladders. * * @return a list of all ladders */ public synchronized List<String> getLadders() { List<String> ret = new ArrayList<>(); for (Group g : groups) { if (!ret.contains(g.getLadder())) { ret.add(g.getLadder()); } } return ret; } /** * Gets a list of all groups that are marked as default and given to all users by default. * * @return a list of default groups */ public synchronized List<Group> getDefaultGroups() { List<Group> ret = new ArrayList<>(); for (Group g : groups) { if (g.isDefault()) { ret.add(g); } } return ret; } /** * Gets a group by its name. * * @param groupname the name of the group to get * @return the found group if any or null */ public synchronized Group getGroup(String groupname) { if (groupname == null) { return null; } for (Group g : groups) { if (g.getName().equalsIgnoreCase(groupname)) { return g; } } return null; } /** * Gets a user by its name. If the user is not loaded it will be loaded. * * @param usernameoruuid the name or the UUID of the user to get * @return the found user or null if it does not exist */ public synchronized User getUser(String usernameoruuid) { if (usernameoruuid == null) { return null; } UUID uuid = Statics.parseUUID(usernameoruuid); if (config.isUseUUIDs()) { if (uuid != null) { return getUser(uuid); } } for (User u : users) { if (u.getName().equalsIgnoreCase(usernameoruuid)) { return u; } } //load user from database User u = null; if (config.isUseUUIDs()) { if (uuid == null) { uuid = UUIDPlayerDB.getUUID(usernameoruuid); } if (uuid != null) { u = backEnd.loadUser(uuid); } } else { u = backEnd.loadUser(usernameoruuid); } if (u != null) { users.add(u); return u; } return null; } /** * Gets a user by its UUID. If the user is not loaded it will be loaded. * * @param uuid the uuid of the user to get * @return the found user or null if it does not exist */ public synchronized User getUser(UUID uuid) { if (uuid == null) { return null; } for (User u : users) { if (u.getUUID().equals(uuid)) { return u; } } //load user from database User u = backEnd.loadUser(uuid); if (u != null) { users.add(u); return u; } return null; } /** * Gets an unmodifiable list of all groups * * @return an unmodifiable list of all groups */ public List<Group> getGroups() { return Collections.unmodifiableList(groups); } /** * Gets an unmodifiable list of all loaded users * * @return an unmodifiable list of all loaded users */ public List<User> getUsers() { return Collections.unmodifiableList(users); } /** * Gets a list of all users * * @return a list of all users */ public List<String> getRegisteredUsers() { return backEnd.getRegisteredUsers(); } /** * Gets a list of all user which are in the given group * * @param group the group * @return a list of all user which are in the given group */ public List<String> getGroupUsers(Group group) { return backEnd.getGroupUsers(group); } /** * Deletes a user from cache and database. * * @param user the user to delete */ public synchronized void deleteUser(User user) { //cache users.remove(user); //database backEnd.deleteUser(user); //send bukkit update infoif(useUUIDs) BungeePerms.getInstance().getNetworkNotifier().deleteUser(user, null); } /** * Deletes a user from cache and database and validates all groups and users. * * @param group the group the remove */ public synchronized void deleteGroup(Group group) { //cache groups.remove(group); //database backEnd.deleteGroup(group); //group validation validateUsersGroups(); //send bukkit update info BungeePerms.getInstance().getNetworkNotifier().deleteGroup(group, null); } /** * Adds a user to cache and database. * * @param user the user to add */ public synchronized void addUser(User user) { //cache users.add(user); //database backEnd.saveUser(user, true); //send bukkit update info BungeePerms.getInstance().getNetworkNotifier().reloadUser(user, null); } /** * Adds a group to cache and database. * * @param group the group to add */ public synchronized void addGroup(Group group) { //cache groups.add(group); Collections.sort(groups); //database backEnd.saveGroup(group, true); //send bukkit update info BungeePerms.getInstance().getNetworkNotifier().reloadGroup(group, null); } public void format() { backEnd.format(backEnd.loadGroups(), backEnd.loadUsers(), permsversion); backEnd.load(); BungeePerms.getInstance().getNetworkNotifier().reloadAll(null); } public int cleanup() { int res = backEnd.cleanup(backEnd.loadGroups(), backEnd.loadUsers(), permsversion); backEnd.load(); BungeePerms.getInstance().getNetworkNotifier().reloadAll(null); return res; } /** * Adds the given group to the user. * * @param user the user to add the group to * @param group the group to add to the user */ public void addUserGroup(User user, Group group) { //cache user.getGroups().add(group); Collections.sort(user.getGroups()); //database backEnd.saveUserGroups(user); //recalc perms user.recalcPerms(); //send bukkit update info BungeePerms.getInstance().getNetworkNotifier().reloadUser(user, null); } /** * Removes the given group from the user. * * @param user the user to remove the group from * @param group the group to remove from the user */ public void removeUserGroup(User user, Group group) { //cache user.getGroups().remove(group); Collections.sort(user.getGroups()); //database backEnd.saveUserGroups(user); //recalc perms user.recalcPerms(); //send bukkit update info BungeePerms.getInstance().getNetworkNotifier().reloadUser(user, null); } public void addUserPerm(User user, String perm) { //cache user.getExtraPerms().add(perm.toLowerCase()); //database backEnd.saveUserPerms(user); //recalc perms user.recalcPerms(); //send bukkit update info BungeePerms.getInstance().getNetworkNotifier().reloadUser(user, null); } public void removeUserPerm(User user, String perm) { //cache user.getExtraPerms().remove(perm.toLowerCase()); //database backEnd.saveUserPerms(user); //recalc perms user.recalcPerms(); //send bukkit update info BungeePerms.getInstance().getNetworkNotifier().reloadUser(user, null); } public void addUserPerServerPerm(User user, String server, String perm) { //cache Server srv = user.getServer(server); srv.getPerms().add(perm.toLowerCase()); //database backEnd.saveUserPerServerPerms(user, server.toLowerCase()); //recalc perms user.recalcPerms(server.toLowerCase()); //send bukkit update info BungeePerms.getInstance().getNetworkNotifier().reloadUser(user, null); } public void removeUserPerServerPerm(User user, String server, String perm) { //cache Server srv = user.getServer(server); srv.getPerms().remove(perm.toLowerCase()); //database backEnd.saveUserPerServerPerms(user, server); //recalc perms user.recalcPerms(server); //send bukkit update info BungeePerms.getInstance().getNetworkNotifier().reloadUser(user, null); } public void addUserPerServerWorldPerm(User user, String server, String world, String perm) { //cache Server srv = user.getServer(server); World w = srv.getWorld(world); w.getPerms().add(perm.toLowerCase()); //database backEnd.saveUserPerServerWorldPerms(user, server, world); //recalc perms user.recalcPerms(server, world); //send bukkit update info BungeePerms.getInstance().getNetworkNotifier().reloadUser(user, null); } public void removeUserPerServerWorldPerm(User user, String server, String world, String perm) { //cache Server srv = user.getServer(server); World w = srv.getWorld(world); w.getPerms().remove(perm.toLowerCase()); //database backEnd.saveUserPerServerWorldPerms(user, server, world); //recalc perms user.recalcPerms(server, world); //send bukkit update info BungeePerms.getInstance().getNetworkNotifier().reloadUser(user, null); } /** * Sets the displayname of the group * * @param user * @param display * @param server * @param world */ public void setUserDisplay(User user, String display, String server, String world) { //cache if (server == null) { user.setDisplay(display); } else if (world == null) { user.getServer(server).setDisplay(display); } else { user.getServer(server).getWorld(world).setDisplay(display); } //database backEnd.saveUserDisplay(user, server, world); //send bukkit update info BungeePerms.getInstance().getNetworkNotifier().reloadUser(user, null); } /** * Sets the prefix for the group. * * @param user * @param prefix * @param server * @param world */ public void setUserPrefix(User user, String prefix, String server, String world) { //cache if (server == null) { user.setPrefix(prefix); } else if (world == null) { user.getServer(server).setPrefix(prefix); } else { user.getServer(server).getWorld(world).setPrefix(prefix); } //database backEnd.saveUserPrefix(user, server, world); //send bukkit update info BungeePerms.getInstance().getNetworkNotifier().reloadUser(user, null); } /** * Sets the suffix for the group. * * @param user * @param suffix * @param server * @param world */ public void setUserSuffix(User user, String suffix, String server, String world) { //cache if (server == null) { user.setSuffix(suffix); } else if (world == null) { user.getServer(server).setSuffix(suffix); } else { user.getServer(server).getWorld(world).setSuffix(suffix); } //database backEnd.saveUserSuffix(user, server, world); //send bukkit update info BungeePerms.getInstance().getNetworkNotifier().reloadUser(user, null); } public void addGroupPerm(Group group, String perm) { //cache group.getPerms().add(perm.toLowerCase()); //database backEnd.saveGroupPerms(group); //recalc perms for (Group g : groups) { g.recalcPerms(); } for (User u : users) { u.recalcPerms(); } //send bukkit update info BungeePerms.getInstance().getNetworkNotifier().reloadGroup(group, null); } public void removeGroupPerm(Group group, String perm) { //cache group.getPerms().remove(perm.toLowerCase()); //database backEnd.saveGroupPerms(group); //recalc perms for (Group g : groups) { g.recalcPerms(); } for (User u : users) { u.recalcPerms(); } //send bukkit update info BungeePerms.getInstance().getNetworkNotifier().reloadGroup(group, null); } public void addGroupPerServerPerm(Group group, String server, String perm) { //cache Server srv = group.getServer(server); srv.getPerms().add(perm.toLowerCase()); //database backEnd.saveGroupPerServerPerms(group, server); //recalc perms for (Group g : groups) { g.recalcPerms(server); } for (User u : users) { u.recalcPerms(); } //send bukkit update info BungeePerms.getInstance().getNetworkNotifier().reloadGroup(group, null); } public void removeGroupPerServerPerm(Group group, String server, String perm) { //cache Server srv = group.getServer(server); srv.getPerms().remove(perm.toLowerCase()); //database backEnd.saveGroupPerServerPerms(group, server); //recalc perms for (Group g : groups) { g.recalcPerms(server); } for (User u : users) { u.recalcPerms(); } //send bukkit update info BungeePerms.getInstance().getNetworkNotifier().reloadGroup(group, null); } public void addGroupPerServerWorldPerm(Group group, String server, String world, String perm) { //cache Server srv = group.getServer(server); World w = srv.getWorld(world); w.getPerms().add(perm.toLowerCase()); //database backEnd.saveGroupPerServerWorldPerms(group, server, world); //recalc perms for (Group g : groups) { g.recalcPerms(server, world); } for (User u : users) { u.recalcPerms(); } //send bukkit update info BungeePerms.getInstance().getNetworkNotifier().reloadGroup(group, null); } public void removeGroupPerServerWorldPerm(Group group, String server, String world, String perm) { //cache Server srv = group.getServer(server); World w = srv.getWorld(world); w.getPerms().remove(perm.toLowerCase()); //database backEnd.saveGroupPerServerWorldPerms(group, server, world); //recalc perms for (Group g : groups) { g.recalcPerms(server, world); } for (User u : users) { u.recalcPerms(); } //send bukkit update info BungeePerms.getInstance().getNetworkNotifier().reloadGroup(group, null); } /** * Adds the toadd group to the group as inheritance * * @param group the group which should inherit * @param toadd the group which should be inherited */ public void addGroupInheritance(Group group, Group toadd) { //cache group.getInheritances().add(toadd.getName()); Collections.sort(group.getInheritances()); //database backEnd.saveGroupInheritances(group); //recalc perms for (Group g : groups) { g.recalcPerms(); } for (User u : users) { u.recalcPerms(); } //send bukkit update info BungeePerms.getInstance().getNetworkNotifier().reloadGroup(group, null); } /** * Removes the toremove group from the group as inheritance * * @param group the group which should no longer inherit * @param toremove the group which should no longer be inherited */ public void removeGroupInheritance(Group group, Group toremove) { //cache group.getInheritances().remove(toremove.getName()); Collections.sort(group.getInheritances()); //database backEnd.saveGroupInheritances(group); //recalc perms for (Group g : groups) { g.recalcPerms(); } for (User u : users) { u.recalcPerms(); } //send bukkit update info BungeePerms.getInstance().getNetworkNotifier().reloadGroup(group, null); } /** * Set the ladder for the group. * * @param group * @param ladder */ public void ladderGroup(Group group, String ladder) { //cache group.setLadder(ladder); //database backEnd.saveGroupLadder(group); //send bukkit update info BungeePerms.getInstance().getNetworkNotifier().reloadGroup(group, null); } /** * Sets the rank for the group. * * @param group * @param rank */ public void rankGroup(Group group, int rank) { //cache group.setRank(rank); Collections.sort(groups); //database backEnd.saveGroupRank(group); //send bukkit update info BungeePerms.getInstance().getNetworkNotifier().reloadGroup(group, null); } /** * Sets the weight for the group. * * @param group * @param weight */ public void weightGroup(Group group, int weight) { //cache group.setWeight(weight); Collections.sort(groups); //database backEnd.saveGroupWeight(group); //send bukkit update info BungeePerms.getInstance().getNetworkNotifier().reloadGroup(group, null); } /** * Sets if the the group is a default group. * * @param group * @param isdefault */ public void setGroupDefault(Group group, boolean isdefault) { //cache group.setIsdefault(isdefault); //database backEnd.saveGroupDefault(group); //send bukkit update info BungeePerms.getInstance().getNetworkNotifier().reloadGroup(group, null); } /** * Sets the displayname of the group * * @param group * @param display * @param server * @param world */ public void setGroupDisplay(Group group, String display, String server, String world) { //cache if (server == null) { group.setDisplay(display); } else if (world == null) { group.getServer(server).setDisplay(display); } else { group.getServer(server).getWorld(world).setDisplay(display); } //database backEnd.saveGroupDisplay(group, server, world); //send bukkit update info BungeePerms.getInstance().getNetworkNotifier().reloadGroup(group, null); } /** * Sets the prefix for the group. * * @param group * @param prefix * @param server * @param world */ public void setGroupPrefix(Group group, String prefix, String server, String world) { //cache if (server == null) { group.setPrefix(prefix); } else if (world == null) { group.getServer(server).setPrefix(prefix); } else { group.getServer(server).getWorld(world).setPrefix(prefix); } //database backEnd.saveGroupPrefix(group, server, world); //send bukkit update info BungeePerms.getInstance().getNetworkNotifier().reloadGroup(group, null); } /** * Sets the suffix for the group. * * @param group * @param suffix * @param server * @param world */ public void setGroupSuffix(Group group, String suffix, String server, String world) { //cache if (server == null) { group.setSuffix(suffix); } else if (world == null) { group.getServer(server).setSuffix(suffix); } else { group.getServer(server).getWorld(world).setSuffix(suffix); } //database backEnd.saveGroupSuffix(group, server, world); //send bukkit update info BungeePerms.getInstance().getNetworkNotifier().reloadGroup(group, null); } public synchronized void migrateBackEnd(BackEndType bet) { if (bet == null) { throw new NullPointerException("bet must not be null"); } Migrator migrator = null; if (bet == BackEndType.MySQL2) { migrator = new Migrate2MySQL2(config, debug); } else if (bet == BackEndType.MySQL) { migrator = new Migrate2MySQL(config, debug); } else if (bet == BackEndType.YAML) { migrator = new Migrate2YAML(config); } if (migrator == null) { throw new UnsupportedOperationException("bet==" + bet.name()); } migrator.migrate(backEnd.loadGroups(), backEnd.loadUsers(), permsversion); backEnd.load(); } public void migrateUseUUID(Map<String, UUID> uuids) { List<Group> groups = backEnd.loadGroups(); List<User> users = backEnd.loadUsers(); int version = backEnd.loadVersion(); BungeePerms.getInstance().getConfig().setUseUUIDs(true); backEnd.clearDatabase(); for (Group g : groups) { backEnd.saveGroup(g, false); } for (User u : users) { UUID uuid = uuids.get(u.getName()); if (uuid != null) { u.setUUID(uuid); backEnd.saveUser(u, false); } } backEnd.saveVersion(version, true); } public void migrateUsePlayerNames(Map<UUID, String> playernames) { List<Group> groups = backEnd.loadGroups(); List<User> users = backEnd.loadUsers(); int version = backEnd.loadVersion(); BungeePerms.getInstance().getConfig().setUseUUIDs(false); backEnd.clearDatabase(); for (Group g : groups) { backEnd.saveGroup(g, false); } for (User u : users) { String playername = playernames.get(u.getUUID()); if (playername != null) { u.setName(playername); backEnd.saveUser(u, false); } } backEnd.saveVersion(version, true); } /** * Converts the backend of the database holding the UUIDs and their corresponding player names to the new backend. * * @param type the new backend type */ public void migrateUUIDPlayerDB(UUIDPlayerDBType type) { Map<UUID, String> map = UUIDPlayerDB.getAll(); if (type == UUIDPlayerDBType.None) { UUIDPlayerDB = new NoneUUIDPlayerDB(); } else if (type == UUIDPlayerDBType.YAML) { UUIDPlayerDB = new YAMLUUIDPlayerDB(); } else if (type == UUIDPlayerDBType.MySQL) { UUIDPlayerDB = new MySQLUUIDPlayerDB(); } else { throw new UnsupportedOperationException("type==" + type); } BungeePerms.getInstance().getConfig().setUUIDPlayerDB(UUIDPlayerDB.getType()); UUIDPlayerDB.clear(); for (Map.Entry<UUID, String> e : map.entrySet()) { UUIDPlayerDB.update(e.getKey(), e.getValue()); } } //internal functions public void reloadUser(String user) { User u = getUser(user); if (u == null) { debug.log("User " + user + " not found!!!"); return; } backEnd.reloadUser(u); u.recalcPerms(); } public void reloadUser(UUID uuid) { User u = getUser(uuid); if (u == null) { debug.log("User " + uuid + " not found!!!"); return; } backEnd.reloadUser(u); u.recalcPerms(); } public void reloadGroup(String group) { Group g = getGroup(group); if (g == null) { debug.log("Group " + group + " not found!!!"); return; } backEnd.reloadGroup(g); Collections.sort(groups); for (Group gr : groups) { gr.recalcPerms(); } for (User u : users) { u.recalcPerms(); } } public void reloadUsers() { for (User u : users) { backEnd.reloadUser(u); u.recalcPerms(); } } public void reloadGroups() { for (Group g : groups) { backEnd.reloadGroup(g); } Collections.sort(groups); for (Group g : groups) { g.recalcPerms(); } for (User u : users) { u.recalcPerms(); } } public void addUserToCache(User u) { users.add(u); } public void removeUserFromCache(User u) { users.remove(u); } public void addGroupToCache(Group g) { groups.add(g); } public void removeGroupFromCache(Group g) { groups.remove(g); } }
package net.fortuna.ical4j.connector.dav; public abstract class PathResolver { public static final PathResolver CHANDLER = new ChandlerPathResolver(); public static final PathResolver CGP = new CgpPathResolver(); public static final PathResolver KMS = new KmsPathResolver(); public static final PathResolver ZIMBRA = new ZimbraPathResolver(); /** * Resolves the path component for a user's calendar store URL. * @return */ public abstract String getUserPath(String username); /** * Resolves the path component for a principal URL. * @return */ public abstract String getPrincipalPath(String username); private static class ChandlerPathResolver extends PathResolver { /* (non-Javadoc) * @see net.fortuna.ical4j.connector.dav.PathResolver#getPrincipalPath(java.lang.String) */ @Override public String getPrincipalPath(String username) { return "/chandler/dav/users/" + username; } /* (non-Javadoc) * @see net.fortuna.ical4j.connector.dav.PathResolver#getUserPath(java.lang.String) */ @Override public String getUserPath(String username) { return "/chandler/dav/" + username; } } private static class CgpPathResolver extends PathResolver { /* (non-Javadoc) * @see net.fortuna.ical4j.connector.dav.PathResolver#getPrincipalPath(java.lang.String) */ @Override public String getPrincipalPath(String username) { return "/CalDAV/"; } /* (non-Javadoc) * @see net.fortuna.ical4j.connector.dav.PathResolver#getUserPath(java.lang.String) */ @Override public String getUserPath(String arg0) { // TODO Auto-generated method stub return null; } } private static class KmsPathResolver extends PathResolver { /* (non-Javadoc) * @see net.fortuna.ical4j.connector.dav.PathResolver#getPrincipalPath(java.lang.String) */ @Override public String getPrincipalPath(String username) { return "/caldav/"; } /* (non-Javadoc) * @see net.fortuna.ical4j.connector.dav.PathResolver#getUserPath(java.lang.String) */ @Override public String getUserPath(String arg0) { // TODO Auto-generated method stub return null; } } private static class ZimbraPathResolver extends PathResolver { /* (non-Javadoc) * @see net.fortuna.ical4j.connector.dav.PathResolver#getPrincipalPath(java.lang.String) */ @Override public String getPrincipalPath(String username) { return "/principals/users/" + username + "/"; } /* (non-Javadoc) * @see net.fortuna.ical4j.connector.dav.PathResolver#getUserPath(java.lang.String) */ @Override public String getUserPath(String username) { return "/dav/" + username; } } }
package net.minecraftforge.gradle.user; import static net.minecraftforge.gradle.common.Constants.FERNFLOWER; import static net.minecraftforge.gradle.common.Constants.JAR_CLIENT_FRESH; import static net.minecraftforge.gradle.common.Constants.JAR_MERGED; import static net.minecraftforge.gradle.common.Constants.JAR_SERVER_FRESH; import static net.minecraftforge.gradle.user.UserConstants.*; import groovy.lang.Closure; import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import joptsimple.internal.Strings; import net.minecraftforge.gradle.common.BasePlugin; import net.minecraftforge.gradle.common.Constants; import net.minecraftforge.gradle.delayed.DelayedFile; import net.minecraftforge.gradle.json.JsonFactory; import net.minecraftforge.gradle.tasks.*; import net.minecraftforge.gradle.tasks.abstractutil.ExtractTask; import net.minecraftforge.gradle.tasks.user.SourceCopyTask; import net.minecraftforge.gradle.tasks.user.reobf.ArtifactSpec; import net.minecraftforge.gradle.tasks.user.reobf.ReobfTask; import org.gradle.api.Action; import org.gradle.api.DefaultTask; import org.gradle.api.Project; import org.gradle.api.Task; import org.gradle.api.XmlProvider; import org.gradle.api.artifacts.Configuration.State; import org.gradle.api.artifacts.dsl.DependencyHandler; import org.gradle.api.execution.TaskExecutionGraph; import org.gradle.api.internal.ConventionTask; import org.gradle.api.internal.plugins.DslObject; import org.gradle.api.logging.Logger; import org.gradle.api.plugins.JavaPluginConvention; import org.gradle.api.specs.Spec; import org.gradle.api.tasks.GroovySourceSet; import org.gradle.api.tasks.JavaExec; import org.gradle.api.tasks.ScalaSourceSet; import org.gradle.api.tasks.SourceSet; import org.gradle.api.tasks.Sync; import org.gradle.api.tasks.bundling.Jar; import org.gradle.api.tasks.bundling.Zip; import org.gradle.api.tasks.compile.GroovyCompile; import org.gradle.api.tasks.compile.JavaCompile; import org.gradle.api.tasks.scala.ScalaCompile; import org.gradle.plugins.ide.idea.model.IdeaModel; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import com.google.common.base.Joiner; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableMap; import com.google.common.io.Files; public abstract class UserBasePlugin<T extends UserExtension> extends BasePlugin<T> { @SuppressWarnings("serial") @Override public void applyPlugin() { this.applyExternalPlugin("java"); this.applyExternalPlugin("maven"); this.applyExternalPlugin("eclipse"); this.applyExternalPlugin("idea"); hasScalaBefore = project.getPlugins().hasPlugin("scala"); hasGroovyBefore = project.getPlugins().hasPlugin("groovy"); addGitIgnore(); //Morons -.- configureDeps(); configureCompilation(); configureIntellij(); // create basic tasks. tasks(); // create lifecycle tasks. Task task = makeTask("setupCIWorkspace", DefaultTask.class); task.dependsOn("genSrgs", "deobfBinJar"); task.setDescription("Sets up the bare minimum to build a minecraft mod. Idea for CI servers"); task.setGroup("ForgeGradle"); //configureCISetup(task); task = makeTask("setupDevWorkspace", DefaultTask.class); task.dependsOn("genSrgs", "deobfBinJar", "makeStart"); task.setDescription("CIWorkspace + natives and assets to run and test Minecraft"); task.setGroup("ForgeGradle"); //configureDevSetup(task); task = makeTask("setupDecompWorkspace", DefaultTask.class); task.dependsOn("genSrgs", "makeStart", "repackMinecraft"); task.setDescription("DevWorkspace + the deobfuscated Minecraft source linked as a source jar."); task.setGroup("ForgeGradle"); //configureDecompSetup(task); project.getGradle().getTaskGraph().whenReady(new Closure<Object>(this, null) { @Override public Object call() { TaskExecutionGraph graph = project.getGradle().getTaskGraph(); String path = project.getPath(); if (graph.hasTask(path + "setupDecompWorkspace")) { getExtension().setDecomp(); setMinecraftDeps(true, true); } return null; } @Override public Object call(Object obj) { return call(); } @Override public Object call(Object... obj) { return call(); } }); } private boolean hasAppliedJson = false; private boolean hasScalaBefore = false; private boolean hasGroovyBefore = false; /** * may not include delayed tokens. */ public abstract String getApiName(); /** * Name of the source dependency. eg: forgeSrc * may not include delayed tokens. */ protected abstract String getSrcDepName(); /** * Name of the source dependency. eg: forgeBin * may not include delayed tokens. */ protected abstract String getBinDepName(); /** * May invoke the extension object, or be hardcoded. * may not include delayed tokens. */ protected abstract boolean hasApiVersion(); /** * May invoke the extension object, or be hardcoded. * may not include delayed tokens. */ protected abstract String getApiVersion(T exten); /** * May invoke the extension object, or be hardcoded. * may not include delayed tokens. */ protected abstract String getMcVersion(T exten); /** * May invoke the extension object, or be hardcoded. * This unlike the others, is evaluated as a delayed file, and may contain various tokens including: * {API_NAME} {API_VERSION} {MC_VERSION} */ protected abstract String getApiCacheDir(T exten); /** * May invoke the extension object, or be hardcoded. * This unlike the others, is evaluated as a delayed file, and may contain various tokens including: * {API_NAME} {API_VERSION} {MC_VERSION} */ protected abstract String getSrgCacheDir(T exten); /** * May invoke the extension object, or be hardcoded. * This unlike the others, is evaluated as a delayed file, and may contain various tokens including: * {API_NAME} {API_VERSION} {MC_VERSION} */ protected abstract String getUserDevCacheDir(T exten); /** * This unlike the others, is evaluated as a delayed string, and may contain various tokens including: * {API_NAME} {API_VERSION} {MC_VERSION} */ protected abstract String getUserDev(); /** * For run configurations. Is delayed. */ protected abstract String getClientTweaker(); /** * For run configurations. Is delayed. */ protected abstract String getServerTweaker(); /** * For run configurations */ protected abstract String getStartDir(); /** * For run configurations. Is delayed. */ protected abstract String getClientRunClass(); /** * For run configurations */ protected abstract Iterable<String> getClientRunArgs(); /** * For run configurations. Is delayed. */ protected abstract String getServerRunClass(); /** * For run configurations */ protected abstract Iterable<String> getServerRunArgs(); // protected abstract void configureCISetup(Task task); // protected abstract void configureDevSetup(Task task); // protected abstract void configureDecompSetup(Task task); @Override public String resolve(String pattern, Project project, T exten) { pattern = super.resolve(pattern, project, exten); pattern = pattern.replace("{MCP_DATA_DIR}", CONF_DIR); pattern = pattern.replace("{USER_DEV}", this.getUserDevCacheDir(exten)); pattern = pattern.replace("{SRG_DIR}", this.getSrgCacheDir(exten)); pattern = pattern.replace("{API_CACHE_DIR}", this.getApiCacheDir(exten)); pattern = pattern.replace("{MC_VERSION}", getMcVersion(exten)); // do run config stuff. pattern = pattern.replace("{RUN_CLIENT_TWEAKER}", getClientTweaker()); pattern = pattern.replace("{RUN_SERVER_TWEAKER}", getServerTweaker()); pattern = pattern.replace("{RUN_BOUNCE_CLIENT}", getClientRunClass()); pattern = pattern.replace("{RUN_BOUNCE_SERVER}", getServerRunClass()); if (!exten.mappingsSet()) { // no mappings set?remove these tokens pattern = pattern.replace("{MAPPING_CHANNEL}", ""); pattern = pattern.replace("{MAPPING_VERSION}", ""); } if (hasApiVersion()) pattern = pattern.replace("{API_VERSION}", getApiVersion(exten)); pattern = pattern.replace("{API_NAME}", getApiName()); return pattern; } protected void configureDeps() { // create configs project.getConfigurations().create(CONFIG_USERDEV); project.getConfigurations().create(CONFIG_NATIVES); project.getConfigurations().create(CONFIG_START); project.getConfigurations().create(CONFIG_DEPS); project.getConfigurations().create(CONFIG_MC); // special userDev stuff ExtractConfigTask extractUserDev = makeTask("extractUserDev", ExtractConfigTask.class); extractUserDev.setOut(delayedFile("{USER_DEV}")); extractUserDev.setConfig(CONFIG_USERDEV); extractUserDev.setDoesCache(true); extractUserDev.dependsOn("getVersionJson"); extractUserDev.doLast(new Action<Task>() { @Override public void execute(Task arg0) { readAndApplyJson(getDevJson().call(), CONFIG_DEPS, CONFIG_NATIVES, arg0.getLogger()); } }); project.getTasks().findByName("getAssetsIndex").dependsOn("extractUserDev"); // special native stuff ExtractConfigTask extractNatives = makeTask("extractNatives", ExtractConfigTask.class); extractNatives.setOut(delayedFile(NATIVES_DIR)); extractNatives.setConfig(CONFIG_NATIVES); /** * This mod adds the API sourceSet, and correctly configures the */ protected void configureCompilation() { // get conventions JavaPluginConvention javaConv = (JavaPluginConvention) project.getConvention().getPlugins().get("java"); SourceSet main = javaConv.getSourceSets().getByName(SourceSet.MAIN_SOURCE_SET_NAME); SourceSet test = javaConv.getSourceSets().getByName(SourceSet.TEST_SOURCE_SET_NAME); SourceSet api = javaConv.getSourceSets().create("api"); // set the Source javaConv.setSourceCompatibility("1.6"); javaConv.setTargetCompatibility("1.6"); main.setCompileClasspath(main.getCompileClasspath().plus(api.getOutput())); test.setCompileClasspath(test.getCompileClasspath().plus(api.getOutput())); project.getConfigurations().getByName("apiCompile").extendsFrom(project.getConfigurations().getByName("compile")); project.getConfigurations().getByName("testCompile").extendsFrom(project.getConfigurations().getByName("apiCompile")); } private void readAndApplyJson(File file, String depConfig, String nativeConfig, Logger log) { if (version == null) { try { version = JsonFactory.loadVersion(file, delayedFile(Constants.JSONS_DIR).call()); } catch (Exception e) { log.error("" + file + " could not be parsed"); Throwables.propagate(e); } } if (hasAppliedJson) return; // apply the dep info. DependencyHandler handler = project.getDependencies(); // actual dependencies if (project.getConfigurations().getByName(depConfig).getState() == State.UNRESOLVED) { for (net.minecraftforge.gradle.json.version.Library lib : version.getLibraries()) { if (lib.natives == null) handler.add(depConfig, lib.getArtifactName()); } } else log.info("RESOLVED: " + depConfig); // the natives if (project.getConfigurations().getByName(nativeConfig).getState() == State.UNRESOLVED) { for (net.minecraftforge.gradle.json.version.Library lib : version.getLibraries()) { if (lib.natives != null) handler.add(nativeConfig, lib.getArtifactName()); } } else log.info("RESOLVED: " + nativeConfig); hasAppliedJson = true; } @SuppressWarnings("serial") protected void configureIntellij() { IdeaModel ideaConv = (IdeaModel) project.getExtensions().getByName("idea"); ideaConv.getModule().getExcludeDirs().addAll(project.files(".gradle", "build", ".idea").getFiles()); ideaConv.getModule().setDownloadJavadoc(true); ideaConv.getModule().setDownloadSources(true); Task task = makeTask("genIntellijRuns", DefaultTask.class); task.doLast(new Action<Task>() { @Override public void execute(Task task) { try { String module = task.getProject().getProjectDir().getCanonicalPath(); File root = task.getProject().getProjectDir().getCanonicalFile(); File file = null; while (file == null && !root.equals(task.getProject().getRootProject().getProjectDir().getCanonicalFile().getParentFile())) { file = new File(root, ".idea/workspace.xml"); if (!file.exists()) { file = null; // find iws file for (File f : root.listFiles()) { if (f.isFile() && f.getName().endsWith(".iws")) { file = f; break; } } } root = root.getParentFile(); } if (file == null || !file.exists()) throw new RuntimeException("Intellij workspace file could not be found! are you sure you imported the project into intellij?"); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(file); injectIntellijRuns(doc, module); // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(file); //StreamResult result = new StreamResult(System.out); transformer.transform(source, result); } catch (Exception e) { e.printStackTrace(); } } }); if (ideaConv.getWorkspace().getIws() == null) return; ideaConv.getWorkspace().getIws().withXml(new Closure<Object>(this, null) { public Object call(Object... obj) { Element root = ((XmlProvider) this.getDelegate()).asElement(); Document doc = root.getOwnerDocument(); try { injectIntellijRuns(doc, project.getProjectDir().getCanonicalPath()); } catch (Exception e) { e.printStackTrace(); } return null; } }); } public final void injectIntellijRuns(Document doc, String module) throws DOMException, IOException { Element root = null; { NodeList list = doc.getElementsByTagName("component"); for (int i = 0; i < list.getLength(); i++) { Element e = (Element) list.item(i); if ("RunManager".equals(e.getAttribute("name"))) { root = e; break; } } } String[][] config = new String[][] { new String[] { "Minecraft Client", GRADLE_START_CLIENT, "-Xincgc -Xmx1024M -Xms1024M", Joiner.on(' ').join(getClientRunArgs()) }, new String[] { "Minecraft Server", GRADLE_START_SERVER, "-Xincgc -Dfml.ignoreInvalidMinecraftCertificates=true", Joiner.on(' ').join(getServerRunArgs()) } }; for (String[] data : config) { Element child = add(root, "configuration", "default", "false", "name", data[0], "type", "Application", "factoryName", "Application", "default", "false"); add(child, "extension", "name", "coverage", "enabled", "false", "sample_coverage", "true", "runner", "idea"); add(child, "option", "name", "MAIN_CLASS_NAME", "value", data[1]); add(child, "option", "name", "VM_PARAMETERS", "value", data[2]); add(child, "option", "name", "PROGRAM_PARAMETERS", "value", data[3]); add(child, "option", "name", "WORKING_DIRECTORY", "value", "file://" + delayedFile("{RUN_DIR}").call().getCanonicalPath().replace(module, "$PROJECT_DIR$")); add(child, "option", "name", "ALTERNATIVE_JRE_PATH_ENABLED", "value", "false"); add(child, "option", "name", "ALTERNATIVE_JRE_PATH", "value", ""); add(child, "option", "name", "ENABLE_SWING_INSPECTOR", "value", "false"); add(child, "option", "name", "ENV_VARIABLES"); add(child, "option", "name", "PASS_PARENT_ENVS", "value", "true"); add(child, "module", "name", ((IdeaModel) project.getExtensions().getByName("idea")).getModule().getName()); add(child, "envs"); add(child, "RunnerSettings", "RunnerId", "Run"); add(child, "ConfigurationWrapper", "RunnerId", "Run"); add(child, "method"); } File f = delayedFile("{RUN_DIR}").call(); if (!f.exists()) f.mkdirs(); } private Element add(Element parent, String name, String... values) { Element e = parent.getOwnerDocument().createElement(name); for (int x = 0; x < values.length; x += 2) { e.setAttribute(values[x], values[x + 1]); } parent.appendChild(e); return e; } private void tasks() { { GenSrgTask task = makeTask("genSrgs", GenSrgTask.class); task.setInSrg(delayedFile(PACKAGED_SRG)); task.setInExc(delayedFile(PACKAGED_EXC)); task.setMethodsCsv(delayedFile(METHOD_CSV)); task.setFieldsCsv(delayedFile(FIELD_CSV)); task.setNotchToSrg(delayedFile(DEOBF_SRG_SRG)); task.setNotchToMcp(delayedFile(DEOBF_MCP_SRG)); task.setMcpToSrg(delayedFile(REOBF_SRG)); task.setMcpToNotch(delayedFile(REOBF_NOTCH_SRG)); task.setSrgExc(delayedFile(EXC_SRG)); task.setMcpExc(delayedFile(EXC_MCP)); task.dependsOn("extractUserDev", "extractMcpData"); } { MergeJarsTask task = makeTask("mergeJars", MergeJarsTask.class); task.setClient(delayedFile(JAR_CLIENT_FRESH)); task.setServer(delayedFile(JAR_SERVER_FRESH)); task.setOutJar(delayedFile(JAR_MERGED)); task.setMergeCfg(delayedFile(MERGE_CFG)); task.setMcVersion(delayedString("{MC_VERSION}")); task.dependsOn("extractUserDev", "downloadClient", "downloadServer"); } { String name = getBinDepName() + "-" + (hasApiVersion() ? "{API_VERSION}" : "{MC_VERSION}") + ".jar"; ProcessJarTask task = makeTask("deobfBinJar", ProcessJarTask.class); task.setSrg(delayedFile(DEOBF_MCP_SRG)); task.setExceptorJson(delayedFile(EXC_JSON)); task.setExceptorCfg(delayedFile(EXC_MCP)); task.setFieldCsv(delayedFile(FIELD_CSV)); task.setMethodCsv(delayedFile(METHOD_CSV)); task.setInJar(delayedFile(JAR_MERGED)); task.setOutCleanJar(delayedFile("{API_CACHE_DIR}/" + MAPPING_APPENDAGE + name)); task.setOutDirtyJar(delayedFile(DIRTY_DIR + "/" + name)); task.setApplyMarkers(false); task.setStripSynthetics(true); configureDeobfuscation(task); task.dependsOn("downloadMcpTools", "mergeJars", "genSrgs"); } { String name = "{API_NAME}-" + (hasApiVersion() ? "{API_VERSION}" : "{MC_VERSION}") + "-"+ CLASSIFIER_DEOBF_SRG +".jar"; ProcessJarTask task = makeTask("deobfuscateJar", ProcessJarTask.class); task.setSrg(delayedFile(DEOBF_SRG_SRG)); task.setExceptorJson(delayedFile(EXC_JSON)); task.setExceptorCfg(delayedFile(EXC_SRG)); task.setInJar(delayedFile(JAR_MERGED)); task.setOutCleanJar(delayedFile("{API_CACHE_DIR}/" + name)); task.setOutDirtyJar(delayedFile(DIRTY_DIR + "/" + name)); task.setApplyMarkers(true); configureDeobfuscation(task); task.dependsOn("downloadMcpTools", "mergeJars", "genSrgs"); } { ReobfTask task = makeTask("reobf", ReobfTask.class); task.dependsOn("genSrgs"); task.setExceptorCfg(delayedFile(EXC_SRG)); task.setSrg(delayedFile(REOBF_SRG)); task.setFieldCsv(delayedFile(FIELD_CSV)); task.setFieldCsv(delayedFile(METHOD_CSV)); task.mustRunAfter("test"); project.getTasks().getByName("assemble").dependsOn(task); project.getTasks().getByName("uploadArchives").dependsOn(task); } // create start task and add it to the classpath and stuff { // create task CreateStartTask task = makeTask("makeStart", CreateStartTask.class); { task.setAssetIndex(delayedString("{ASSET_INDEX}").forceResolving()); task.setAssetsDir(delayedFile("{CACHE_DIR}/minecraft/assets")); task.setNativesDir(delayedFile(NATIVES_DIR)); task.setVersion(delayedString("{MC_VERSION}")); task.setClientTweaker(delayedString("{RUN_CLIENT_TWEAKER}")); task.setServerTweaker(delayedString("{RUN_SERVER_TWEAKER}")); task.setClientBounce(delayedString("{RUN_BOUNCE_CLIENT}")); task.setServerBounce(delayedString("{RUN_BOUNCE_SERVER}")); task.setStartOut(delayedFile(getStartDir())); task.dependsOn("extractUserDev", "getAssets", "getAssetsIndex", "copyNativesLegacy"); } } createPostDecompTasks(); createExecTasks(); createSourceCopyTasks(); } @SuppressWarnings({ "unchecked", "rawtypes" }) private final void createPostDecompTasks() { DelayedFile decompOut = delayedDirtyFile(null, CLASSIFIER_DECOMPILED, "jar", false); DelayedFile remapped = delayedDirtyFile(getSrcDepName(), CLASSIFIER_SOURCES, "jar"); final DelayedFile recomp = delayedDirtyFile(getSrcDepName(), null, "jar"); final DelayedFile recompSrc = delayedFile(RECOMP_SRC_DIR); final DelayedFile recompCls = delayedFile(RECOMP_CLS_DIR); DecompileTask decomp = makeTask("decompile", DecompileTask.class); { decomp.setInJar(delayedDirtyFile(null, CLASSIFIER_DEOBF_SRG, "jar", false)); decomp.setOutJar(decompOut); decomp.setFernFlower(delayedFile(FERNFLOWER)); decomp.setPatch(delayedFile(MCP_PATCH_DIR)); decomp.setAstyleConfig(delayedFile(ASTYLE_CFG)); decomp.dependsOn("downloadMcpTools", "deobfuscateJar", "genSrgs"); } // Remap to MCP names RemapSourcesTask remap = makeTask("remapJar", RemapSourcesTask.class); { remap.setInJar(decompOut); remap.setOutJar(remapped); remap.setFieldsCsv(delayedFile(FIELD_CSV)); remap.setMethodsCsv(delayedFile(METHOD_CSV)); remap.setParamsCsv(delayedFile(PARAM_CSV)); remap.setDoesJavadocs(true); remap.dependsOn(decomp); } Spec onlyIfCheck = new Spec() { @Override public boolean isSatisfiedBy(Object obj) { boolean didWork = ((Task) obj).dependsOnTaskDidWork(); boolean exists = recomp.call().exists(); if (!exists) return true; else return didWork; } }; ExtractTask extract = makeTask("extractMinecraftSrc", ExtractTask.class); { extract.from(remapped); extract.into(recompSrc); extract.setIncludeEmptyDirs(false); extract.setClean(true); extract.dependsOn(remap); extract.onlyIf(onlyIfCheck); } JavaCompile recompTask = makeTask("recompMinecraft", JavaCompile.class); { recompTask.setSource(recompSrc); recompTask.setSourceCompatibility("1.6"); recompTask.setTargetCompatibility("1.6"); recompTask.setClasspath(project.getConfigurations().getByName(CONFIG_DEPS)); recompTask.dependsOn(extract); recompTask.getOptions().setWarnings(false); recompTask.onlyIf(onlyIfCheck); } Jar repackageTask = makeTask("repackMinecraft", Jar.class); { repackageTask.from(recompSrc); repackageTask.from(recompCls); repackageTask.exclude("*.java", "**/*.java", "**.java"); repackageTask.dependsOn(recompTask); // file output configuration done in the delayed configuration. repackageTask.onlyIf(onlyIfCheck); } } @SuppressWarnings("serial") private class MakeDirExist extends Closure<Boolean> { DelayedFile path; MakeDirExist(DelayedFile path) { super(project); this.path = path; } @Override public Boolean call() { File f = path.call(); if (!f.exists()) f.mkdirs(); return true; } } @SuppressWarnings({ "unchecked", "rawtypes" }) private void createExecTasks() { JavaExec exec = makeTask("runClient", JavaExec.class); { exec.doFirst(new MakeDirExist(delayedFile("{RUN_DIR}"))); exec.setMain(GRADLE_START_CLIENT); //exec.jvmArgs("-Xincgc", "-Xmx1024M", "-Xms1024M", "-Dfml.ignoreInvalidMinecraftCertificates=true"); exec.args(getClientRunArgs()); exec.workingDir(delayedFile("{RUN_DIR}")); exec.setStandardOutput(System.out); exec.setErrorOutput(System.err); exec.setGroup("ForgeGradle"); exec.setDescription("Runs the Minecraft client"); exec.dependsOn("makeStart"); } exec = makeTask("runServer", JavaExec.class); { exec.doFirst(new MakeDirExist(delayedFile("{RUN_DIR}"))); exec.setMain(GRADLE_START_SERVER); exec.jvmArgs("-Xincgc", "-Dfml.ignoreInvalidMinecraftCertificates=true"); exec.workingDir(delayedFile("{RUN_DIR}")); exec.args(getServerRunArgs()); exec.setStandardOutput(System.out); exec.setStandardInput(System.in); exec.setErrorOutput(System.err); exec.setGroup("ForgeGradle"); exec.setDescription("Runs the Minecraft Server"); exec.dependsOn("makeStart"); } exec = makeTask("debugClient", JavaExec.class); { exec.doFirst(new MakeDirExist(delayedFile("{RUN_DIR}"))); exec.doFirst( new Action() { @Override public void execute(Object o) { project.getLogger().error(""); project.getLogger().error("THIS TASK WILL BE DEP RECATED SOON!"); project.getLogger().error("Instead use the runClient task, with the --debug-jvm option"); if (!project.getGradle().getGradleVersion().equals("1.12")) { project.getLogger().error("You may have to update to Gradle 1.12"); } project.getLogger().error(""); } }); exec.setMain(GRADLE_START_CLIENT); exec.jvmArgs("-Xincgc", "-Xmx1024M", "-Xms1024M", "-Dfml.ignoreInvalidMinecraftCertificates=true"); exec.args(getClientRunArgs()); exec.workingDir(delayedFile("{RUN_DIR}")); exec.setStandardOutput(System.out); exec.setErrorOutput(System.err); exec.setDebug(true); exec.setGroup("ForgeGradle"); exec.setDescription("Runs the Minecraft client in debug mode"); exec.dependsOn("makeStart"); } exec = makeTask("debugServer", JavaExec.class); { exec.doFirst(new MakeDirExist(delayedFile("{RUN_DIR}"))); exec.doFirst( new Action() { @Override public void execute(Object o) { project.getLogger().error(""); project.getLogger().error("THIS TASK WILL BE DEPRECATED SOON!"); project.getLogger().error("Instead use the runServer task, with the --debug-jvm option"); if (!project.getGradle().getGradleVersion().equals("1.12")) { project.getLogger().error("You may have to update to Gradle 1.12"); } project.getLogger().error(""); } }); exec.setMain(GRADLE_START_SERVER); exec.jvmArgs("-Xincgc", "-Dfml.ignoreInvalidMinecraftCertificates=true"); exec.workingDir(delayedFile("{RUN_DIR}")); exec.args(getServerRunArgs()); exec.setStandardOutput(System.out); exec.setStandardInput(System.in); exec.setErrorOutput(System.err); exec.setDebug(true); exec.setGroup("ForgeGradle"); exec.setDescription("Runs the Minecraft serevr in debug mode"); exec.dependsOn("makeStart"); } } private final void createSourceCopyTasks() { JavaPluginConvention javaConv = (JavaPluginConvention) project.getConvention().getPlugins().get("java"); SourceSet main = javaConv.getSourceSets().getByName(SourceSet.MAIN_SOURCE_SET_NAME); // do the special source moving... SourceCopyTask task; // main { DelayedFile dir = delayedFile(SOURCES_DIR + "/java"); task = makeTask("sourceMainJava", SourceCopyTask.class); task.setSource(main.getJava()); task.setOutput(dir); JavaCompile compile = (JavaCompile) project.getTasks().getByName(main.getCompileJavaTaskName()); compile.dependsOn("sourceMainJava"); compile.setSource(dir); } // scala!!! if (project.getPlugins().hasPlugin("scala")) { ScalaSourceSet set = (ScalaSourceSet) new DslObject(main).getConvention().getPlugins().get("scala"); DelayedFile dir = delayedFile(SOURCES_DIR + "/scala"); task = makeTask("sourceMainScala", SourceCopyTask.class); task.setSource(set.getScala()); task.setOutput(dir); ScalaCompile compile = (ScalaCompile) project.getTasks().getByName(main.getCompileTaskName("scala")); compile.dependsOn("sourceMainScala"); compile.setSource(dir); } // groovy!!! if (project.getPlugins().hasPlugin("groovy")) { GroovySourceSet set = (GroovySourceSet) new DslObject(main).getConvention().getPlugins().get("groovy"); DelayedFile dir = delayedFile(SOURCES_DIR + "/groovy"); task = makeTask("sourceMainGroovy", SourceCopyTask.class); task.setSource(set.getGroovy()); task.setOutput(dir); GroovyCompile compile = (GroovyCompile) project.getTasks().getByName(main.getCompileTaskName("groovy")); compile.dependsOn("sourceMainGroovy"); compile.setSource(dir); } } @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public final void afterEvaluate() { String mcversion = getMcVersion(getExtension()); if (!getExtension().mappingsSet() && mcversion.startsWith("1.8")) { getExtension().setMappings("snapshot_20141001"); //Default snapshots for 1.8 } super.afterEvaluate(); // version checks { String version = getMcVersion(getExtension()); if (hasApiVersion()) version = getApiVersion(getExtension()); doVersionChecks(version); } // ensure plugin application sequence.. groovy or scala or wtvr first, then the forge/fml/liteloader plugins if (!hasScalaBefore && project.getPlugins().hasPlugin("scala")) throw new RuntimeException(delayedString("You have applied the 'scala' plugin after '{API_NAME}', you must apply it before.").call()); if (!hasGroovyBefore && project.getPlugins().hasPlugin("groovy")) throw new RuntimeException(delayedString("You have applied the 'groovy' plugin after '{API_NAME}', you must apply it before.").call()); project.getDependencies().add(CONFIG_USERDEV, delayedString(getUserDev()).call() + ":userdev"); // grab the json && read dependencies if (getDevJson().call().exists()) { readAndApplyJson(getDevJson().call(), CONFIG_DEPS, CONFIG_NATIVES, project.getLogger()); } delayedTaskConfig(); // add MC repo. final String repoDir = delayedDirtyFile("this", "doesnt", "matter").call().getParentFile().getAbsolutePath(); project.allprojects(new Action<Project>() { public void execute(Project proj) { addFlatRepo(proj, getApiName()+"FlatRepo", repoDir); proj.getLogger().info("Adding repo to " + proj.getPath() + " >> " + repoDir); } }); // check for decompilation status.. has decompiled or not etc final File decompFile = delayedDirtyFile(getSrcDepName(), CLASSIFIER_SOURCES, "jar").call(); if (decompFile.exists()) { getExtension().setDecomp(); } // post decompile status thing. configurePostDecomp(getExtension().isDecomp()); { // stop getting empty dirs Action<ConventionTask> act = new Action() { @Override public void execute(Object arg0) { Zip task = (Zip) arg0; task.setIncludeEmptyDirs(false); } }; project.getTasks().withType(Jar.class, act); project.getTasks().withType(Zip.class, act); } } /** * Allows for the configuration of tasks in AfterEvaluate */ @SuppressWarnings({ "unchecked", "rawtypes" }) protected void delayedTaskConfig() { // add extraSRG lines to reobf task { ReobfTask task = ((ReobfTask) project.getTasks().getByName("reobf")); task.reobf(project.getTasks().getByName("jar"), new Action<ArtifactSpec>() { @Override public void execute(ArtifactSpec arg0) { JavaPluginConvention javaConv = (JavaPluginConvention) project.getConvention().getPlugins().get("java"); arg0.setClasspath(javaConv.getSourceSets().getByName("main").getCompileClasspath()); } }); task.setExtraSrg(getExtension().getSrgExtra()); } // configure output of recompile task { JavaCompile compile = (JavaCompile) project.getTasks().getByName("recompMinecraft"); compile.setDestinationDir(delayedFile(RECOMP_CLS_DIR).call()); } // configure output of repackage task. { Jar repackageTask = (Jar) project.getTasks().getByName("repackMinecraft"); final DelayedFile recomp = delayedDirtyFile(getSrcDepName(), null, "jar"); //done in the delayed configuration. File out = recomp.call(); repackageTask.setArchiveName(out.getName()); repackageTask.setDestinationDir(out.getParentFile()); } // Add the mod and stuff to the classpath of the exec tasks. final Jar jarTask = (Jar) project.getTasks().getByName("jar"); JavaExec exec = (JavaExec) project.getTasks().getByName("runClient"); { exec.classpath(project.getConfigurations().getByName("runtime")); exec.classpath(jarTask.getArchivePath()); exec.dependsOn(jarTask); } exec = (JavaExec) project.getTasks().getByName("runServer"); { exec.classpath(project.getConfigurations().getByName("runtime")); exec.classpath(jarTask.getArchivePath()); exec.dependsOn(jarTask); } exec = (JavaExec) project.getTasks().getByName("debugClient"); { exec.classpath(project.getConfigurations().getByName("runtime")); exec.classpath(jarTask.getArchivePath()); exec.dependsOn(jarTask); } exec = (JavaExec) project.getTasks().getByName("debugServer"); { exec.classpath(project.getConfigurations().getByName("runtime")); exec.classpath(jarTask.getArchivePath()); exec.dependsOn(jarTask); } // configure source replacement. for (SourceCopyTask t : project.getTasks().withType(SourceCopyTask.class)) { t.replace(getExtension().getReplacements()); t.include(getExtension().getIncludes()); } // use zinc for scala compilation project.getTasks().withType(ScalaCompile.class, new Action() { @Override public void execute(Object arg0) { ((ScalaCompile) arg0).getScalaCompileOptions().setUseAnt(false); } }); } /** * Configure tasks and stuff after you know if the decomp file exists or not. */ protected void configurePostDecomp(boolean decomp) { if (decomp) { ((ReobfTask) project.getTasks().getByName("reobf")).setDeobfFile(((ProcessJarTask) project.getTasks().getByName("deobfuscateJar")).getDelayedOutput()); ((ReobfTask) project.getTasks().getByName("reobf")).setRecompFile(delayedDirtyFile(getSrcDepName(), null, "jar")); } else { (project.getTasks().getByName("compileJava")).dependsOn("deobfBinJar"); (project.getTasks().getByName("compileApiJava")).dependsOn("deobfBinJar"); } setMinecraftDeps(decomp, false); } protected void setMinecraftDeps(boolean decomp, boolean remove) { String version = getMcVersion(getExtension()); if (hasApiVersion()) version = getApiVersion(getExtension()); if (decomp) { project.getDependencies().add(CONFIG_MC, ImmutableMap.of("name", getSrcDepName(), "version", version)); if (remove) { project.getConfigurations().getByName(CONFIG_MC).exclude(ImmutableMap.of("module", getBinDepName())); } } else { project.getDependencies().add(CONFIG_MC, ImmutableMap.of("name", getBinDepName(), "version", version)); if (remove) { project.getConfigurations().getByName(CONFIG_MC).exclude(ImmutableMap.of("module", getSrcDepName())); } } } /** * Add Forge/FML ATs here. * This happens during normal evaluation, and NOT AfterEvaluate. */ protected abstract void configureDeobfuscation(ProcessJarTask task); /** * * @param version may have pre-release suffix _pre# */ protected abstract void doVersionChecks(String version); /** * Returns a file in the DirtyDir if the deobfuscation task is dirty. Otherwise returns the cached one. * @param classifier * @param ext * @return */ protected DelayedFile delayedDirtyFile(final String name, final String classifier, final String ext) { return delayedDirtyFile(name, classifier, ext, true); } /** * Returns a file in the DirtyDir if the deobfuscation task is dirty. Otherwise returns the cached one. * @param classifier * @param ext * @return */ @SuppressWarnings("serial") protected DelayedFile delayedDirtyFile(final String name, final String classifier, final String ext, final boolean usesMappings) { return new DelayedFile(project, "", this) { @Override public File resolveDelayed() { ProcessJarTask decompDeobf = (ProcessJarTask) project.getTasks().getByName("deobfuscateJar"); pattern = (decompDeobf.isClean() ? "{API_CACHE_DIR}/"+(usesMappings ? MAPPING_APPENDAGE : "") : DIRTY_DIR) + "/"; if (!Strings.isNullOrEmpty(name)) pattern += name; else pattern += "{API_NAME}"; pattern += "-" + (hasApiVersion() ? "{API_VERSION}" : "{MC_VERSION}"); if (!Strings.isNullOrEmpty(classifier)) pattern+= "-"+classifier; if (!Strings.isNullOrEmpty(ext)) pattern+= "."+ext; return super.resolveDelayed(); } }; } /** * This extension object will have the name "minecraft" * @return */ @SuppressWarnings("unchecked") protected Class<T> getExtensionClass() { return (Class<T>) UserExtension.class; } private void addGitIgnore() { File git = new File(project.getBuildDir(), ".gitignore"); if (!git.exists()) { git.getParentFile().mkdir(); try { Files.write("#Seriously guys, stop commiting this to your git repo!\r\n*".getBytes(), git); } catch (IOException e){} } } }
package nl.hsac.fitnesse.fixture.slim.web; import fitnesse.slim.fixtureInteraction.FixtureInteraction; import nl.hsac.fitnesse.fixture.slim.SlimFixture; import nl.hsac.fitnesse.fixture.slim.SlimFixtureException; import nl.hsac.fitnesse.fixture.slim.StopTestException; import nl.hsac.fitnesse.fixture.slim.web.annotation.TimeoutPolicy; import nl.hsac.fitnesse.fixture.slim.web.annotation.WaitUntil; import nl.hsac.fitnesse.fixture.util.BinaryHttpResponse; import nl.hsac.fitnesse.fixture.util.FileUtil; import nl.hsac.fitnesse.fixture.util.HttpResponse; import nl.hsac.fitnesse.fixture.util.ReflectionHelper; import nl.hsac.fitnesse.fixture.util.selenium.ListItemBy; import nl.hsac.fitnesse.fixture.util.selenium.PageSourceSaver; import nl.hsac.fitnesse.fixture.util.selenium.SeleniumHelper; import nl.hsac.fitnesse.fixture.util.selenium.by.ContainerBy; import nl.hsac.fitnesse.fixture.util.selenium.by.GridBy; import nl.hsac.fitnesse.fixture.util.selenium.by.OptionBy; import nl.hsac.fitnesse.fixture.util.selenium.by.XPathBy; import nl.hsac.fitnesse.slim.interaction.ExceptionHelper; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.commons.text.StringEscapeUtils; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.Cookie; import org.openqa.selenium.Dimension; import org.openqa.selenium.Keys; import org.openqa.selenium.SearchContext; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.UnhandledAlertException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; import java.io.File; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.function.Function; import java.util.function.Supplier; public class BrowserTest<T extends WebElement> extends SlimFixture { private SeleniumHelper<T> seleniumHelper = getEnvironment().getSeleniumHelper(); private ReflectionHelper reflectionHelper = getEnvironment().getReflectionHelper(); private NgBrowserTest ngBrowserTest; private boolean implicitWaitForAngular = false; private boolean implicitFindInFrames = true; private int secondsBeforeTimeout; private int secondsBeforePageLoadTimeout; private int waitAfterScroll = 150; private String screenshotBase = new File(filesDir, "screenshots").getPath() + "/"; private String screenshotHeight = "200"; private String downloadBase = new File(filesDir, "downloads").getPath() + "/"; private String pageSourceBase = new File(filesDir, "pagesources").getPath() + "/"; @Override protected void beforeInvoke(Method method, Object[] arguments) { super.beforeInvoke(method, arguments); waitForAngularIfNeeded(method); } @Override protected Object invoke(FixtureInteraction interaction, Method method, Object[] arguments) throws Throwable { Object result; WaitUntil waitUntil = reflectionHelper.getAnnotation(WaitUntil.class, method); if (waitUntil == null) { result = superInvoke(interaction, method, arguments); } else { result = invokedWrappedInWaitUntil(waitUntil, interaction, method, arguments); } return result; } protected Object invokedWrappedInWaitUntil(WaitUntil waitUntil, FixtureInteraction interaction, Method method, Object[] arguments) { ExpectedCondition<Object> condition = webDriver -> { try { return superInvoke(interaction, method, arguments); } catch (Throwable e) { Throwable realEx = ExceptionHelper.stripReflectionException(e); if (realEx instanceof RuntimeException) { throw (RuntimeException) realEx; } else if (realEx instanceof Error) { throw (Error) realEx; } else { throw new RuntimeException(realEx); } } }; condition = wrapConditionForFramesIfNeeded(condition); Object result; switch (waitUntil.value()) { case STOP_TEST: result = waitUntilOrStop(condition); break; case RETURN_NULL: result = waitUntilOrNull(condition); break; case RETURN_FALSE: result = waitUntilOrNull(condition) != null; break; case THROW: default: result = waitUntil(condition); break; } return result; } protected Object superInvoke(FixtureInteraction interaction, Method method, Object[] arguments) throws Throwable { return super.invoke(interaction, method, arguments); } /** * Determines whether the current method might require waiting for angular given the currently open site, * and ensure it does if needed. * @param method */ protected void waitForAngularIfNeeded(Method method) { if (isImplicitWaitForAngularEnabled()) { try { if (ngBrowserTest == null) { ngBrowserTest = new NgBrowserTest(secondsBeforeTimeout()); ngBrowserTest.secondsBeforePageLoadTimeout(secondsBeforePageLoadTimeout()); } if (ngBrowserTest.requiresWaitForAngular(method) && currentSiteUsesAngular()) { try { ngBrowserTest.waitForAngularRequestsToFinish(); } catch (Exception e) { // if something goes wrong, just use normal behavior: continue to invoke() System.err.print("Found Angular, but encountered an error while waiting for it to be ready. "); e.printStackTrace(); } } } catch (UnhandledAlertException e) { System.err.println("Cannot determine whether Angular is present while alert is active."); } catch (Exception e) { // if something goes wrong, just use normal behavior: continue to invoke() System.err.print("Error while determining whether Angular is present. "); e.printStackTrace(); } } } protected boolean currentSiteUsesAngular() { Object windowHasAngular = getSeleniumHelper().executeJavascript("return window.angular?1:0;"); return Long.valueOf(1).equals(windowHasAngular); } @Override protected Throwable handleException(Method method, Object[] arguments, Throwable t) { Throwable result; if (t instanceof UnhandledAlertException) { UnhandledAlertException e = (UnhandledAlertException) t; String alertText = e.getAlertText(); if (alertText == null) { alertText = alertText(); } String msgBase = "Unhandled alert: alert must be confirmed or dismissed before test can continue. Alert text: " + alertText; String msg = getSlimFixtureExceptionMessage("alertException", msgBase, e); result = new StopTestException(false, msg, t); } else if (t instanceof SlimFixtureException) { result = super.handleException(method, arguments, t); } else { String msg = getSlimFixtureExceptionMessage("exception", null, t); result = new SlimFixtureException(false, msg, t); } return result; } public BrowserTest() { secondsBeforeTimeout(getEnvironment().getSeleniumDriverManager().getDefaultTimeoutSeconds()); ensureActiveTabIsNotClosed(); } public BrowserTest(int secondsBeforeTimeout) { secondsBeforeTimeout(secondsBeforeTimeout); ensureActiveTabIsNotClosed(); } public boolean open(String address) { String url = getUrl(address); try { getNavigation().to(url); } catch (TimeoutException e) { handleTimeoutException(e); } finally { switchToDefaultContent(); } waitUntil(webDriver -> { String readyState = getSeleniumHelper().executeJavascript("return document.readyState").toString(); // IE 7 is reported to return "loaded" boolean done = "complete".equalsIgnoreCase(readyState) || "loaded".equalsIgnoreCase(readyState); if (!done) { System.err.printf("Open of %s returned while document.readyState was %s", url, readyState); System.err.println(); } return done; }); return true; } public String location() { return driver().getCurrentUrl(); } public boolean back() { getNavigation().back(); switchToDefaultContent(); // firefox sometimes prevents immediate back, if previous page was reached via POST waitMilliseconds(500); WebElement element = findElement(By.id("errorTryAgain")); if (element != null) { element.click(); // don't use confirmAlert as this may be overridden in subclass and to get rid of the // firefox pop-up we need the basic behavior getSeleniumHelper().getAlert().accept(); } return true; } public boolean forward() { getNavigation().forward(); switchToDefaultContent(); return true; } public boolean refresh() { getNavigation().refresh(); switchToDefaultContent(); return true; } private WebDriver.Navigation getNavigation() { return getSeleniumHelper().navigate(); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public String alertText() { Alert alert = getAlert(); String text = null; if (alert != null) { text = alert.getText(); } return text; } @WaitUntil public boolean confirmAlert() { Alert alert = getAlert(); boolean result = false; if (alert != null) { alert.accept(); onAlertHandled(true); result = true; } return result; } @WaitUntil public boolean dismissAlert() { Alert alert = getAlert(); boolean result = false; if (alert != null) { alert.dismiss(); onAlertHandled(false); result = true; } return result; } /** * Called when an alert is either dismissed or accepted. * @param accepted true if the alert was accepted, false if dismissed. */ protected void onAlertHandled(boolean accepted) { // if we were looking in nested frames, we could not go back to original frame // because of the alert. Ensure we do so now the alert is handled. getSeleniumHelper().resetFrameDepthOnAlertError(); } protected Alert getAlert() { return getSeleniumHelper().getAlert(); } public boolean openInNewTab(String url) { String cleanUrl = getUrl(url); int tabCount = tabCount(); getSeleniumHelper().executeJavascript("window.open('%s', '_blank')", cleanUrl); // ensure new window is open waitUntil(webDriver -> tabCount() > tabCount); return switchToNextTab(); } @WaitUntil public boolean switchToNextTab() { boolean result = false; List<String> tabs = getTabHandles(); if (tabs.size() > 1) { int currentTab = getCurrentTabIndex(tabs); int nextTab = currentTab + 1; if (nextTab == tabs.size()) { nextTab = 0; } goToTab(tabs, nextTab); result = true; } return result; } @WaitUntil public boolean switchToPreviousTab() { boolean result = false; List<String> tabs = getTabHandles(); if (tabs.size() > 1) { int currentTab = getCurrentTabIndex(tabs); int nextTab = currentTab - 1; if (nextTab < 0) { nextTab = tabs.size() - 1; } goToTab(tabs, nextTab); result = true; } return result; } public boolean closeTab() { boolean result = false; List<String> tabs = getTabHandles(); int currentTab = getCurrentTabIndex(tabs); int tabToGoTo = -1; if (currentTab > 0) { tabToGoTo = currentTab - 1; } else { if (tabs.size() > 1) { tabToGoTo = 1; } } if (tabToGoTo > -1) { WebDriver driver = driver(); driver.close(); goToTab(tabs, tabToGoTo); result = true; } return result; } public void ensureOnlyOneTab() { ensureActiveTabIsNotClosed(); int tabCount = tabCount(); for (int i = 1; i < tabCount; i++) { closeTab(); } } public boolean ensureActiveTabIsNotClosed() { boolean result = false; List<String> tabHandles = getTabHandles(); int currentTab = getCurrentTabIndex(tabHandles); if (currentTab < 0) { result = true; goToTab(tabHandles, 0); } return result; } public int tabCount() { return getTabHandles().size(); } public int currentTabIndex() { return getCurrentTabIndex(getTabHandles()) + 1; } protected int getCurrentTabIndex(List<String> tabHandles) { return getSeleniumHelper().getCurrentTabIndex(tabHandles); } protected void goToTab(List<String> tabHandles, int indexToGoTo) { getSeleniumHelper().goToTab(tabHandles, indexToGoTo); } protected List<String> getTabHandles() { return getSeleniumHelper().getTabHandles(); } /** * Activates main/top-level iframe (i.e. makes it the current frame). */ public void switchToDefaultContent() { getSeleniumHelper().switchToDefaultContent(); clearSearchContext(); } /** * Activates specified child frame of current iframe. * @param technicalSelector selector to find iframe. * @return true if iframe was found. */ public boolean switchToFrame(String technicalSelector) { boolean result = false; T iframe = getElement(technicalSelector); if (iframe != null) { getSeleniumHelper().switchToFrame(iframe); result = true; } return result; } /** * Activates parent frame of current iframe. * Does nothing if when current frame is the main/top-level one. */ public void switchToParentFrame() { getSeleniumHelper().switchToParentFrame(); } public String pageTitle() { return getSeleniumHelper().getPageTitle(); } /** * @return current page's content type. */ public String pageContentType() { String result = null; Object ct = getSeleniumHelper().executeJavascript("return document.contentType;"); if (ct != null) { result = ct.toString(); } return result; } /** * Replaces content at place by value. * @param value value to set. * @param place element to set value on. * @return true, if element was found. */ @WaitUntil public boolean enterAs(String value, String place) { return enterAsIn(value, place, null); } /** * Replaces content at place by value. * @param value value to set. * @param place element to set value on. * @param container element containing place. * @return true, if element was found. */ @WaitUntil public boolean enterAsIn(String value, String place, String container) { return enter(value, place, container, true); } /** * Adds content to place. * @param value value to add. * @param place element to add value to. * @return true, if element was found. */ @WaitUntil public boolean enterFor(String value, String place) { return enterForIn(value, place, null); } /** * Adds content to place. * @param value value to add. * @param place element to add value to. * @param container element containing place. * @return true, if element was found. */ @WaitUntil public boolean enterForIn(String value, String place, String container) { return enter(value, place, container, false); } protected boolean enter(String value, String place, boolean shouldClear) { return enter(value, place, null, shouldClear); } protected boolean enter(String value, String place, String container, boolean shouldClear) { WebElement element = getElementToSendValue(place, container); return enter(element, value, shouldClear); } protected boolean enter(WebElement element, String value, boolean shouldClear) { boolean result = element != null && isInteractable(element); if (result) { if (isSelect(element)) { result = clickSelectOption(element, value); } else { if (shouldClear) { clear(element); } sendValue(element, value); } } return result; } @WaitUntil public boolean enterDateAs(String date, String place) { WebElement element = getElementToSendValue(place); boolean result = element != null && isInteractable(element); if (result) { getSeleniumHelper().fillDateInput(element, date); } return result; } protected T getElementToSendValue(String place) { return getElementToSendValue(place, null); } protected T getElementToSendValue(String place, String container) { return getElement(place, container); } /** * Simulates pressing the 'Tab' key. * @return true, if an element was active the key could be sent to. */ public boolean pressTab() { return sendKeysToActiveElement(Keys.TAB); } /** * Simulates pressing the 'Enter' key. * @return true, if an element was active the key could be sent to. */ public boolean pressEnter() { return sendKeysToActiveElement(Keys.ENTER); } /** * Simulates pressing the 'Esc' key. * @return true, if an element was active the key could be sent to. */ public boolean pressEsc() { return sendKeysToActiveElement(Keys.ESCAPE); } /** * Simulates typing a text to the current active element. * @param text text to type. * @return true, if an element was active the text could be sent to. */ public boolean type(String text) { String value = cleanupValue(text); return sendKeysToActiveElement(value); } public boolean press(String key) { CharSequence s; String[] parts = key.split("\\s*\\+\\s*"); if (parts.length > 1 && !"".equals(parts[0]) && !"".equals(parts[1])) { CharSequence[] sequence = new CharSequence[parts.length]; for (int i = 0; i < parts.length; i++) { sequence[i] = parseKey(parts[i]); } s = Keys.chord(sequence); } else { s = parseKey(key); } return sendKeysToActiveElement(s); } protected CharSequence parseKey(String key) { CharSequence s; try { s = Keys.valueOf(key.toUpperCase()); } catch (IllegalArgumentException e) { s = key; } return s; } /** * Simulates pressing keys. * @param keys keys to press. * @return true, if an element was active the keys could be sent to. */ protected boolean sendKeysToActiveElement(CharSequence keys) { boolean result = false; WebElement element = getSeleniumHelper().getActiveElement(); if (element != null) { element.sendKeys(keys); result = true; } return result; } /** * Sends Fitnesse cell content to element. * @param element element to call sendKeys() on. * @param value cell content. */ protected void sendValue(WebElement element, String value) { if (StringUtils.isNotEmpty(value)) { String keys = cleanupValue(value); element.sendKeys(keys); } } @WaitUntil public boolean selectAs(String value, String place) { return selectFor(value, place); } @WaitUntil public boolean selectFor(String value, String place) { WebElement element = getElementToSelectFor(place); return clickSelectOption(element, value); } @WaitUntil public boolean selectForIn(String value, String place, String container) { return Boolean.TRUE.equals(doInContainer(container, () -> selectFor(value, place))); } @WaitUntil public boolean enterForHidden(String value, String idOrName) { return getSeleniumHelper().setHiddenInputValue(idOrName, value); } protected T getElementToSelectFor(String selectPlace) { return getElement(selectPlace); } protected boolean clickSelectOption(WebElement element, String optionValue) { boolean result = false; if (element != null) { if (isSelect(element)) { optionValue = cleanupValue(optionValue); By optionBy = new OptionBy(optionValue); WebElement option = optionBy.findElement(element); if (option != null) { result = clickElement(option); } } } return result; } @WaitUntil public boolean click(String place) { return clickImp(place, null); } @WaitUntil(TimeoutPolicy.RETURN_FALSE) public boolean clickIfAvailable(String place) { return clickIfAvailableIn(place, null); } @WaitUntil(TimeoutPolicy.RETURN_FALSE) public boolean clickIfAvailableIn(String place, String container) { return clickImp(place, container); } @WaitUntil public boolean clickIn(String place, String container) { return clickImp(place, container); } protected boolean clickImp(String place, String container) { boolean result = false; place = cleanupValue(place); try { WebElement element = getElementToClick(place, container); result = clickElement(element); } catch (WebDriverException e) { // if other element hides the element (in Chrome) an exception is thrown String msg = e.getMessage(); if (msg == null || !msg.contains("Other element would receive the click")) { throw e; } } return result; } @WaitUntil public boolean doubleClick(String place) { return doubleClickIn(place, null); } @WaitUntil public boolean doubleClickIn(String place, String container) { place = cleanupValue(place); WebElement element = getElementToClick(place, container); return doubleClick(element); } protected boolean doubleClick(WebElement element) { boolean result = false; if (element != null) { scrollIfNotOnScreen(element); if (isInteractable(element)) { getSeleniumHelper().doubleClick(element); result = true; } } return result; } @WaitUntil public boolean rightClick(String place) { return rightClickIn(place, null); } @WaitUntil public boolean rightClickIn(String place, String container) { place = cleanupValue(place); WebElement element = getElementToClick(place, container); return rightClick(element); } protected boolean rightClick(WebElement element) { boolean result = false; if (element != null) { scrollIfNotOnScreen(element); if (isInteractable(element)) { getSeleniumHelper().rightClick(element); result = true; } } return result; } @WaitUntil public boolean shiftClick(String place) { return shiftClickIn(place, null); } @WaitUntil public boolean shiftClickIn(String place, String container) { place = cleanupValue(place); WebElement element = getElementToClick(place, container); return shiftClick(element); } protected boolean shiftClick(WebElement element) { boolean result = false; if (element != null) { scrollIfNotOnScreen(element); if (isInteractable(element)) { clickWithKeyDown(element, Keys.SHIFT); result = true; } } return result; } @WaitUntil public boolean controlClick(String place) { return controlClickIn(place, null); } @WaitUntil public boolean controlClickIn(String place, String container) { place = cleanupValue(place); WebElement element = getElementToClick(place, container); return controlClick(element); } protected boolean controlClick(WebElement element) { boolean result = false; if (element != null) { scrollIfNotOnScreen(element); if (isInteractable(element)) { clickWithKeyDown(element, Keys.CONTROL); result = true; } } return result; } protected void clickWithKeyDown(WebElement element, CharSequence key) { getSeleniumHelper().getActions().keyDown(key).click(element).keyUp(key).perform(); } @WaitUntil public boolean dragAndDropTo(String source, String destination) { WebElement sourceElement = getElementToClick(source); WebElement destinationElement = getElementToClick(destination); return dragAndDropTo(sourceElement, destinationElement); } protected boolean dragAndDropTo(WebElement sourceElement, WebElement destinationElement) { boolean result = false; if ((sourceElement != null) && (destinationElement != null)) { scrollIfNotOnScreen(sourceElement); if (isInteractable(sourceElement) && destinationElement.isDisplayed()) { getSeleniumHelper().dragAndDrop(sourceElement, destinationElement); result = true; } } return result; } protected T getElementToClick(String place) { return getSeleniumHelper().getElementToClick(place); } protected T getElementToClick(String place, String container) { return doInContainer(container, () -> getElementToClick(place)); } /** * Convenience method to create custom heuristics in subclasses. * @param container container to use (use <code>null</code> for current container), can be a technical selector. * @param place place to look for inside container, can be a technical selector. * @param suppliers suppliers that will be used in turn until an element is found, IF place is not a technical selector. * @return first hit of place, technical selector or result of first supplier that provided result. */ protected T findFirstInContainer(String container, String place, Supplier<? extends T>... suppliers) { return doInContainer(container, () -> getSeleniumHelper().findByTechnicalSelectorOr(place, suppliers)); } protected <R> R doInContainer(String container, Supplier<R> action) { R result = null; if (container == null) { result = action.get(); } else { container = cleanupValue(container); T containerElement = getContainerElement(container); if (containerElement != null) { result = doInContainer(containerElement, action); } } return result; } protected <R> R doInContainer(T container, Supplier<R> action) { return getSeleniumHelper().doInContext(container, action); } @WaitUntil public boolean setSearchContextTo(String container) { boolean result = false; WebElement containerElement = getContainerElement(container); if (containerElement != null) { setSearchContextTo(containerElement); result = true; } return result; } protected void setSearchContextTo(SearchContext containerElement) { getSeleniumHelper().setCurrentContext(containerElement); } public void clearSearchContext() { getSeleniumHelper().setCurrentContext(null); } protected T getContainerElement(String container) { return findByTechnicalSelectorOr(container, this::getContainerImpl); } protected T getContainerImpl(String container) { return findElement(ContainerBy.heuristic(container)); } protected boolean clickElement(WebElement element) { boolean result = false; if (element != null) { scrollIfNotOnScreen(element); if (isInteractable(element)) { element.click(); result = true; } } return result; } protected boolean isInteractable(WebElement element) { return getSeleniumHelper().isInteractable(element); } @WaitUntil(TimeoutPolicy.STOP_TEST) public boolean waitForPage(String pageName) { return pageTitle().equals(pageName); } public boolean waitForTagWithText(String tagName, String expectedText) { return waitForElementWithText(By.tagName(tagName), expectedText); } public boolean waitForClassWithText(String cssClassName, String expectedText) { return waitForElementWithText(By.className(cssClassName), expectedText); } protected boolean waitForElementWithText(By by, String expectedText) { String textToLookFor = cleanExpectedValue(expectedText); return waitUntilOrStop(webDriver -> { boolean ok = false; List<WebElement> elements = webDriver.findElements(by); if (elements != null) { for (WebElement element : elements) { // we don't want stale elements to make single // element false, but instead we stop processing // current list and do a new findElements ok = hasText(element, textToLookFor); if (ok) { // no need to continue to check other elements break; } } } return ok; }); } protected String cleanExpectedValue(String expectedText) { return cleanupValue(expectedText); } protected boolean hasText(WebElement element, String textToLookFor) { boolean ok; String actual = getElementText(element); if (textToLookFor == null) { ok = actual == null; } else { if (StringUtils.isEmpty(actual)) { String value = element.getAttribute("value"); if (!StringUtils.isEmpty(value)) { actual = value; } } if (actual != null) { actual = actual.trim(); } ok = textToLookFor.equals(actual); } return ok; } @WaitUntil(TimeoutPolicy.STOP_TEST) public boolean waitForClass(String cssClassName) { boolean ok = false; WebElement element = findElement(By.className(cssClassName)); if (element != null) { ok = true; } return ok; } @WaitUntil(TimeoutPolicy.STOP_TEST) public boolean waitForVisible(String place) { return waitForVisibleIn(place, null); } @WaitUntil(TimeoutPolicy.STOP_TEST) public boolean waitForVisibleIn(String place, String container) { Boolean result = Boolean.FALSE; WebElement element = getElementToCheckVisibility(place, container); if (element != null) { scrollIfNotOnScreen(element); result = element.isDisplayed(); } return result; } /** * @deprecated use #waitForVisible(xpath=) instead */ @Deprecated public boolean waitForXPathVisible(String xPath) { By by = By.xpath(xPath); return waitForVisible(by); } @Deprecated protected boolean waitForVisible(By by) { return waitUntilOrStop(webDriver -> { Boolean result = Boolean.FALSE; WebElement element = findElement(by); if (element != null) { scrollIfNotOnScreen(element); result = element.isDisplayed(); } return result; }); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public String valueOf(String place) { return valueFor(place); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public String valueFor(String place) { return valueForIn(place, null); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public String valueOfIn(String place, String container) { return valueForIn(place, container); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public String valueForIn(String place, String container) { WebElement element = getElementToRetrieveValue(place, container); return valueFor(element); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public String normalizedValueOf(String place) { return normalizedValueFor(place); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public String normalizedValueFor(String place) { return normalizedValueForIn(place, null); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public String normalizedValueOfIn(String place, String container) { return normalizedValueForIn(place, container); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public String normalizedValueForIn(String place, String container) { String value = valueForIn(place, container); return XPathBy.getNormalizedText(value); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public String tooltipFor(String place) { return tooltipForIn(place, null); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public String tooltipForIn(String place, String container) { return valueOfAttributeOnIn("title", place, container); } @WaitUntil public String targetOfLink(String place) { WebElement linkElement = getSeleniumHelper().getLink(place); return getLinkTarget(linkElement); } protected String getLinkTarget(WebElement linkElement) { String target = null; if (linkElement != null) { target = linkElement.getAttribute("href"); } return target; } @WaitUntil(TimeoutPolicy.RETURN_NULL) public String valueOfAttributeOn(String attribute, String place) { return valueOfAttributeOnIn(attribute, place, null); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public String valueOfAttributeOnIn(String attribute, String place, String container) { String result = null; WebElement element = getElementToRetrieveValue(place, container); if (element != null) { result = element.getAttribute(attribute); } return result; } protected T getElementToRetrieveValue(String place, String container) { return getElement(place, container); } protected String valueFor(By by) { WebElement element = getSeleniumHelper().findElement(by); return valueFor(element); } protected String valueFor(WebElement element) { String result = null; if (element != null) { if (isSelect(element)) { Select s = new Select(element); List<WebElement> options = s.getAllSelectedOptions(); if (options.size() > 0) { result = getElementText(options.get(0)); } } else { String elementType = element.getAttribute("type"); if ("checkbox".equals(elementType) || "radio".equals(elementType)) { result = String.valueOf(element.isSelected()); } else if ("li".equalsIgnoreCase(element.getTagName())) { result = getElementText(element); } else { result = element.getAttribute("value"); if (result == null) { result = getElementText(element); } } } } return result; } private boolean isSelect(WebElement element) { return "select".equalsIgnoreCase(element.getTagName()); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public ArrayList<String> valuesOf(String place) { return valuesFor(place); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public ArrayList<String> valuesOfIn(String place, String container) { return valuesForIn(place, container); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public ArrayList<String> valuesFor(String place) { return valuesForIn(place, null); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public ArrayList<String> valuesForIn(String place, String container) { ArrayList<String> values = null; WebElement element = getElementToRetrieveValue(place, container); if (element != null) { values = new ArrayList<String>(); String tagName = element.getTagName(); if ("ul".equalsIgnoreCase(tagName) || "ol".equalsIgnoreCase(tagName)) { List<WebElement> items = element.findElements(By.tagName("li")); for (WebElement item : items) { if (item.isDisplayed()) { values.add(getElementText(item)); } } } else if (isSelect(element)) { Select s = new Select(element); List<WebElement> options = s.getAllSelectedOptions(); for (WebElement item : options) { values.add(getElementText(item)); } } else { values.add(valueFor(element)); } } return values; } @WaitUntil(TimeoutPolicy.RETURN_NULL) public Integer numberFor(String place) { Integer number = null; WebElement element = findElement(ListItemBy.numbered(place)); if (element != null) { scrollIfNotOnScreen(element); number = getSeleniumHelper().getNumberFor(element); } return number; } @WaitUntil(TimeoutPolicy.RETURN_NULL) public Integer numberForIn(String place, String container) { return doInContainer(container, () -> numberFor(place)); } public ArrayList<String> availableOptionsFor(String place) { ArrayList<String> result = null; WebElement element = getElementToSelectFor(place); if (element != null) { scrollIfNotOnScreen(element); result = getSeleniumHelper().getAvailableOptions(element); } return result; } @WaitUntil public boolean clear(String place) { return clearIn(place, null); } @WaitUntil public boolean clearIn(String place, String container) { boolean result = false; WebElement element = getElementToClear(place, container); if (element != null) { clear(element); result = true; } return result; } protected void clear(WebElement element) { element.clear(); } protected T getElementToClear(String place, String container) { return getElementToSendValue(place, container); } @WaitUntil public boolean enterAsInRowWhereIs(String value, String requestedColumnName, String selectOnColumn, String selectOnValue) { By cellBy = GridBy.columnInRowWhereIs(requestedColumnName, selectOnColumn, selectOnValue); WebElement element = findElement(cellBy); return enter(element, value, true); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public String valueOfColumnNumberInRowNumber(int columnIndex, int rowIndex) { By by = GridBy.coordinates(columnIndex, rowIndex); return valueFor(by); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public String valueOfInRowNumber(String requestedColumnName, int rowIndex) { By by = GridBy.columnInRow(requestedColumnName, rowIndex); return valueFor(by); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public String valueOfInRowWhereIs(String requestedColumnName, String selectOnColumn, String selectOnValue) { By by = GridBy.columnInRowWhereIs(requestedColumnName, selectOnColumn, selectOnValue); return valueFor(by); } @WaitUntil(TimeoutPolicy.RETURN_FALSE) public boolean rowExistsWhereIs(String selectOnColumn, String selectOnValue) { return findElement(GridBy.rowWhereIs(selectOnColumn, selectOnValue)) != null; } @WaitUntil public boolean clickInRowNumber(String place, int rowIndex) { By rowBy = GridBy.rowNumber(rowIndex); return clickInRow(rowBy, place); } @WaitUntil public boolean clickInRowWhereIs(String place, String selectOnColumn, String selectOnValue) { By rowBy = GridBy.rowWhereIs(selectOnColumn, selectOnValue); return clickInRow(rowBy, place); } protected boolean clickInRow(By rowBy, String place) { boolean result = false; T row = findElement(rowBy); if (row != null) { result = doInContainer(row, () -> click(place)); } return result; } /** * Downloads the target of a link in a grid's row. * @param place which link to download. * @param rowNumber (1-based) row number to retrieve link from. * @return downloaded file if any, null otherwise. */ @WaitUntil public String downloadFromRowNumber(String place, int rowNumber) { return downloadFromRow(GridBy.linkInRow(place, rowNumber)); } /** * Downloads the target of a link in a grid, finding the row based on one of the other columns' value. * @param place which link to download. * @param selectOnColumn column header of cell whose value must be selectOnValue. * @param selectOnValue value to be present in selectOnColumn to find correct row. * @return downloaded file if any, null otherwise. */ @WaitUntil public String downloadFromRowWhereIs(String place, String selectOnColumn, String selectOnValue) { return downloadFromRow(GridBy.linkInRowWhereIs(place, selectOnColumn, selectOnValue)); } protected String downloadFromRow(By linkBy) { String result = null; WebElement element = findElement(linkBy); if (element != null) { result = downloadLinkTarget(element); } return result; } protected T getElement(String place) { return getSeleniumHelper().getElement(place); } protected T getElement(String place, String container) { return doInContainer(container, () -> getElement(place)); } /** * @deprecated use #click(xpath=) instead. */ @WaitUntil @Deprecated public boolean clickByXPath(String xPath) { WebElement element = findByXPath(xPath); return clickElement(element); } /** * @deprecated use #valueOf(xpath=) instead. */ @WaitUntil(TimeoutPolicy.RETURN_NULL) @Deprecated public String textByXPath(String xPath) { return getTextByXPath(xPath); } protected String getTextByXPath(String xpathPattern, String... params) { WebElement element = findByXPath(xpathPattern, params); return getElementText(element); } /** * @deprecated use #valueOf(css=.) instead. */ @WaitUntil(TimeoutPolicy.RETURN_NULL) @Deprecated public String textByClassName(String className) { return getTextByClassName(className); } protected String getTextByClassName(String className) { WebElement element = findByClassName(className); return getElementText(element); } protected T findByClassName(String className) { By by = By.className(className); return findElement(by); } protected T findByXPath(String xpathPattern, String... params) { return getSeleniumHelper().findByXPath(xpathPattern, params); } protected T findByCss(String cssPattern, String... params) { By by = getSeleniumHelper().byCss(cssPattern, params); return findElement(by); } protected T findByJavascript(String script, Object... parameters) { By by = getSeleniumHelper().byJavascript(script, parameters); return findElement(by); } protected List<T> findAllByXPath(String xpathPattern, String... params) { By by = getSeleniumHelper().byXpath(xpathPattern, params); return findElements(by); } protected List<T> findAllByCss(String cssPattern, String... params) { By by = getSeleniumHelper().byCss(cssPattern, params); return findElements(by); } protected List<T> findAllByJavascript(String script, Object... parameters) { By by = getSeleniumHelper().byJavascript(script, parameters); return findElements(by); } protected List<T> findElements(By by) { List elements = driver().findElements(by); return elements; } public void waitMilliSecondAfterScroll(int msToWait) { waitAfterScroll = msToWait; } protected int getWaitAfterScroll() { return waitAfterScroll; } protected String getElementText(WebElement element) { String result = null; if (element != null) { scrollIfNotOnScreen(element); result = getSeleniumHelper().getText(element); } return result; } /** * Scrolls browser window so top of place becomes visible. * @param place element to scroll to. */ @WaitUntil public boolean scrollTo(String place) { return scrollToIn(place, null); } /** * Scrolls browser window so top of place becomes visible. * @param place element to scroll to. * @param container parent of place. */ @WaitUntil public boolean scrollToIn(String place, String container) { boolean result = false; WebElement element = getElementToScrollTo(place, container); if (element != null) { scrollTo(element); result = true; } return result; } protected T getElementToScrollTo(String place, String container) { return getElementToCheckVisibility(place, container); } /** * Scrolls browser window so top of element becomes visible. * @param element element to scroll to. */ protected void scrollTo(WebElement element) { getSeleniumHelper().scrollTo(element); waitAfterScroll(waitAfterScroll); } /** * Wait after the scroll if needed * @param msToWait amount of ms to wait after the scroll */ protected void waitAfterScroll(int msToWait) { if (msToWait > 0) { waitMilliseconds(msToWait); } } /** * Scrolls browser window if element is not currently visible so top of element becomes visible. * @param element element to scroll to. */ protected void scrollIfNotOnScreen(WebElement element) { if (!element.isDisplayed() || !isElementOnScreen(element)) { scrollTo(element); } } /** * Determines whether element is enabled (i.e. can be clicked). * @param place element to check. * @return true if element is enabled. */ @WaitUntil(TimeoutPolicy.RETURN_FALSE) public boolean isEnabled(String place) { return isEnabledIn(place, null); } /** * Determines whether element is enabled (i.e. can be clicked). * @param place element to check. * @param container parent of place. * @return true if element is enabled. */ @WaitUntil(TimeoutPolicy.RETURN_FALSE) public boolean isEnabledIn(String place, String container) { boolean result = false; T element = getElementToCheckVisibility(place, container); if (element != null) { if ("label".equalsIgnoreCase(element.getTagName())) { // for labels we want to know whether their target is enabled, not the label itself T labelTarget = getSeleniumHelper().getLabelledElement(element); if (labelTarget != null) { element = labelTarget; } } result = element.isEnabled(); } return result; } /** * Determines whether element can be see in browser's window. * @param place element to check. * @return true if element is displayed and in viewport. */ @WaitUntil(TimeoutPolicy.RETURN_FALSE) public boolean isVisible(String place) { return isVisibleIn(place, null); } /** * Determines whether element can be see in browser's window. * @param place element to check. * @param container parent of place. * @return true if element is displayed and in viewport. */ @WaitUntil(TimeoutPolicy.RETURN_FALSE) public boolean isVisibleIn(String place, String container) { return isVisibleImpl(place, container, true); } /** * Determines whether element is somewhere in browser's window. * @param place element to check. * @return true if element is displayed. */ @WaitUntil(TimeoutPolicy.RETURN_FALSE) public boolean isVisibleOnPage(String place) { return isVisibleOnPageIn(place, null); } /** * Determines whether element is somewhere in browser's window. * @param place element to check. * @param container parent of place. * @return true if element is displayed. */ @WaitUntil(TimeoutPolicy.RETURN_FALSE) public boolean isVisibleOnPageIn(String place, String container) { return isVisibleImpl(place, container, false); } protected boolean isVisibleImpl(String place, String container, boolean checkOnScreen) { WebElement element = getElementToCheckVisibility(place, container); return getSeleniumHelper().checkVisible(element, checkOnScreen); } public int numberOfTimesIsVisible(String text) { return numberOfTimesIsVisibleInImpl(text, true); } public int numberOfTimesIsVisibleOnPage(String text) { return numberOfTimesIsVisibleInImpl(text, false); } public int numberOfTimesIsVisibleIn(String text, String container) { return intValueOf(doInContainer(container, () -> numberOfTimesIsVisible(text))); } public int numberOfTimesIsVisibleOnPageIn(String text, String container) { return intValueOf(doInContainer(container, () -> numberOfTimesIsVisibleOnPage(text))); } protected int intValueOf(Integer count) { if (count == null) { count = Integer.valueOf(0); } return count; } protected int numberOfTimesIsVisibleInImpl(String text, boolean checkOnScreen) { return getSeleniumHelper().countVisibleOccurrences(text, checkOnScreen); } protected T getElementToCheckVisibility(String place) { return getSeleniumHelper().getElementToCheckVisibility(place); } protected T getElementToCheckVisibility(String place, String container) { return doInContainer(container, () -> findByTechnicalSelectorOr(place, this::getElementToCheckVisibility)); } /** * Checks whether element is in browser's viewport. * @param element element to check * @return true if element is in browser's viewport. */ protected boolean isElementOnScreen(WebElement element) { Boolean onScreen = getSeleniumHelper().isElementOnScreen(element); return onScreen == null || onScreen.booleanValue(); } @WaitUntil public boolean hoverOver(String place) { return hoverOverIn(place, null); } @WaitUntil public boolean hoverOverIn(String place, String container) { WebElement element = getElementToClick(place, container); return hoverOver(element); } protected boolean hoverOver(WebElement element) { boolean result = false; if (element != null) { scrollIfNotOnScreen(element); if (element.isDisplayed()) { getSeleniumHelper().hoverOver(element); result = true; } } return result; } /** * @param timeout number of seconds before waitUntil() and waitForJavascriptCallback() throw TimeOutException. */ public void secondsBeforeTimeout(int timeout) { secondsBeforeTimeout = timeout; secondsBeforePageLoadTimeout(timeout); int timeoutInMs = timeout * 1000; getSeleniumHelper().setScriptWait(timeoutInMs); } /** * @return number of seconds waitUntil() will wait at most. */ public int secondsBeforeTimeout() { return secondsBeforeTimeout; } /** * @param timeout number of seconds before waiting for a new page to load will throw a TimeOutException. */ public void secondsBeforePageLoadTimeout(int timeout) { secondsBeforePageLoadTimeout = timeout; int timeoutInMs = timeout * 1000; getSeleniumHelper().setPageLoadWait(timeoutInMs); } /** * @return number of seconds Selenium will wait at most for a request to load a page. */ public int secondsBeforePageLoadTimeout() { return secondsBeforePageLoadTimeout; } /** * Clears HTML5's sessionStorage (for the domain of the current open page in the browser). */ public void clearSessionStorage() { getSeleniumHelper().executeJavascript("sessionStorage.clear();"); } /** * Clears HTML5's localStorage (for the domain of the current open page in the browser). */ public void clearLocalStorage() { getSeleniumHelper().executeJavascript("localStorage.clear();"); } /** * Deletes all cookies(for the domain of the current open page in the browser). */ public void deleteAllCookies() { getSeleniumHelper().deleteAllCookies(); } /** * @param directory sets base directory where screenshots will be stored. */ public void screenshotBaseDirectory(String directory) { if (directory.equals("") || directory.endsWith("/") || directory.endsWith("\\")) { screenshotBase = directory; } else { screenshotBase = directory + "/"; } } /** * @param height height to use to display screenshot images */ public void screenshotShowHeight(String height) { screenshotHeight = height; } /** * @return (escaped) HTML content of current page. */ public String pageSource() { String html = getSeleniumHelper().getHtml(); return getEnvironment().getHtml(html); } /** * Saves current page's source to the wiki'f files section and returns a link to the * created file. * @return hyperlink to the file containing the page source. */ public String savePageSource() { String fileName = getSeleniumHelper().getResourceNameFromLocation(); return savePageSource(fileName, fileName + ".html"); } protected String savePageSource(String fileName, String linkText) { PageSourceSaver saver = getSeleniumHelper().getPageSourceSaver(pageSourceBase); // make href to file String url = saver.savePageSource(fileName); return String.format("<a href=\"%s\">%s</a>", url, linkText); } /** * Takes screenshot from current page * @param basename filename (below screenshot base directory). * @return location of screenshot. */ public String takeScreenshot(String basename) { try { String screenshotFile = createScreenshot(basename); if (screenshotFile == null) { throw new SlimFixtureException(false, "Unable to take screenshot: does the webdriver support it?"); } else { screenshotFile = getScreenshotLink(screenshotFile); } return screenshotFile; } catch (UnhandledAlertException e) { // standard behavior will stop test, this breaks storyboard that will attempt to take screenshot // after triggering alert, but before the alert can be handled. // so we output a message but no exception. We rely on a next line to actually handle alert // (which may mean either really handle or stop test). return String.format( "<div><strong>Unable to take screenshot</strong>, alert is active. Alert text:<br/>" + "'<span>%s</span>'</div>", StringEscapeUtils.escapeHtml4(alertText())); } } private String getScreenshotLink(String screenshotFile) { String wikiUrl = getWikiUrl(screenshotFile); if (wikiUrl != null) { // make href to screenshot if ("".equals(screenshotHeight)) { wikiUrl = String.format("<a href=\"%s\">%s</a>", wikiUrl, screenshotFile); } else { wikiUrl = String.format("<a href=\"%1$s\"><img src=\"%1$s\" title=\"%2$s\" height=\"%3$s\"/></a>", wikiUrl, screenshotFile, screenshotHeight); } screenshotFile = wikiUrl; } return screenshotFile; } private String createScreenshot(String basename) { String name = getScreenshotBasename(basename); return getSeleniumHelper().takeScreenshot(name); } private String createScreenshot(String basename, Throwable t) { String screenshotFile; byte[] screenshotInException = getSeleniumHelper().findScreenshot(t); if (screenshotInException == null || screenshotInException.length == 0) { screenshotFile = createScreenshot(basename); } else { String name = getScreenshotBasename(basename); screenshotFile = getSeleniumHelper().writeScreenshot(name, screenshotInException); } return screenshotFile; } private String getScreenshotBasename(String basename) { return screenshotBase + basename; } /** * Waits until the condition evaluates to a value that is neither null nor * false. Because of this contract, the return type must not be Void. * @param <T> the return type of the method, which must not be Void * @param condition condition to evaluate to determine whether waiting can be stopped. * @throws SlimFixtureException if condition was not met before secondsBeforeTimeout. * @return result of condition. */ protected <T> T waitUntil(ExpectedCondition<T> condition) { try { return waitUntilImpl(condition); } catch (TimeoutException e) { String message = getTimeoutMessage(e); return lastAttemptBeforeThrow(condition, new SlimFixtureException(false, message, e)); } } /** * Waits until the condition evaluates to a value that is neither null nor * false. If that does not occur the whole test is stopped. * Because of this contract, the return type must not be Void. * @param <T> the return type of the method, which must not be Void * @param condition condition to evaluate to determine whether waiting can be stopped. * @throws TimeoutStopTestException if condition was not met before secondsBeforeTimeout. * @return result of condition. */ protected <T> T waitUntilOrStop(ExpectedCondition<T> condition) { try { return waitUntilImpl(condition); } catch (TimeoutException e) { try { return handleTimeoutException(e); } catch (TimeoutStopTestException tste) { return lastAttemptBeforeThrow(condition, tste); } } } /** * Tries the condition one last time before throwing an exception. * This to prevent exception messages in the wiki that show no problem, which could happen if the browser's * window content has changed between last (failing) try at condition and generation of the exception. * @param <T> the return type of the method, which must not be Void * @param condition condition that caused exception. * @param e exception that will be thrown if condition does not return a result. * @return last attempt results, if not null. * @throws SlimFixtureException throws e if last attempt returns null. */ protected <T> T lastAttemptBeforeThrow(ExpectedCondition<T> condition, SlimFixtureException e) { T lastAttemptResult = null; try { // last attempt to ensure condition has not been met // this to prevent messages that show no problem lastAttemptResult = condition.apply(getSeleniumHelper().driver()); } catch (Throwable t) { // ignore } if (lastAttemptResult != null) { return lastAttemptResult; } throw e; } /** * Waits until the condition evaluates to a value that is neither null nor * false. If that does not occur null is returned. * Because of this contract, the return type must not be Void. * @param <T> the return type of the method, which must not be Void * @param condition condition to evaluate to determine whether waiting can be stopped. * @return result of condition. */ protected <T> T waitUntilOrNull(ExpectedCondition<T> condition) { try { return waitUntilImpl(condition); } catch (TimeoutException e) { return null; } } protected <T> T waitUntilImpl(ExpectedCondition<T> condition) { return getSeleniumHelper().waitUntil(secondsBeforeTimeout(), condition); } protected <T> T handleTimeoutException(TimeoutException e) { String message = getTimeoutMessage(e); throw new TimeoutStopTestException(false, message, e); } private String getTimeoutMessage(TimeoutException e) { String messageBase = String.format("Timed-out waiting (after %ss)", secondsBeforeTimeout()); return getSlimFixtureExceptionMessage("timeouts", "timeout", messageBase, e); } protected void handleRequiredElementNotFound(String toFind) { handleRequiredElementNotFound(toFind, null); } protected void handleRequiredElementNotFound(String toFind, Throwable t) { String messageBase = String.format("Unable to find: %s", toFind); String message = getSlimFixtureExceptionMessage("notFound", toFind, messageBase, t); throw new SlimFixtureException(false, message, t); } protected String getSlimFixtureExceptionMessage(String screenshotFolder, String screenshotFile, String messageBase, Throwable t) { String screenshotBaseName = String.format("%s/%s/%s", screenshotFolder, getClass().getSimpleName(), screenshotFile); return getSlimFixtureExceptionMessage(screenshotBaseName, messageBase, t); } protected String getSlimFixtureExceptionMessage(String screenshotBaseName, String messageBase, Throwable t) { String exceptionMsg = getExceptionMessageText(messageBase, t); // take a screenshot of what was on screen String screenshotTag = getExceptionScreenshotTag(screenshotBaseName, messageBase, t); String label = getExceptionPageSourceTag(screenshotBaseName, messageBase, t); String message = String.format("<div><div>%s.</div><div>%s:%s</div></div>", exceptionMsg, label, screenshotTag); return message; } protected String getExceptionMessageText(String messageBase, Throwable t) { String message = messageBase; if (message == null) { if (t == null) { message = ""; } else { message = ExceptionUtils.getStackTrace(t); } } return formatExceptionMsg(message); } protected String getExceptionScreenshotTag(String screenshotBaseName, String messageBase, Throwable t) { String screenshotTag = "(Screenshot not available)"; try { String screenShotFile = createScreenshot(screenshotBaseName, t); screenshotTag = getScreenshotLink(screenShotFile); } catch (UnhandledAlertException e) { System.err.println("Unable to take screenshot while alert is present for exception: " + messageBase); } catch (Exception sse) { System.err.println("Unable to take screenshot for exception: " + messageBase); sse.printStackTrace(); } return screenshotTag; } protected String getExceptionPageSourceTag(String screenshotBaseName, String messageBase, Throwable t) { String label = "Page content"; try { String fileName; if (t != null) { fileName = t.getClass().getName(); } else if (screenshotBaseName != null) { fileName = screenshotBaseName; } else { fileName = "exception"; } label = savePageSource(fileName, label); } catch (UnhandledAlertException e) { System.err.println("Unable to capture page source while alert is present for exception: " + messageBase); } catch (Exception e) { System.err.println("Unable to capture page source for exception: " + messageBase); e.printStackTrace(); } return label; } protected String formatExceptionMsg(String value) { return StringEscapeUtils.escapeHtml4(value); } private WebDriver driver() { return getSeleniumHelper().driver(); } private WebDriverWait waitDriver() { return getSeleniumHelper().waitDriver(); } /** * @return helper to use. */ protected SeleniumHelper<T> getSeleniumHelper() { return seleniumHelper; } /** * Sets SeleniumHelper to use, for testing purposes. * @param helper helper to use. */ protected void setSeleniumHelper(SeleniumHelper<T> helper) { seleniumHelper = helper; } public int currentBrowserWidth() { return getWindowSize().getWidth(); } public int currentBrowserHeight() { return getWindowSize().getHeight(); } public void setBrowserWidth(int newWidth) { int currentHeight = currentBrowserHeight(); setBrowserSizeToBy(newWidth, currentHeight); } public void setBrowserHeight(int newHeight) { int currentWidth = currentBrowserWidth(); setBrowserSizeToBy(currentWidth, newHeight); } public void setBrowserSizeToBy(int newWidth, int newHeight) { getSeleniumHelper().setWindowSize(newWidth, newHeight); Dimension actualSize = getWindowSize(); if (actualSize.getHeight() != newHeight || actualSize.getWidth() != newWidth) { String message = String.format("Unable to change size to: %s x %s; size is: %s x %s", newWidth, newHeight, actualSize.getWidth(), actualSize.getHeight()); throw new SlimFixtureException(false, message); } } protected Dimension getWindowSize() { return getSeleniumHelper().getWindowSize(); } public void setBrowserSizeToMaximum() { getSeleniumHelper().setWindowSizeToMaximum(); } /** * Downloads the target of the supplied link. * @param place link to follow. * @return downloaded file if any, null otherwise. */ @WaitUntil public String download(String place) { WebElement element = getSeleniumHelper().getLink(place); return downloadLinkTarget(element); } /** * Downloads the target of the supplied link. * @param place link to follow. * @param container part of screen containing link. * @return downloaded file if any, null otherwise. */ @WaitUntil public String downloadIn(String place, String container) { return doInContainer(container, () -> download(place)); } protected T findElement(By selector) { return getSeleniumHelper().findElement(selector); } public T findByTechnicalSelectorOr(String place, Function<String, ? extends T> supplierF) { return getSeleniumHelper().findByTechnicalSelectorOr(place, () -> supplierF.apply(place)); } /** * Downloads the target of the supplied link. * @param element link to follow. * @return downloaded file if any, null otherwise. */ protected String downloadLinkTarget(WebElement element) { String result; String href = getLinkTarget(element); if (href != null) { result = downloadContentFrom(href); } else { throw new SlimFixtureException(false, "Could not determine url to download from"); } return result; } /** * Downloads binary content from specified url (using the browser's cookies). * @param urlOrLink url to download from * @return link to downloaded file */ public String downloadContentFrom(String urlOrLink) { String result = null; if (urlOrLink != null) { String url = getUrl(urlOrLink); BinaryHttpResponse resp = new BinaryHttpResponse(); getUrlContent(url, resp); byte[] content = resp.getResponseContent(); if (content == null) { result = resp.getResponse(); } else { String fileName = resp.getFileName(); if (StringUtils.isEmpty(fileName)) { fileName = "download"; } String baseName = FilenameUtils.getBaseName(fileName); String ext = FilenameUtils.getExtension(fileName); String downloadedFile = FileUtil.saveToFile(getDownloadName(baseName), ext, content); String wikiUrl = getWikiUrl(downloadedFile); if (wikiUrl != null) { // make href to file result = String.format("<a href=\"%s\">%s</a>", wikiUrl, fileName); } else { result = downloadedFile; } } } return result; } /** * Selects a file using the first file upload control. * @param fileName file to upload * @return true, if a file input was found and file existed. */ @WaitUntil public boolean selectFile(String fileName) { return selectFileFor(fileName, "css=input[type='file']"); } /** * Selects a file using a file upload control. * @param fileName file to upload * @param place file input to select the file for * @return true, if place was a file input and file existed. */ @WaitUntil public boolean selectFileFor(String fileName, String place) { return selectFileForIn(fileName, place, null); } /** * Selects a file using a file upload control. * @param fileName file to upload * @param place file input to select the file for * @param container part of screen containing place * @return true, if place was a file input and file existed. */ @WaitUntil public boolean selectFileForIn(String fileName, String place, String container) { boolean result = false; if (fileName != null) { String fullPath = getFilePathFromWikiUrl(fileName); if (new File(fullPath).exists()) { WebElement element = getElementToSelectFile(place, container); if (element != null) { element.sendKeys(fullPath); result = true; } } else { throw new SlimFixtureException(false, "Unable to find file: " + fullPath); } } return result; } protected T getElementToSelectFile(String place, String container) { T result = null; T element = getElement(place, container); if (element != null && "input".equalsIgnoreCase(element.getTagName()) && "file".equalsIgnoreCase(element.getAttribute("type"))) { result = element; } return result; } private String getDownloadName(String baseName) { return downloadBase + baseName; } /** * GETs content of specified URL, using the browsers cookies. * @param url url to retrieve content from * @param resp response to store content in */ protected void getUrlContent(String url, HttpResponse resp) { getEnvironment().addSeleniumCookies(resp); getEnvironment().doGet(url, resp); } /** * Gets the value of the cookie with the supplied name. * @param cookieName name of cookie to get value from. * @return cookie's value if any. */ public String cookieValue(String cookieName) { String result = null; Cookie cookie = getSeleniumHelper().getCookie(cookieName); if (cookie != null) { result = cookie.getValue(); } return result; } public boolean refreshUntilValueOfIs(String place, String expectedValue) { return repeatUntil(getRefreshUntilValueIs(place, expectedValue)); } public boolean refreshUntilValueOfIsNot(String place, String expectedValue) { return repeatUntilNot(getRefreshUntilValueIs(place, expectedValue)); } protected RepeatCompletion getRefreshUntilValueIs(String place, String expectedValue) { return new ConditionBasedRepeatUntil(false, d-> refresh(), true, d -> checkValueIs(place, expectedValue)); } public boolean clickUntilValueOfIs(String clickPlace, String checkPlace, String expectedValue) { return repeatUntil(getClickUntilValueIs(clickPlace, checkPlace, expectedValue)); } public boolean clickUntilValueOfIsNot(String clickPlace, String checkPlace, String expectedValue) { return repeatUntilNot(getClickUntilValueIs(clickPlace, checkPlace, expectedValue)); } public boolean executeJavascriptUntilIs(String script, String place, String value) { return repeatUntil(getExecuteScriptUntilValueIs(script, place, value)); } public boolean executeJavascriptUntilIsNot(String script, String place, String value) { return repeatUntilNot(getExecuteScriptUntilValueIs(script, place, value)); } protected RepeatCompletion getExecuteScriptUntilValueIs(String script, String place, String expectedValue) { return new ConditionBasedRepeatUntil( false, d -> { Object r = executeScript(script); return r != null ? r : true; }, true, d -> checkValueIs(place, expectedValue)); } protected RepeatCompletion getClickUntilValueIs(String clickPlace, String checkPlace, String expectedValue) { String place = cleanupValue(clickPlace); return getClickUntilCompletion(place, checkPlace, expectedValue); } protected RepeatCompletion getClickUntilCompletion(String place, String checkPlace, String expectedValue) { return new ConditionBasedRepeatUntil(true, d -> click(place), d -> checkValueIs(checkPlace, expectedValue)); } protected boolean repeatUntil(ExpectedCondition<Object> actionCondition, ExpectedCondition<Boolean> finishCondition) { return repeatUntil(new ConditionBasedRepeatUntil(true, actionCondition, finishCondition)); } protected boolean repeatUntilIsNot(ExpectedCondition<Object> actionCondition, ExpectedCondition<Boolean> finishCondition) { return repeatUntilNot(new ConditionBasedRepeatUntil(true, actionCondition, finishCondition)); } protected <T> ExpectedCondition<T> wrapConditionForFramesIfNeeded(ExpectedCondition<T> condition) { if (implicitFindInFrames) { condition = getSeleniumHelper().conditionForAllFrames(condition); } return condition; } @Override protected boolean repeatUntil(RepeatCompletion repeat) { // During repeating we reduce the timeout used for finding elements, // but the page load timeout is kept as-is (which takes extra work because secondsBeforeTimeout(int) // also changes that. int previousTimeout = secondsBeforeTimeout(); int pageLoadTimeout = secondsBeforePageLoadTimeout(); try { int timeoutDuringRepeat = Math.max((Math.toIntExact(repeatInterval() / 1000)), 1); secondsBeforeTimeout(timeoutDuringRepeat); secondsBeforePageLoadTimeout(pageLoadTimeout); return super.repeatUntil(repeat); } finally { secondsBeforeTimeout(previousTimeout); secondsBeforePageLoadTimeout(pageLoadTimeout); } } protected boolean checkValueIs(String place, String expectedValue) { boolean match; String actual = valueOf(place); if (expectedValue == null) { match = actual == null; } else { match = cleanExpectedValue(expectedValue).equals(actual); } return match; } protected class ConditionBasedRepeatUntil extends FunctionalCompletion { public ConditionBasedRepeatUntil(boolean wrapIfNeeded, ExpectedCondition<? extends Object> repeatCondition, ExpectedCondition<Boolean> finishedCondition) { this(wrapIfNeeded, repeatCondition, wrapIfNeeded, finishedCondition); } public ConditionBasedRepeatUntil(boolean wrapRepeatIfNeeded, ExpectedCondition<? extends Object> repeatCondition, boolean wrapFinishedIfNeeded, ExpectedCondition<Boolean> finishedCondition) { if (wrapRepeatIfNeeded) { repeatCondition = wrapConditionForFramesIfNeeded(repeatCondition); } ExpectedCondition<?> finalRepeatCondition = repeatCondition; if (wrapFinishedIfNeeded) { finishedCondition = wrapConditionForFramesIfNeeded(finishedCondition); } ExpectedCondition<Boolean> finalFinishedCondition = finishedCondition; setIsFinishedSupplier(() -> waitUntilOrNull(finalFinishedCondition)); setRepeater(() -> waitUntil(finalRepeatCondition)); } } protected Object waitForJavascriptCallback(String statement, Object... parameters) { try { return getSeleniumHelper().waitForJavascriptCallback(statement, parameters); } catch (TimeoutException e) { return handleTimeoutException(e); } } public NgBrowserTest getNgBrowserTest() { return ngBrowserTest; } public void setNgBrowserTest(NgBrowserTest ngBrowserTest) { this.ngBrowserTest = ngBrowserTest; } public boolean isImplicitWaitForAngularEnabled() { return implicitWaitForAngular; } public void setImplicitWaitForAngularTo(boolean implicitWaitForAngular) { this.implicitWaitForAngular = implicitWaitForAngular; } public void setImplicitFindInFramesTo(boolean implicitFindInFrames) { this.implicitFindInFrames = implicitFindInFrames; } /** * Executes javascript in the browser. * @param script you want to execute * @return result from script */ public Object executeScript(String script) { String statement = cleanupValue(script); return getSeleniumHelper().executeJavascript(statement); } }
package nl.hsac.fitnesse.fixture.slim.web; import fitnesse.slim.fixtureInteraction.FixtureInteraction; import nl.hsac.fitnesse.fixture.slim.SlimFixture; import nl.hsac.fitnesse.fixture.slim.SlimFixtureException; import nl.hsac.fitnesse.fixture.slim.StopTestException; import nl.hsac.fitnesse.fixture.slim.web.annotation.TimeoutPolicy; import nl.hsac.fitnesse.fixture.slim.web.annotation.WaitUntil; import nl.hsac.fitnesse.fixture.util.BinaryHttpResponse; import nl.hsac.fitnesse.fixture.util.FileUtil; import nl.hsac.fitnesse.fixture.util.HttpResponse; import nl.hsac.fitnesse.fixture.util.ReflectionHelper; import nl.hsac.fitnesse.fixture.util.selenium.ListItemBy; import nl.hsac.fitnesse.fixture.util.selenium.PageSourceSaver; import nl.hsac.fitnesse.fixture.util.selenium.SeleniumHelper; import nl.hsac.fitnesse.fixture.util.selenium.by.ContainerBy; import nl.hsac.fitnesse.fixture.util.selenium.by.GridBy; import nl.hsac.fitnesse.fixture.util.selenium.by.OptionBy; import nl.hsac.fitnesse.fixture.util.selenium.by.TextBy; import nl.hsac.fitnesse.fixture.util.selenium.by.XPathBy; import nl.hsac.fitnesse.slim.interaction.ExceptionHelper; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.commons.text.StringEscapeUtils; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.Cookie; import org.openqa.selenium.Dimension; import org.openqa.selenium.Keys; import org.openqa.selenium.SearchContext; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.UnhandledAlertException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; import java.io.File; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.function.Function; import java.util.function.Supplier; public class BrowserTest<T extends WebElement> extends SlimFixture { private SeleniumHelper<T> seleniumHelper = getEnvironment().getSeleniumHelper(); private ReflectionHelper reflectionHelper = getEnvironment().getReflectionHelper(); private NgBrowserTest ngBrowserTest; private boolean implicitWaitForAngular = false; private boolean implicitFindInFrames = true; private int secondsBeforeTimeout; private int secondsBeforePageLoadTimeout; private int waitAfterScroll = 150; private String screenshotBase = new File(filesDir, "screenshots").getPath() + "/"; private String screenshotHeight = "200"; private String downloadBase = new File(filesDir, "downloads").getPath() + "/"; private String pageSourceBase = new File(filesDir, "pagesources").getPath() + "/"; @Override protected void beforeInvoke(Method method, Object[] arguments) { super.beforeInvoke(method, arguments); waitForAngularIfNeeded(method); } @Override protected Object invoke(FixtureInteraction interaction, Method method, Object[] arguments) throws Throwable { Object result; WaitUntil waitUntil = reflectionHelper.getAnnotation(WaitUntil.class, method); if (waitUntil == null) { result = superInvoke(interaction, method, arguments); } else { result = invokedWrappedInWaitUntil(waitUntil, interaction, method, arguments); } return result; } protected Object invokedWrappedInWaitUntil(WaitUntil waitUntil, FixtureInteraction interaction, Method method, Object[] arguments) { ExpectedCondition<Object> condition = webDriver -> { try { return superInvoke(interaction, method, arguments); } catch (Throwable e) { Throwable realEx = ExceptionHelper.stripReflectionException(e); if (realEx instanceof RuntimeException) { throw (RuntimeException) realEx; } else if (realEx instanceof Error) { throw (Error) realEx; } else { throw new RuntimeException(realEx); } } }; condition = wrapConditionForFramesIfNeeded(condition); Object result; switch (waitUntil.value()) { case STOP_TEST: result = waitUntilOrStop(condition); break; case RETURN_NULL: result = waitUntilOrNull(condition); break; case RETURN_FALSE: result = waitUntilOrNull(condition) != null; break; case THROW: default: result = waitUntil(condition); break; } return result; } protected Object superInvoke(FixtureInteraction interaction, Method method, Object[] arguments) throws Throwable { return super.invoke(interaction, method, arguments); } /** * Determines whether the current method might require waiting for angular given the currently open site, * and ensure it does if needed. * @param method */ protected void waitForAngularIfNeeded(Method method) { if (isImplicitWaitForAngularEnabled()) { try { if (ngBrowserTest == null) { ngBrowserTest = new NgBrowserTest(secondsBeforeTimeout()); ngBrowserTest.secondsBeforePageLoadTimeout(secondsBeforePageLoadTimeout()); } if (ngBrowserTest.requiresWaitForAngular(method) && currentSiteUsesAngular()) { try { ngBrowserTest.waitForAngularRequestsToFinish(); } catch (Exception e) { // if something goes wrong, just use normal behavior: continue to invoke() System.err.print("Found Angular, but encountered an error while waiting for it to be ready. "); e.printStackTrace(); } } } catch (UnhandledAlertException e) { System.err.println("Cannot determine whether Angular is present while alert is active."); } catch (Exception e) { // if something goes wrong, just use normal behavior: continue to invoke() System.err.print("Error while determining whether Angular is present. "); e.printStackTrace(); } } } protected boolean currentSiteUsesAngular() { Object windowHasAngular = getSeleniumHelper().executeJavascript("return window.angular?1:0;"); return Long.valueOf(1).equals(windowHasAngular); } @Override protected Throwable handleException(Method method, Object[] arguments, Throwable t) { Throwable result; if (t instanceof UnhandledAlertException) { UnhandledAlertException e = (UnhandledAlertException) t; String alertText = e.getAlertText(); if (alertText == null) { alertText = alertText(); } String msgBase = "Unhandled alert: alert must be confirmed or dismissed before test can continue. Alert text: " + alertText; String msg = getSlimFixtureExceptionMessage("alertException", msgBase, e); result = new StopTestException(false, msg, t); } else if (t instanceof SlimFixtureException) { result = super.handleException(method, arguments, t); } else { String msg = getSlimFixtureExceptionMessage("exception", null, t); result = new SlimFixtureException(false, msg, t); } return result; } public BrowserTest() { secondsBeforeTimeout(getEnvironment().getSeleniumDriverManager().getDefaultTimeoutSeconds()); ensureActiveTabIsNotClosed(); } public BrowserTest(int secondsBeforeTimeout) { secondsBeforeTimeout(secondsBeforeTimeout); ensureActiveTabIsNotClosed(); } public boolean open(String address) { String url = getUrl(address); try { getNavigation().to(url); } catch (TimeoutException e) { handleTimeoutException(e); } finally { switchToDefaultContent(); } waitUntil(webDriver -> { String readyState = getSeleniumHelper().executeJavascript("return document.readyState").toString(); // IE 7 is reported to return "loaded" boolean done = "complete".equalsIgnoreCase(readyState) || "loaded".equalsIgnoreCase(readyState); if (!done) { System.err.printf("Open of %s returned while document.readyState was %s", url, readyState); System.err.println(); } return done; }); return true; } public String location() { return driver().getCurrentUrl(); } public boolean back() { getNavigation().back(); switchToDefaultContent(); // firefox sometimes prevents immediate back, if previous page was reached via POST waitMilliseconds(500); WebElement element = findElement(By.id("errorTryAgain")); if (element != null) { element.click(); // don't use confirmAlert as this may be overridden in subclass and to get rid of the // firefox pop-up we need the basic behavior getSeleniumHelper().getAlert().accept(); } return true; } public boolean forward() { getNavigation().forward(); switchToDefaultContent(); return true; } public boolean refresh() { getNavigation().refresh(); switchToDefaultContent(); return true; } private WebDriver.Navigation getNavigation() { return getSeleniumHelper().navigate(); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public String alertText() { Alert alert = getAlert(); String text = null; if (alert != null) { text = alert.getText(); } return text; } @WaitUntil public boolean confirmAlert() { Alert alert = getAlert(); boolean result = false; if (alert != null) { alert.accept(); onAlertHandled(true); result = true; } return result; } @WaitUntil public boolean dismissAlert() { Alert alert = getAlert(); boolean result = false; if (alert != null) { alert.dismiss(); onAlertHandled(false); result = true; } return result; } /** * Called when an alert is either dismissed or accepted. * @param accepted true if the alert was accepted, false if dismissed. */ protected void onAlertHandled(boolean accepted) { // if we were looking in nested frames, we could not go back to original frame // because of the alert. Ensure we do so now the alert is handled. getSeleniumHelper().resetFrameDepthOnAlertError(); } protected Alert getAlert() { return getSeleniumHelper().getAlert(); } public boolean openInNewTab(String url) { String cleanUrl = getUrl(url); int tabCount = tabCount(); getSeleniumHelper().executeJavascript("window.open('%s', '_blank')", cleanUrl); // ensure new window is open waitUntil(webDriver -> tabCount() > tabCount); return switchToNextTab(); } @WaitUntil public boolean switchToNextTab() { boolean result = false; List<String> tabs = getTabHandles(); if (tabs.size() > 1) { int currentTab = getCurrentTabIndex(tabs); int nextTab = currentTab + 1; if (nextTab == tabs.size()) { nextTab = 0; } goToTab(tabs, nextTab); result = true; } return result; } @WaitUntil public boolean switchToPreviousTab() { boolean result = false; List<String> tabs = getTabHandles(); if (tabs.size() > 1) { int currentTab = getCurrentTabIndex(tabs); int nextTab = currentTab - 1; if (nextTab < 0) { nextTab = tabs.size() - 1; } goToTab(tabs, nextTab); result = true; } return result; } public boolean closeTab() { boolean result = false; List<String> tabs = getTabHandles(); int currentTab = getCurrentTabIndex(tabs); int tabToGoTo = -1; if (currentTab > 0) { tabToGoTo = currentTab - 1; } else { if (tabs.size() > 1) { tabToGoTo = 1; } } if (tabToGoTo > -1) { WebDriver driver = driver(); driver.close(); goToTab(tabs, tabToGoTo); result = true; } return result; } public void ensureOnlyOneTab() { ensureActiveTabIsNotClosed(); int tabCount = tabCount(); for (int i = 1; i < tabCount; i++) { closeTab(); } } public boolean ensureActiveTabIsNotClosed() { boolean result = false; List<String> tabHandles = getTabHandles(); int currentTab = getCurrentTabIndex(tabHandles); if (currentTab < 0) { result = true; goToTab(tabHandles, 0); } return result; } public int tabCount() { return getTabHandles().size(); } public int currentTabIndex() { return getCurrentTabIndex(getTabHandles()) + 1; } protected int getCurrentTabIndex(List<String> tabHandles) { return getSeleniumHelper().getCurrentTabIndex(tabHandles); } protected void goToTab(List<String> tabHandles, int indexToGoTo) { getSeleniumHelper().goToTab(tabHandles, indexToGoTo); } protected List<String> getTabHandles() { return getSeleniumHelper().getTabHandles(); } /** * Activates main/top-level iframe (i.e. makes it the current frame). */ public void switchToDefaultContent() { getSeleniumHelper().switchToDefaultContent(); clearSearchContext(); } /** * Activates specified child frame of current iframe. * @param technicalSelector selector to find iframe. * @return true if iframe was found. */ public boolean switchToFrame(String technicalSelector) { boolean result = false; T iframe = getElement(technicalSelector); if (iframe != null) { getSeleniumHelper().switchToFrame(iframe); result = true; } return result; } /** * Activates parent frame of current iframe. * Does nothing if when current frame is the main/top-level one. */ public void switchToParentFrame() { getSeleniumHelper().switchToParentFrame(); } public String pageTitle() { return getSeleniumHelper().getPageTitle(); } /** * @return current page's content type. */ public String pageContentType() { String result = null; Object ct = getSeleniumHelper().executeJavascript("return document.contentType;"); if (ct != null) { result = ct.toString(); } return result; } /** * Replaces content at place by value. * @param value value to set. * @param place element to set value on. * @return true, if element was found. */ @WaitUntil public boolean enterAs(String value, String place) { return enterAsIn(value, place, null); } /** * Replaces content at place by value. * @param value value to set. * @param place element to set value on. * @param container element containing place. * @return true, if element was found. */ @WaitUntil public boolean enterAsIn(String value, String place, String container) { return enter(value, place, container, true); } /** * Adds content to place. * @param value value to add. * @param place element to add value to. * @return true, if element was found. */ @WaitUntil public boolean enterFor(String value, String place) { return enterForIn(value, place, null); } /** * Adds content to place. * @param value value to add. * @param place element to add value to. * @param container element containing place. * @return true, if element was found. */ @WaitUntil public boolean enterForIn(String value, String place, String container) { return enter(value, place, container, false); } protected boolean enter(String value, String place, boolean shouldClear) { return enter(value, place, null, shouldClear); } protected boolean enter(String value, String place, String container, boolean shouldClear) { WebElement element = getElementToSendValue(place, container); return enter(element, value, shouldClear); } protected boolean enter(WebElement element, String value, boolean shouldClear) { boolean result = element != null && isInteractable(element); if (result) { if (isSelect(element)) { result = clickSelectOption(element, value); } else { if (shouldClear) { clear(element); } sendValue(element, value); } } return result; } @WaitUntil public boolean enterDateAs(String date, String place) { WebElement element = getElementToSendValue(place); boolean result = element != null && isInteractable(element); if (result) { getSeleniumHelper().fillDateInput(element, date); } return result; } protected T getElementToSendValue(String place) { return getElementToSendValue(place, null); } protected T getElementToSendValue(String place, String container) { return getElement(place, container); } /** * Simulates pressing the 'Tab' key. * @return true, if an element was active the key could be sent to. */ public boolean pressTab() { return sendKeysToActiveElement(Keys.TAB); } /** * Simulates pressing the 'Enter' key. * @return true, if an element was active the key could be sent to. */ public boolean pressEnter() { return sendKeysToActiveElement(Keys.ENTER); } /** * Simulates pressing the 'Esc' key. * @return true, if an element was active the key could be sent to. */ public boolean pressEsc() { return sendKeysToActiveElement(Keys.ESCAPE); } /** * Simulates typing a text to the current active element. * @param text text to type. * @return true, if an element was active the text could be sent to. */ public boolean type(String text) { String value = cleanupValue(text); return sendKeysToActiveElement(value); } public boolean press(String key) { CharSequence s; String[] parts = key.split("\\s*\\+\\s*"); if (parts.length > 1 && !"".equals(parts[0]) && !"".equals(parts[1])) { CharSequence[] sequence = new CharSequence[parts.length]; for (int i = 0; i < parts.length; i++) { sequence[i] = parseKey(parts[i]); } s = Keys.chord(sequence); } else { s = parseKey(key); } return sendKeysToActiveElement(s); } protected CharSequence parseKey(String key) { CharSequence s; try { s = Keys.valueOf(key.toUpperCase()); } catch (IllegalArgumentException e) { s = key; } return s; } /** * Simulates pressing keys. * @param keys keys to press. * @return true, if an element was active the keys could be sent to. */ protected boolean sendKeysToActiveElement(CharSequence keys) { boolean result = false; WebElement element = getSeleniumHelper().getActiveElement(); if (element != null) { element.sendKeys(keys); result = true; } return result; } /** * Sends Fitnesse cell content to element. * @param element element to call sendKeys() on. * @param value cell content. */ protected void sendValue(WebElement element, String value) { if (StringUtils.isNotEmpty(value)) { String keys = cleanupValue(value); element.sendKeys(keys); } } @WaitUntil public boolean selectAs(String value, String place) { return selectFor(value, place); } @WaitUntil public boolean selectFor(String value, String place) { WebElement element = getElementToSelectFor(place); return clickSelectOption(element, value); } @WaitUntil public boolean selectForIn(String value, String place, String container) { return Boolean.TRUE.equals(doInContainer(container, () -> selectFor(value, place))); } @WaitUntil public boolean enterForHidden(String value, String idOrName) { return getSeleniumHelper().setHiddenInputValue(idOrName, value); } protected T getElementToSelectFor(String selectPlace) { return getElement(selectPlace); } protected boolean clickSelectOption(WebElement element, String optionValue) { boolean result = false; if (element != null) { if (isSelect(element)) { optionValue = cleanupValue(optionValue); By optionBy = new OptionBy(optionValue); WebElement option = optionBy.findElement(element); if (option != null) { result = clickElement(option); } } } return result; } @WaitUntil public boolean click(String place) { return clickImp(place, null); } @WaitUntil(TimeoutPolicy.RETURN_FALSE) public boolean clickIfAvailable(String place) { return clickIfAvailableIn(place, null); } @WaitUntil(TimeoutPolicy.RETURN_FALSE) public boolean clickIfAvailableIn(String place, String container) { return clickImp(place, container); } @WaitUntil public boolean clickIn(String place, String container) { return clickImp(place, container); } protected boolean clickImp(String place, String container) { boolean result = false; place = cleanupValue(place); try { WebElement element = getElementToClick(place, container); result = clickElement(element); } catch (WebDriverException e) { // if other element hides the element (in Chrome) an exception is thrown String msg = e.getMessage(); if (msg == null || !msg.contains("Other element would receive the click")) { throw e; } } return result; } @WaitUntil public boolean doubleClick(String place) { return doubleClickIn(place, null); } @WaitUntil public boolean doubleClickIn(String place, String container) { WebElement element = getElementToClick(place, container); return doubleClick(element); } protected boolean doubleClick(WebElement element) { boolean result = false; if (element != null) { scrollIfNotOnScreen(element); if (isInteractable(element)) { getSeleniumHelper().doubleClick(element); result = true; } } return result; } @WaitUntil public boolean rightClick(String place) { return rightClickIn(place, null); } @WaitUntil public boolean rightClickIn(String place, String container) { WebElement element = getElementToClick(place, container); return rightClick(element); } protected boolean rightClick(WebElement element) { boolean result = false; if (element != null) { scrollIfNotOnScreen(element); if (isInteractable(element)) { getSeleniumHelper().rightClick(element); result = true; } } return result; } @WaitUntil public boolean dragAndDropTo(String source, String destination) { WebElement sourceElement = getElementToClick(source); WebElement destinationElement = getElementToClick(destination); return dragAndDropTo(sourceElement, destinationElement); } protected boolean dragAndDropTo(WebElement sourceElement, WebElement destinationElement) { boolean result = false; if ((sourceElement != null) && (destinationElement != null)) { scrollIfNotOnScreen(sourceElement); if (isInteractable(sourceElement) && destinationElement.isDisplayed()) { getSeleniumHelper().dragAndDrop(sourceElement, destinationElement); result = true; } } return result; } protected T getElementToClick(String place) { return getSeleniumHelper().getElementToClick(place); } protected T getElementToClick(String place, String container) { return doInContainer(container, () -> getElementToClick(place)); } protected <R> R doInContainer(String container, Supplier<R> action) { R result = null; if (container == null) { result = action.get(); } else { T containerElement = getContainerElement(container); if (containerElement != null) { result = doInContainer(containerElement, action); } } return result; } protected <R> R doInContainer(T container, Supplier<R> action) { return getSeleniumHelper().doInContext(container, action); } @WaitUntil public boolean setSearchContextTo(String container) { boolean result = false; WebElement containerElement = getContainerElement(container); if (containerElement != null) { setSearchContextTo(containerElement); result = true; } return result; } protected void setSearchContextTo(SearchContext containerElement) { getSeleniumHelper().setCurrentContext(containerElement); } public void clearSearchContext() { getSeleniumHelper().setCurrentContext(null); } protected T getContainerElement(String container) { return findByTechnicalSelectorOr(container, this::getContainerImpl); } protected T getContainerImpl(String container) { return findElement(ContainerBy.heuristic(container)); } protected boolean clickElement(WebElement element) { boolean result = false; if (element != null) { scrollIfNotOnScreen(element); if (isInteractable(element)) { element.click(); result = true; } } return result; } protected boolean isInteractable(WebElement element) { return getSeleniumHelper().isInteractable(element); } @WaitUntil(TimeoutPolicy.STOP_TEST) public boolean waitForPage(String pageName) { return pageTitle().equals(pageName); } public boolean waitForTagWithText(String tagName, String expectedText) { return waitForElementWithText(By.tagName(tagName), expectedText); } public boolean waitForClassWithText(String cssClassName, String expectedText) { return waitForElementWithText(By.className(cssClassName), expectedText); } protected boolean waitForElementWithText(By by, String expectedText) { String textToLookFor = cleanExpectedValue(expectedText); return waitUntilOrStop(webDriver -> { boolean ok = false; List<WebElement> elements = webDriver.findElements(by); if (elements != null) { for (WebElement element : elements) { // we don't want stale elements to make single // element false, but instead we stop processing // current list and do a new findElements ok = hasText(element, textToLookFor); if (ok) { // no need to continue to check other elements break; } } } return ok; }); } protected String cleanExpectedValue(String expectedText) { return cleanupValue(expectedText); } protected boolean hasText(WebElement element, String textToLookFor) { boolean ok; String actual = getElementText(element); if (textToLookFor == null) { ok = actual == null; } else { if (StringUtils.isEmpty(actual)) { String value = element.getAttribute("value"); if (!StringUtils.isEmpty(value)) { actual = value; } } if (actual != null) { actual = actual.trim(); } ok = textToLookFor.equals(actual); } return ok; } @WaitUntil(TimeoutPolicy.STOP_TEST) public boolean waitForClass(String cssClassName) { boolean ok = false; WebElement element = findElement(By.className(cssClassName)); if (element != null) { ok = true; } return ok; } @WaitUntil(TimeoutPolicy.STOP_TEST) public boolean waitForVisible(String place) { return waitForVisibleIn(place, null); } @WaitUntil(TimeoutPolicy.STOP_TEST) public boolean waitForVisibleIn(String place, String container) { Boolean result = Boolean.FALSE; WebElement element = getElementToCheckVisibility(place, container); if (element != null) { scrollIfNotOnScreen(element); result = element.isDisplayed(); } return result; } /** * @deprecated use #waitForVisible(xpath=) instead */ @Deprecated public boolean waitForXPathVisible(String xPath) { By by = By.xpath(xPath); return waitForVisible(by); } @Deprecated protected boolean waitForVisible(By by) { return waitUntilOrStop(webDriver -> { Boolean result = Boolean.FALSE; WebElement element = findElement(by); if (element != null) { scrollIfNotOnScreen(element); result = element.isDisplayed(); } return result; }); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public String valueOf(String place) { return valueFor(place); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public String valueFor(String place) { return valueForIn(place, null); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public String valueOfIn(String place, String container) { return valueForIn(place, container); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public String valueForIn(String place, String container) { WebElement element = getElementToRetrieveValue(place, container); return valueFor(element); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public String normalizedValueOf(String place) { return normalizedValueFor(place); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public String normalizedValueFor(String place) { return normalizedValueForIn(place, null); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public String normalizedValueOfIn(String place, String container) { return normalizedValueForIn(place, container); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public String normalizedValueForIn(String place, String container) { String value = valueForIn(place, container); return XPathBy.getNormalizedText(value); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public String tooltipFor(String place) { return tooltipForIn(place, null); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public String tooltipForIn(String place, String container) { return valueOfAttributeOnIn("title", place, container); } @WaitUntil public String targetOfLink(String place) { WebElement linkElement = getSeleniumHelper().getLink(place); return getLinkTarget(linkElement); } protected String getLinkTarget(WebElement linkElement) { String target = null; if (linkElement != null) { target = linkElement.getAttribute("href"); } return target; } @WaitUntil(TimeoutPolicy.RETURN_NULL) public String valueOfAttributeOn(String attribute, String place) { return valueOfAttributeOnIn(attribute, place, null); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public String valueOfAttributeOnIn(String attribute, String place, String container) { String result = null; WebElement element = getElementToRetrieveValue(place, container); if (element != null) { result = element.getAttribute(attribute); } return result; } protected T getElementToRetrieveValue(String place, String container) { return getElement(place, container); } protected String valueFor(By by) { WebElement element = getSeleniumHelper().findElement(by); return valueFor(element); } protected String valueFor(WebElement element) { String result = null; if (element != null) { if (isSelect(element)) { Select s = new Select(element); List<WebElement> options = s.getAllSelectedOptions(); if (options.size() > 0) { result = getElementText(options.get(0)); } } else { String elementType = element.getAttribute("type"); if ("checkbox".equals(elementType) || "radio".equals(elementType)) { result = String.valueOf(element.isSelected()); } else if ("li".equalsIgnoreCase(element.getTagName())) { result = getElementText(element); } else { result = element.getAttribute("value"); if (result == null) { result = getElementText(element); } } } } return result; } private boolean isSelect(WebElement element) { return "select".equalsIgnoreCase(element.getTagName()); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public ArrayList<String> valuesOf(String place) { return valuesFor(place); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public ArrayList<String> valuesOfIn(String place, String container) { return valuesForIn(place, container); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public ArrayList<String> valuesFor(String place) { return valuesForIn(place, null); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public ArrayList<String> valuesForIn(String place, String container) { ArrayList<String> values = null; WebElement element = getElementToRetrieveValue(place, container); if (element != null) { values = new ArrayList<String>(); String tagName = element.getTagName(); if ("ul".equalsIgnoreCase(tagName) || "ol".equalsIgnoreCase(tagName)) { List<WebElement> items = element.findElements(By.tagName("li")); for (WebElement item : items) { if (item.isDisplayed()) { values.add(getElementText(item)); } } } else if (isSelect(element)) { Select s = new Select(element); List<WebElement> options = s.getAllSelectedOptions(); for (WebElement item : options) { values.add(getElementText(item)); } } else { values.add(valueFor(element)); } } return values; } @WaitUntil(TimeoutPolicy.RETURN_NULL) public Integer numberFor(String place) { Integer number = null; WebElement element = findElement(ListItemBy.numbered(place)); if (element != null) { scrollIfNotOnScreen(element); number = getSeleniumHelper().getNumberFor(element); } return number; } @WaitUntil(TimeoutPolicy.RETURN_NULL) public Integer numberForIn(String place, String container) { return doInContainer(container, () -> numberFor(place)); } public ArrayList<String> availableOptionsFor(String place) { ArrayList<String> result = null; WebElement element = getElementToSelectFor(place); if (element != null) { scrollIfNotOnScreen(element); result = getSeleniumHelper().getAvailableOptions(element); } return result; } @WaitUntil public boolean clear(String place) { return clearIn(place, null); } @WaitUntil public boolean clearIn(String place, String container) { boolean result = false; WebElement element = getElementToClear(place, container); if (element != null) { clear(element); result = true; } return result; } protected void clear(WebElement element) { element.clear(); } protected T getElementToClear(String place, String container) { return getElementToSendValue(place, container); } @WaitUntil public boolean enterAsInRowWhereIs(String value, String requestedColumnName, String selectOnColumn, String selectOnValue) { By cellBy = GridBy.columnInRowWhereIs(requestedColumnName, selectOnColumn, selectOnValue); WebElement element = findElement(cellBy); return enter(element, value, true); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public String valueOfColumnNumberInRowNumber(int columnIndex, int rowIndex) { By by = GridBy.coordinates(columnIndex, rowIndex); return valueFor(by); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public String valueOfInRowNumber(String requestedColumnName, int rowIndex) { By by = GridBy.columnInRow(requestedColumnName, rowIndex); return valueFor(by); } @WaitUntil(TimeoutPolicy.RETURN_NULL) public String valueOfInRowWhereIs(String requestedColumnName, String selectOnColumn, String selectOnValue) { By by = GridBy.columnInRowWhereIs(requestedColumnName, selectOnColumn, selectOnValue); return valueFor(by); } @WaitUntil(TimeoutPolicy.RETURN_FALSE) public boolean rowExistsWhereIs(String selectOnColumn, String selectOnValue) { return findElement(GridBy.rowWhereIs(selectOnColumn, selectOnValue)) != null; } @WaitUntil public boolean clickInRowNumber(String place, int rowIndex) { By rowBy = GridBy.rowNumber(rowIndex); return clickInRow(rowBy, place); } @WaitUntil public boolean clickInRowWhereIs(String place, String selectOnColumn, String selectOnValue) { By rowBy = GridBy.rowWhereIs(selectOnColumn, selectOnValue); return clickInRow(rowBy, place); } protected boolean clickInRow(By rowBy, String place) { boolean result = false; T row = findElement(rowBy); if (row != null) { result = doInContainer(row, () -> click(place)); } return result; } /** * Downloads the target of a link in a grid's row. * @param place which link to download. * @param rowNumber (1-based) row number to retrieve link from. * @return downloaded file if any, null otherwise. */ @WaitUntil public String downloadFromRowNumber(String place, int rowNumber) { return downloadFromRow(GridBy.linkInRow(place, rowNumber)); } /** * Downloads the target of a link in a grid, finding the row based on one of the other columns' value. * @param place which link to download. * @param selectOnColumn column header of cell whose value must be selectOnValue. * @param selectOnValue value to be present in selectOnColumn to find correct row. * @return downloaded file if any, null otherwise. */ @WaitUntil public String downloadFromRowWhereIs(String place, String selectOnColumn, String selectOnValue) { return downloadFromRow(GridBy.linkInRowWhereIs(place, selectOnColumn, selectOnValue)); } protected String downloadFromRow(By linkBy) { String result = null; WebElement element = findElement(linkBy); if (element != null) { result = downloadLinkTarget(element); } return result; } protected T getElement(String place) { return getSeleniumHelper().getElement(place); } protected T getElement(String place, String container) { return doInContainer(container, () -> getElement(place)); } /** * @deprecated use #click(xpath=) instead. */ @WaitUntil @Deprecated public boolean clickByXPath(String xPath) { WebElement element = findByXPath(xPath); return clickElement(element); } /** * @deprecated use #valueOf(xpath=) instead. */ @WaitUntil(TimeoutPolicy.RETURN_NULL) @Deprecated public String textByXPath(String xPath) { return getTextByXPath(xPath); } protected String getTextByXPath(String xpathPattern, String... params) { WebElement element = findByXPath(xpathPattern, params); return getElementText(element); } /** * @deprecated use #valueOf(css=.) instead. */ @WaitUntil(TimeoutPolicy.RETURN_NULL) @Deprecated public String textByClassName(String className) { return getTextByClassName(className); } protected String getTextByClassName(String className) { WebElement element = findByClassName(className); return getElementText(element); } protected T findByClassName(String className) { By by = By.className(className); return findElement(by); } protected T findByXPath(String xpathPattern, String... params) { return getSeleniumHelper().findByXPath(xpathPattern, params); } protected T findByCss(String cssPattern, String... params) { By by = getSeleniumHelper().byCss(cssPattern, params); return findElement(by); } protected T findByJavascript(String script, Object... parameters) { By by = getSeleniumHelper().byJavascript(script, parameters); return findElement(by); } protected List<T> findAllByXPath(String xpathPattern, String... params) { By by = getSeleniumHelper().byXpath(xpathPattern, params); return findElements(by); } protected List<T> findAllByCss(String cssPattern, String... params) { By by = getSeleniumHelper().byCss(cssPattern, params); return findElements(by); } protected List<T> findAllByJavascript(String script, Object... parameters) { By by = getSeleniumHelper().byJavascript(script, parameters); return findElements(by); } protected List<T> findElements(By by) { List elements = driver().findElements(by); return elements; } public void waitMilliSecondAfterScroll(int msToWait) { waitAfterScroll = msToWait; } protected int getWaitAfterScroll() { return waitAfterScroll; } protected String getElementText(WebElement element) { String result = null; if (element != null) { scrollIfNotOnScreen(element); result = getSeleniumHelper().getText(element); } return result; } /** * Scrolls browser window so top of place becomes visible. * @param place element to scroll to. */ @WaitUntil public boolean scrollTo(String place) { return scrollToIn(place, null); } /** * Scrolls browser window so top of place becomes visible. * @param place element to scroll to. * @param container parent of place. */ @WaitUntil public boolean scrollToIn(String place, String container) { boolean result = false; WebElement element = getElementToScrollTo(place, container); if (element != null) { scrollTo(element); result = true; } return result; } protected T getElementToScrollTo(String place, String container) { return getElementToCheckVisibility(place, container); } /** * Scrolls browser window so top of element becomes visible. * @param element element to scroll to. */ protected void scrollTo(WebElement element) { getSeleniumHelper().scrollTo(element); waitAfterScroll(waitAfterScroll); } /** * Wait after the scroll if needed * @param msToWait amount of ms to wait after the scroll */ protected void waitAfterScroll(int msToWait) { if (msToWait > 0) { waitMilliseconds(msToWait); } } /** * Scrolls browser window if element is not currently visible so top of element becomes visible. * @param element element to scroll to. */ protected void scrollIfNotOnScreen(WebElement element) { if (!element.isDisplayed() || !isElementOnScreen(element)) { scrollTo(element); } } /** * Determines whether element is enabled (i.e. can be clicked). * @param place element to check. * @return true if element is enabled. */ @WaitUntil(TimeoutPolicy.RETURN_FALSE) public boolean isEnabled(String place) { return isEnabledIn(place, null); } /** * Determines whether element is enabled (i.e. can be clicked). * @param place element to check. * @param container parent of place. * @return true if element is enabled. */ @WaitUntil(TimeoutPolicy.RETURN_FALSE) public boolean isEnabledIn(String place, String container) { boolean result = false; T element = getElementToCheckVisibility(place, container); if (element != null) { if ("label".equalsIgnoreCase(element.getTagName())) { // for labels we want to know whether their target is enabled, not the label itself T labelTarget = getSeleniumHelper().getLabelledElement(element); if (labelTarget != null) { element = labelTarget; } } result = element.isEnabled(); } return result; } /** * Determines whether element can be see in browser's window. * @param place element to check. * @return true if element is displayed and in viewport. */ @WaitUntil(TimeoutPolicy.RETURN_FALSE) public boolean isVisible(String place) { return isVisibleIn(place, null); } /** * Determines whether element can be see in browser's window. * @param place element to check. * @param container parent of place. * @return true if element is displayed and in viewport. */ @WaitUntil(TimeoutPolicy.RETURN_FALSE) public boolean isVisibleIn(String place, String container) { return isVisibleImpl(place, container, true); } /** * Determines whether element is somewhere in browser's window. * @param place element to check. * @return true if element is displayed. */ @WaitUntil(TimeoutPolicy.RETURN_FALSE) public boolean isVisibleOnPage(String place) { return isVisibleOnPageIn(place, null); } /** * Determines whether element is somewhere in browser's window. * @param place element to check. * @param container parent of place. * @return true if element is displayed. */ @WaitUntil(TimeoutPolicy.RETURN_FALSE) public boolean isVisibleOnPageIn(String place, String container) { return isVisibleImpl(place, container, false); } protected boolean isVisibleImpl(String place, String container, boolean checkOnScreen) { WebElement element = getElementToCheckVisibility(place, container); return getSeleniumHelper().checkVisible(element, checkOnScreen); } public int numberOfTimesIsVisible(String text) { return numberOfTimesIsVisibleInImpl(text, true); } public int numberOfTimesIsVisibleOnPage(String text) { return numberOfTimesIsVisibleInImpl(text, false); } public int numberOfTimesIsVisibleIn(String text, String container) { return intValueOf(doInContainer(container, () -> numberOfTimesIsVisible(text))); } public int numberOfTimesIsVisibleOnPageIn(String text, String container) { return intValueOf(doInContainer(container, () -> numberOfTimesIsVisibleOnPage(text))); } protected int intValueOf(Integer count) { if (count == null) { count = Integer.valueOf(0); } return count; } protected int numberOfTimesIsVisibleInImpl(String text, boolean checkOnScreen) { return getSeleniumHelper().countVisibleOccurrences(text, checkOnScreen); } protected T getElementToCheckVisibility(String place) { T result = findElement(TextBy.partial(place)); if (result == null || !result.isDisplayed()) { result = getElementToClick(place); } return result; } protected T getElementToCheckVisibility(String place, String container) { return doInContainer(container, () -> findByTechnicalSelectorOr(place, this::getElementToCheckVisibility)); } /** * Checks whether element is in browser's viewport. * @param element element to check * @return true if element is in browser's viewport. */ protected boolean isElementOnScreen(WebElement element) { Boolean onScreen = getSeleniumHelper().isElementOnScreen(element); return onScreen == null || onScreen.booleanValue(); } @WaitUntil public boolean hoverOver(String place) { return hoverOverIn(place, null); } @WaitUntil public boolean hoverOverIn(String place, String container) { WebElement element = getElementToClick(place, container); return hoverOver(element); } protected boolean hoverOver(WebElement element) { boolean result = false; if (element != null) { scrollIfNotOnScreen(element); if (element.isDisplayed()) { getSeleniumHelper().hoverOver(element); result = true; } } return result; } /** * @param timeout number of seconds before waitUntil() and waitForJavascriptCallback() throw TimeOutException. */ public void secondsBeforeTimeout(int timeout) { secondsBeforeTimeout = timeout; secondsBeforePageLoadTimeout(timeout); int timeoutInMs = timeout * 1000; getSeleniumHelper().setScriptWait(timeoutInMs); } /** * @return number of seconds waitUntil() will wait at most. */ public int secondsBeforeTimeout() { return secondsBeforeTimeout; } /** * @param timeout number of seconds before waiting for a new page to load will throw a TimeOutException. */ public void secondsBeforePageLoadTimeout(int timeout) { secondsBeforePageLoadTimeout = timeout; int timeoutInMs = timeout * 1000; getSeleniumHelper().setPageLoadWait(timeoutInMs); } /** * @return number of seconds Selenium will wait at most for a request to load a page. */ public int secondsBeforePageLoadTimeout() { return secondsBeforePageLoadTimeout; } /** * Clears HTML5's localStorage (for the domain of the current open page in the browser). */ public void clearLocalStorage() { getSeleniumHelper().executeJavascript("localStorage.clear();"); } /** * Deletes all cookies(for the domain of the current open page in the browser). */ public void deleteAllCookies() { getSeleniumHelper().deleteAllCookies(); } /** * @param directory sets base directory where screenshots will be stored. */ public void screenshotBaseDirectory(String directory) { if (directory.equals("") || directory.endsWith("/") || directory.endsWith("\\")) { screenshotBase = directory; } else { screenshotBase = directory + "/"; } } /** * @param height height to use to display screenshot images */ public void screenshotShowHeight(String height) { screenshotHeight = height; } /** * @return (escaped) HTML content of current page. */ public String pageSource() { String html = getSeleniumHelper().getHtml(); return getEnvironment().getHtml(html); } /** * Saves current page's source to the wiki'f files section and returns a link to the * created file. * @return hyperlink to the file containing the page source. */ public String savePageSource() { String fileName = getSeleniumHelper().getResourceNameFromLocation(); return savePageSource(fileName, fileName + ".html"); } protected String savePageSource(String fileName, String linkText) { PageSourceSaver saver = getSeleniumHelper().getPageSourceSaver(pageSourceBase); // make href to file String url = saver.savePageSource(fileName); return String.format("<a href=\"%s\">%s</a>", url, linkText); } /** * Takes screenshot from current page * @param basename filename (below screenshot base directory). * @return location of screenshot. */ public String takeScreenshot(String basename) { try { String screenshotFile = createScreenshot(basename); if (screenshotFile == null) { throw new SlimFixtureException(false, "Unable to take screenshot: does the webdriver support it?"); } else { screenshotFile = getScreenshotLink(screenshotFile); } return screenshotFile; } catch (UnhandledAlertException e) { // standard behavior will stop test, this breaks storyboard that will attempt to take screenshot // after triggering alert, but before the alert can be handled. // so we output a message but no exception. We rely on a next line to actually handle alert // (which may mean either really handle or stop test). return String.format( "<div><strong>Unable to take screenshot</strong>, alert is active. Alert text:<br/>" + "'<span>%s</span>'</div>", StringEscapeUtils.escapeHtml4(alertText())); } } private String getScreenshotLink(String screenshotFile) { String wikiUrl = getWikiUrl(screenshotFile); if (wikiUrl != null) { // make href to screenshot if ("".equals(screenshotHeight)) { wikiUrl = String.format("<a href=\"%s\">%s</a>", wikiUrl, screenshotFile); } else { wikiUrl = String.format("<a href=\"%1$s\"><img src=\"%1$s\" title=\"%2$s\" height=\"%3$s\"/></a>", wikiUrl, screenshotFile, screenshotHeight); } screenshotFile = wikiUrl; } return screenshotFile; } private String createScreenshot(String basename) { String name = getScreenshotBasename(basename); return getSeleniumHelper().takeScreenshot(name); } private String createScreenshot(String basename, Throwable t) { String screenshotFile; byte[] screenshotInException = getSeleniumHelper().findScreenshot(t); if (screenshotInException == null || screenshotInException.length == 0) { screenshotFile = createScreenshot(basename); } else { String name = getScreenshotBasename(basename); screenshotFile = getSeleniumHelper().writeScreenshot(name, screenshotInException); } return screenshotFile; } private String getScreenshotBasename(String basename) { return screenshotBase + basename; } /** * Waits until the condition evaluates to a value that is neither null nor * false. Because of this contract, the return type must not be Void. * @param <T> the return type of the method, which must not be Void * @param condition condition to evaluate to determine whether waiting can be stopped. * @throws SlimFixtureException if condition was not met before secondsBeforeTimeout. * @return result of condition. */ protected <T> T waitUntil(ExpectedCondition<T> condition) { try { return waitUntilImpl(condition); } catch (TimeoutException e) { String message = getTimeoutMessage(e); return lastAttemptBeforeThrow(condition, new SlimFixtureException(false, message, e)); } } /** * Waits until the condition evaluates to a value that is neither null nor * false. If that does not occur the whole test is stopped. * Because of this contract, the return type must not be Void. * @param <T> the return type of the method, which must not be Void * @param condition condition to evaluate to determine whether waiting can be stopped. * @throws TimeoutStopTestException if condition was not met before secondsBeforeTimeout. * @return result of condition. */ protected <T> T waitUntilOrStop(ExpectedCondition<T> condition) { try { return waitUntilImpl(condition); } catch (TimeoutException e) { try { return handleTimeoutException(e); } catch (TimeoutStopTestException tste) { return lastAttemptBeforeThrow(condition, tste); } } } /** * Tries the condition one last time before throwing an exception. * This to prevent exception messages in the wiki that show no problem, which could happen if the browser's * window content has changed between last (failing) try at condition and generation of the exception. * @param <T> the return type of the method, which must not be Void * @param condition condition that caused exception. * @param e exception that will be thrown if condition does not return a result. * @return last attempt results, if not null. * @throws SlimFixtureException throws e if last attempt returns null. */ protected <T> T lastAttemptBeforeThrow(ExpectedCondition<T> condition, SlimFixtureException e) { T lastAttemptResult = null; try { // last attempt to ensure condition has not been met // this to prevent messages that show no problem lastAttemptResult = condition.apply(getSeleniumHelper().driver()); } catch (Throwable t) { // ignore } if (lastAttemptResult != null) { return lastAttemptResult; } throw e; } /** * Waits until the condition evaluates to a value that is neither null nor * false. If that does not occur null is returned. * Because of this contract, the return type must not be Void. * @param <T> the return type of the method, which must not be Void * @param condition condition to evaluate to determine whether waiting can be stopped. * @return result of condition. */ protected <T> T waitUntilOrNull(ExpectedCondition<T> condition) { try { return waitUntilImpl(condition); } catch (TimeoutException e) { return null; } } protected <T> T waitUntilImpl(ExpectedCondition<T> condition) { return getSeleniumHelper().waitUntil(secondsBeforeTimeout(), condition); } protected <T> T handleTimeoutException(TimeoutException e) { String message = getTimeoutMessage(e); throw new TimeoutStopTestException(false, message, e); } private String getTimeoutMessage(TimeoutException e) { String messageBase = String.format("Timed-out waiting (after %ss)", secondsBeforeTimeout()); return getSlimFixtureExceptionMessage("timeouts", "timeout", messageBase, e); } protected void handleRequiredElementNotFound(String toFind) { handleRequiredElementNotFound(toFind, null); } protected void handleRequiredElementNotFound(String toFind, Throwable t) { String messageBase = String.format("Unable to find: %s", toFind); String message = getSlimFixtureExceptionMessage("notFound", toFind, messageBase, t); throw new SlimFixtureException(false, message, t); } protected String getSlimFixtureExceptionMessage(String screenshotFolder, String screenshotFile, String messageBase, Throwable t) { String screenshotBaseName = String.format("%s/%s/%s", screenshotFolder, getClass().getSimpleName(), screenshotFile); return getSlimFixtureExceptionMessage(screenshotBaseName, messageBase, t); } protected String getSlimFixtureExceptionMessage(String screenshotBaseName, String messageBase, Throwable t) { String exceptionMsg = getExceptionMessageText(messageBase, t); // take a screenshot of what was on screen String screenshotTag = getExceptionScreenshotTag(screenshotBaseName, messageBase, t); String label = getExceptionPageSourceTag(screenshotBaseName, messageBase, t); String message = String.format("<div><div>%s.</div><div>%s:%s</div></div>", exceptionMsg, label, screenshotTag); return message; } protected String getExceptionMessageText(String messageBase, Throwable t) { String message = messageBase; if (message == null) { if (t == null) { message = ""; } else { message = ExceptionUtils.getStackTrace(t); } } return formatExceptionMsg(message); } protected String getExceptionScreenshotTag(String screenshotBaseName, String messageBase, Throwable t) { String screenshotTag = "(Screenshot not available)"; try { String screenShotFile = createScreenshot(screenshotBaseName, t); screenshotTag = getScreenshotLink(screenShotFile); } catch (UnhandledAlertException e) { System.err.println("Unable to take screenshot while alert is present for exception: " + messageBase); } catch (Exception sse) { System.err.println("Unable to take screenshot for exception: " + messageBase); sse.printStackTrace(); } return screenshotTag; } protected String getExceptionPageSourceTag(String screenshotBaseName, String messageBase, Throwable t) { String label = "Page content"; try { String fileName; if (t != null) { fileName = t.getClass().getName(); } else if (screenshotBaseName != null) { fileName = screenshotBaseName; } else { fileName = "exception"; } label = savePageSource(fileName, label); } catch (UnhandledAlertException e) { System.err.println("Unable to capture page source while alert is present for exception: " + messageBase); } catch (Exception e) { System.err.println("Unable to capture page source for exception: " + messageBase); e.printStackTrace(); } return label; } protected String formatExceptionMsg(String value) { return StringEscapeUtils.escapeHtml4(value); } private WebDriver driver() { return getSeleniumHelper().driver(); } private WebDriverWait waitDriver() { return getSeleniumHelper().waitDriver(); } /** * @return helper to use. */ protected SeleniumHelper<T> getSeleniumHelper() { return seleniumHelper; } /** * Sets SeleniumHelper to use, for testing purposes. * @param helper helper to use. */ protected void setSeleniumHelper(SeleniumHelper<T> helper) { seleniumHelper = helper; } public int currentBrowserWidth() { return getWindowSize().getWidth(); } public int currentBrowserHeight() { return getWindowSize().getHeight(); } public void setBrowserWidth(int newWidth) { int currentHeight = currentBrowserHeight(); setBrowserSizeToBy(newWidth, currentHeight); } public void setBrowserHeight(int newHeight) { int currentWidth = currentBrowserWidth(); setBrowserSizeToBy(currentWidth, newHeight); } public void setBrowserSizeToBy(int newWidth, int newHeight) { getSeleniumHelper().setWindowSize(newWidth, newHeight); Dimension actualSize = getWindowSize(); if (actualSize.getHeight() != newHeight || actualSize.getWidth() != newWidth) { String message = String.format("Unable to change size to: %s x %s; size is: %s x %s", newWidth, newHeight, actualSize.getWidth(), actualSize.getHeight()); throw new SlimFixtureException(false, message); } } protected Dimension getWindowSize() { return getSeleniumHelper().getWindowSize(); } public void setBrowserSizeToMaximum() { getSeleniumHelper().setWindowSizeToMaximum(); } /** * Downloads the target of the supplied link. * @param place link to follow. * @return downloaded file if any, null otherwise. */ @WaitUntil public String download(String place) { WebElement element = getSeleniumHelper().getLink(place); return downloadLinkTarget(element); } /** * Downloads the target of the supplied link. * @param place link to follow. * @param container part of screen containing link. * @return downloaded file if any, null otherwise. */ @WaitUntil public String downloadIn(String place, String container) { return doInContainer(container, () -> download(place)); } protected T findElement(By selector) { return getSeleniumHelper().findElement(selector); } public T findByTechnicalSelectorOr(String place, Function<String, ? extends T> supplierF) { return getSeleniumHelper().findByTechnicalSelectorOr(place, () -> supplierF.apply(place)); } /** * Downloads the target of the supplied link. * @param element link to follow. * @return downloaded file if any, null otherwise. */ protected String downloadLinkTarget(WebElement element) { String result; String href = getLinkTarget(element); if (href != null) { result = downloadContentFrom(href); } else { throw new SlimFixtureException(false, "Could not determine url to download from"); } return result; } /** * Downloads binary content from specified url (using the browser's cookies). * @param urlOrLink url to download from * @return link to downloaded file */ public String downloadContentFrom(String urlOrLink) { String result = null; if (urlOrLink != null) { String url = getUrl(urlOrLink); BinaryHttpResponse resp = new BinaryHttpResponse(); getUrlContent(url, resp); byte[] content = resp.getResponseContent(); if (content == null) { result = resp.getResponse(); } else { String fileName = resp.getFileName(); if (StringUtils.isEmpty(fileName)) { fileName = "download"; } String baseName = FilenameUtils.getBaseName(fileName); String ext = FilenameUtils.getExtension(fileName); String downloadedFile = FileUtil.saveToFile(getDownloadName(baseName), ext, content); String wikiUrl = getWikiUrl(downloadedFile); if (wikiUrl != null) { // make href to file result = String.format("<a href=\"%s\">%s</a>", wikiUrl, fileName); } else { result = downloadedFile; } } } return result; } /** * Selects a file using the first file upload control. * @param fileName file to upload * @return true, if a file input was found and file existed. */ @WaitUntil public boolean selectFile(String fileName) { return selectFileFor(fileName, "css=input[type='file']"); } /** * Selects a file using a file upload control. * @param fileName file to upload * @param place file input to select the file for * @return true, if place was a file input and file existed. */ @WaitUntil public boolean selectFileFor(String fileName, String place) { return selectFileForIn(fileName, place, null); } /** * Selects a file using a file upload control. * @param fileName file to upload * @param place file input to select the file for * @param container part of screen containing place * @return true, if place was a file input and file existed. */ @WaitUntil public boolean selectFileForIn(String fileName, String place, String container) { boolean result = false; if (fileName != null) { String fullPath = getFilePathFromWikiUrl(fileName); if (new File(fullPath).exists()) { WebElement element = getElementToSelectFile(place, container); if (element != null) { element.sendKeys(fullPath); result = true; } } else { throw new SlimFixtureException(false, "Unable to find file: " + fullPath); } } return result; } protected T getElementToSelectFile(String place, String container) { T result = null; T element = getElement(place, container); if (element != null && "input".equalsIgnoreCase(element.getTagName()) && "file".equalsIgnoreCase(element.getAttribute("type"))) { result = element; } return result; } private String getDownloadName(String baseName) { return downloadBase + baseName; } /** * GETs content of specified URL, using the browsers cookies. * @param url url to retrieve content from * @param resp response to store content in */ protected void getUrlContent(String url, HttpResponse resp) { getEnvironment().addSeleniumCookies(resp); getEnvironment().doGet(url, resp); } /** * Gets the value of the cookie with the supplied name. * @param cookieName name of cookie to get value from. * @return cookie's value if any. */ public String cookieValue(String cookieName) { String result = null; Cookie cookie = getSeleniumHelper().getCookie(cookieName); if (cookie != null) { result = cookie.getValue(); } return result; } public boolean refreshUntilValueOfIs(String place, String expectedValue) { return repeatUntil(getRefreshUntilValueIs(place, expectedValue)); } public boolean refreshUntilValueOfIsNot(String place, String expectedValue) { return repeatUntilNot(getRefreshUntilValueIs(place, expectedValue)); } protected RepeatUntilValueIsCompletion getRefreshUntilValueIs(String place, String expectedValue) { return new RepeatUntilValueIsCompletion(place, expectedValue) { @Override public void repeat() { refresh(); } }; } public boolean clickUntilValueOfIs(String clickPlace, String checkPlace, String expectedValue) { return repeatUntil(getClickUntilValueIs(clickPlace, checkPlace, expectedValue)); } public boolean clickUntilValueOfIsNot(String clickPlace, String checkPlace, String expectedValue) { return repeatUntilNot(getClickUntilValueIs(clickPlace, checkPlace, expectedValue)); } public boolean executeJavascriptUntilIs(String script, String place, String value) { return repeatUntil(getExecuteScriptUntilValueIs(script, place, value)); } public boolean executeJavascriptUntilIsNot(String script, String place, String value) { return repeatUntilNot(getExecuteScriptUntilValueIs(script, place, value)); } protected RepeatUntilValueIsCompletion getExecuteScriptUntilValueIs(String script, String place, String expectedValue) { return new RepeatUntilValueIsCompletion(place, expectedValue) { @Override public void repeat() { executeScript(script); } }; } protected RepeatUntilValueIsCompletion getClickUntilValueIs(String clickPlace, String checkPlace, String expectedValue) { String place = cleanupValue(clickPlace); return getClickUntilCompletion(place, checkPlace, expectedValue); } protected RepeatUntilValueIsCompletion getClickUntilCompletion(String place, String checkPlace, String expectedValue) { ExpectedCondition<Object> condition = wrapConditionForFramesIfNeeded(webDriver -> click(place)); return new RepeatUntilValueIsCompletion(checkPlace, expectedValue) { @Override public void repeat() { waitUntil(condition); } }; } protected <T> ExpectedCondition<T> wrapConditionForFramesIfNeeded(ExpectedCondition<T> condition) { if (implicitFindInFrames) { condition = getSeleniumHelper().conditionForAllFrames(condition); } return condition; } @Override protected boolean repeatUntil(RepeatCompletion repeat) { // During repeating we reduce the timeout used for finding elements, // but the page load timeout is kept as-is (which takes extra work because secondsBeforeTimeout(int) // also changes that. int previousTimeout = secondsBeforeTimeout(); int pageLoadTimeout = secondsBeforePageLoadTimeout(); try { int timeoutDuringRepeat = Math.max((Math.toIntExact(repeatInterval() / 1000)), 1); secondsBeforeTimeout(timeoutDuringRepeat); secondsBeforePageLoadTimeout(pageLoadTimeout); return super.repeatUntil(repeat); } finally { secondsBeforeTimeout(previousTimeout); secondsBeforePageLoadTimeout(pageLoadTimeout); } } protected abstract class RepeatUntilValueIsCompletion implements RepeatCompletion { private final String place; private final String expectedValue; protected RepeatUntilValueIsCompletion(String place, String expectedValue) { this.place = place; this.expectedValue = cleanExpectedValue(expectedValue); } @Override public boolean isFinished() { ExpectedCondition<Boolean> condition = wrapConditionForFramesIfNeeded(webDriver -> checkValueImpl()); Boolean valueFound = waitUntilOrNull(condition); return valueFound != null && valueFound; } protected boolean checkValueImpl() { boolean match; String actual = valueOf(place); if (expectedValue == null) { match = actual == null; } else { match = expectedValue.equals(actual); } return match; } } protected Object waitForJavascriptCallback(String statement, Object... parameters) { try { return getSeleniumHelper().waitForJavascriptCallback(statement, parameters); } catch (TimeoutException e) { return handleTimeoutException(e); } } public NgBrowserTest getNgBrowserTest() { return ngBrowserTest; } public void setNgBrowserTest(NgBrowserTest ngBrowserTest) { this.ngBrowserTest = ngBrowserTest; } public boolean isImplicitWaitForAngularEnabled() { return implicitWaitForAngular; } public void setImplicitWaitForAngularTo(boolean implicitWaitForAngular) { this.implicitWaitForAngular = implicitWaitForAngular; } public void setImplicitFindInFramesTo(boolean implicitFindInFrames) { this.implicitFindInFrames = implicitFindInFrames; } /** * Executes javascript in the browser. * @param script you want to execute * @return result from script */ public Object executeScript(String script) { String statement = cleanupValue(script); return getSeleniumHelper().executeJavascript(statement); } }
package nl.hsac.fitnesse.fixture.slim.web; import nl.hsac.fitnesse.fixture.slim.SlimFixture; import nl.hsac.fitnesse.fixture.util.SeleniumHelper; import org.openqa.selenium.*; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.FluentWait; import org.openqa.selenium.support.ui.WebDriverWait; import java.io.File; import java.util.List; import java.util.concurrent.TimeUnit; public class BrowserTest extends SlimFixture { private static final String ELEMENT_ON_SCREEN_JS = "var rect = arguments[0].getBoundingClientRect();\n" + "return (\n" + " rect.top >= 0 &&\n" + " rect.left >= 0 &&\n" + " rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&\n" + " rect.right <= (window.innerWidth || document.documentElement.clientWidth));"; private SeleniumHelper seleniumHelper = getEnvironment().getSeleniumHelper(); private int secondsBeforeTimeout; private int waitAfterScroll = 0; private final String filesDir = getEnvironment().getFitNesseFilesSectionDir(); private String screenshotBase = new File(filesDir, "screenshots").getPath() + "/"; private String screenshotHeight = "200"; public BrowserTest() { secondsBeforeTimeout(SeleniumHelper.DEFAULT_TIMEOUT_SECONDS); ensureActiveTabIsNotClosed(); } public boolean open(String address) { String url = getUrl(address); try { getNavigation().to(url); } catch (TimeoutException e) { throw new TimeoutStopTestException("Unable to go to: " + url, e); } return true; } public boolean back() { getNavigation().back(); // firefox sometimes prevents immediate back, if previous page was reached via POST waitMilliSeconds(500); WebElement element = getSeleniumHelper().findElement(By.id("errorTryAgain")); if (element != null) { element.click(); Alert alert = getSeleniumHelper().driver().switchTo().alert(); alert.accept(); } return true; } public boolean forward() { getNavigation().forward(); return true; } public boolean refresh() { getNavigation().refresh(); return true; } private WebDriver.Navigation getNavigation() { return getSeleniumHelper().navigate(); } public boolean openInNewTab(String url) { String cleanUrl = cleanupValue(url); final int tabCount = tabCount(); getSeleniumHelper().executeJavascript("window.open('%s', '_blank')", cleanUrl); // ensure new window is open waitUntil(new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver webDriver) { return tabCount() > tabCount; } }); return switchToNextTab(); } public boolean switchToNextTab() { boolean result = false; List<String> tabs = getTabHandles(); if (tabs.size() > 1) { int currentTab = getCurrentTabIndex(tabs); int nextTab = currentTab + 1; if (nextTab == tabs.size()) { nextTab = 0; } goToTab(tabs, nextTab); result = true; } return result; } public boolean switchToPreviousTab() { boolean result = false; List<String> tabs = getTabHandles(); if (tabs.size() > 1) { int currentTab = getCurrentTabIndex(tabs); int nextTab = currentTab - 1; if (nextTab < 0) { nextTab = tabs.size() - 1; } goToTab(tabs, nextTab); result = true; } return result; } public boolean closeTab() { boolean result = false; List<String> tabs = getTabHandles(); int currentTab = getCurrentTabIndex(tabs); int tabToGoTo = -1; if (currentTab > 0) { tabToGoTo = currentTab - 1; } else { if (tabs.size() > 1) { tabToGoTo = 1; } } if (tabToGoTo > -1) { WebDriver driver = getSeleniumHelper().driver(); driver.close(); goToTab(tabs, tabToGoTo); result = true; } return result; } public void ensureOnlyOneTab() { ensureActiveTabIsNotClosed(); int tabCount = tabCount(); for (int i = 1; i < tabCount; i++) { closeTab(); } } public boolean ensureActiveTabIsNotClosed() { boolean result = false; List<String> tabHandles = getTabHandles(); int currentTab = getCurrentTabIndex(tabHandles); if (currentTab < 0) { result = true; goToTab(tabHandles, 0); } return result; } public int tabCount() { return getTabHandles().size(); } public int currentTabIndex() { return getCurrentTabIndex(getTabHandles()) + 1; } protected int getCurrentTabIndex(List<String> tabHandles) { return getSeleniumHelper().getCurrentTabIndex(tabHandles); } protected void goToTab(List<String> tabHandles, int indexToGoTo) { getSeleniumHelper().goToTab(tabHandles, indexToGoTo); } protected List<String> getTabHandles() { return getSeleniumHelper().getTabHandles(); } public String pageTitle() { return getSeleniumHelper().getPageTitle(); } /** * @return current page's content type. */ public String pageContentType() { String result = null; Object ct = getSeleniumHelper().executeJavascript("return document.contentType;"); if (ct != null) { result = ct.toString(); } return result; } /** * Replaces content at place by value. * @param value value to set. * @param place element to set value on. * @return true, if element was found. */ public boolean enterAs(String value, String place) { final WebElement element = getElement(place); boolean result = waitUntilInteractable(element); if (result) { element.clear(); sendValue(element, value); } return result; } protected boolean waitUntilInteractable(final WebElement element) { return waitUntil(new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver webDriver) { return element != null && element.isDisplayed() && element.isEnabled(); } }); } /** * Adds content to place. * @param value value to add. * @param place element to add value to. * @return true, if element was found. */ public boolean enterFor(String value, String place) { boolean result = false; WebElement element = getElement(place); if (element != null) { sendValue(element, value); result = true; } return result; } /** * Simulates pressing the 'Tab' key. * @return true, if an element was active the key could be sent to. */ public boolean pressTab() { return sendKeysToActiveElement(Keys.TAB); } /** * Simulates pressing the 'Enter' key. * @return true, if an element was active the key could be sent to. */ public boolean pressEnter() { return sendKeysToActiveElement(Keys.ENTER); } /** * Simulates pressing the 'Esc' key. * @return true, if an element was active the key could be sent to. */ public boolean pressEsc() { return sendKeysToActiveElement(Keys.ESCAPE); } /** * Simulates pressing a key. * @param key key to press, can be a normal letter (e.g. 'M') or a special key (e.g. 'down'). * @return true, if an element was active the key could be sent to. */ public boolean press(String key) { CharSequence s; try { s = Keys.valueOf(key.toUpperCase()); } catch (IllegalArgumentException e) { s = key; } return sendKeysToActiveElement(s); } /** * Simulates pressing keys. * @param keys keys to press. * @return true, if an element was active the keys could be sent to. */ protected boolean sendKeysToActiveElement(CharSequence keys) { boolean result = false; WebElement element = getSeleniumHelper().getActiveElement(); if (element != null) { element.sendKeys(keys); result = true; } return result; } /** * Sends Fitnesse cell content to element. * @param element element to call sendKeys() on. * @param value cell content. */ protected void sendValue(WebElement element, String value) { String keys = cleanupValue(value); element.sendKeys(keys); } public boolean selectAs(String value, String place) { return selectFor(value, place); } public boolean selectFor(String value, String place) { // choose option for select, if possible boolean result = clickSelectOption(place, value); if (!result) { // try to click the first element with right value result = click(value); } return result; } public boolean enterForHidden(String value, String idOrName) { return getSeleniumHelper().setHiddenInputValue(idOrName, value); } private boolean clickSelectOption(String selectPlace, String optionValue) { boolean result = false; WebElement element = getElement(selectPlace); if (element != null) { if (isSelect(element)) { String attrToUse = "id"; String attrValue = element.getAttribute(attrToUse); if (attrValue == null || attrValue.isEmpty()) { attrToUse = "name"; attrValue = element.getAttribute(attrToUse); } if (attrValue != null && !attrValue.isEmpty()) { String xpathToOptions = "//select[@" + attrToUse + "='%s']//option"; result = clickOption(attrValue, xpathToOptions + "[text()='%s']", optionValue); if (!result) { result = clickOption(attrValue, xpathToOptions + "[contains(text(), '%s')]", optionValue); } } } } return result; } private boolean clickOption(String selectId, String optionXPath, String optionValue) { boolean result = false; By optionWithText = getSeleniumHelper().byXpath(optionXPath, selectId, optionValue); WebElement option = getSeleniumHelper().findElement(true, optionWithText); if (option != null) { result = clickElement(option); } return result; } public boolean click(String place) { // if other element hides the element (in Chrome) an exception is thrown // we retry clicking the element a few times before giving up. boolean result = false; boolean retry = true; for (int i = 0; !result && retry; i++) { try { if (i > 0) { waitSeconds(1); } result = clickImpl(place); } catch (WebDriverException e) { String msg = e.getMessage(); if (!msg.contains("Other element would receive the click") || i == secondsBeforeTimeout()) { retry = false; } } // don't wait forever trying to click // only try secondsBeforeTimeout + 1 times retry &= i < secondsBeforeTimeout(); } return result; } protected boolean clickImpl(String place) { WebElement element = getElement(place); if (element == null) { /** * Creates an XPath expression that will find a cell in a row, selecting the row based on the * text in a specific column (identified by its header text). * @param columnName header text of the column to find value in. * @param value text to find in column with the supplied header. * @return XPath expression selecting a td in the row */ protected String getXPathForColumnInRowByValueInOtherColumn(String columnName, String value) { String selectIndex = getXPathForColumnIndex(columnName); return String.format("//tr[normalize-space(td[%s]/descendant-or-self::text())='%s']/td", selectIndex, value); } /** * Creates an XPath expression that will determine, for a row, which index to use to select the cell in the column * with the supplied header text value. * @param columnName name of column in header (th) * @return XPath expression which can be used to select a td in a row */ protected String getXPathForColumnIndex(String columnName) { // determine how many columns are before the column with the requested name // the column with the requested name will have an index of the value +1 (since XPath indexes are 1 based) return String.format("count(//tr/th[normalize-space(descendant-or-self::text())='%s']/preceding-sibling::th)+1", columnName); } protected WebElement getElement(String place) { return getSeleniumHelper().getElement(place); } public String textByXPath(String xPath) { return getTextByXPath(xPath); } protected String getTextByXPath(String xpathPattern, String... params) { String result; try { WebElement element = findByXPath(xpathPattern, params); result = getElementText(element); } catch (StaleElementReferenceException e) { // sometime we are troubled by ajax updates that cause 'stale state' let's try once more if that is the case WebElement element = findByXPath(xpathPattern, params); result = getElementText(element); } return result; } public String textByClassName(String className) { return getTextByClassName(className); } protected String getTextByClassName(String className) { String result; try { WebElement element = findByClassName(className); result = getElementText(element); } catch (StaleElementReferenceException e) { // sometime we are troubled by ajax updates that cause 'stale state' let's try once more if that is the case WebElement element = findByClassName(className); result = getElementText(element); } return result; } protected WebElement findByClassName(String className) { By by = By.className(className); return getSeleniumHelper().findElement(by); } protected WebElement findByXPath(String xpathPattern, String... params) { By by = getSeleniumHelper().byXpath(xpathPattern, params); return getSeleniumHelper().findElement(by); } protected List<WebElement> findAllByXPath(String xpathPattern, String... params) { By by = getSeleniumHelper().byXpath(xpathPattern, params); return getSeleniumHelper().driver().findElements(by); } protected List<WebElement> findAllByCss(String cssPattern, String... params) { By by = getSeleniumHelper().byCss(cssPattern, params); return getSeleniumHelper().driver().findElements(by); } public void waitMilliSecondAfterScroll(int msToWait) { waitAfterScroll = msToWait; } protected String getElementText(WebElement element) { String result = null; if (element != null) { scrollIfNotOnScreen(element); result = element.getText(); } return result; } /** * Scrolls browser window so top of place becomes visible. * @param place element to scroll to. */ public void scrollTo(String place) { WebElement element = getElement(place); if (place != null) { scrollTo(element); } } /** * Scrolls browser window so top of element becomes visible. * @param element element to scroll to. */ protected void scrollTo(WebElement element) { getSeleniumHelper().executeJavascript("arguments[0].scrollIntoView(true);", element); if (waitAfterScroll > 0) { waitMilliSeconds(waitAfterScroll); } } /** * Scrolls browser window if element is not currently visible so top of element becomes visible. * @param element element to scroll to. */ protected void scrollIfNotOnScreen(WebElement element) { if (element.isDisplayed() && !isElementOnScreen(element)) { scrollTo(element); } } /** * Determines whether element can be see in browser's window. * @param place element to check. * @return true if element is displayed and in viewport. */ public boolean isVisible(String place) { boolean result = false; WebElement element = getElement(place); if (element != null) { result = element.isDisplayed() && isElementOnScreen(element); } return result; } /** * Checks whether element is in browser's viewport. * @param element element to check * @return true if element is in browser's viewport. */ protected boolean isElementOnScreen(WebElement element) { return (Boolean)getSeleniumHelper().executeJavascript(ELEMENT_ON_SCREEN_JS, element); } /** * @param timeout number of seconds before waitUntil() throws TimeOutException. */ public void secondsBeforeTimeout(int timeout) { secondsBeforeTimeout = timeout; int timeoutInMs = timeout * 1000; getSeleniumHelper().setPageLoadWait(timeoutInMs); } /** * @return number of seconds waitUntil() will wait at most. */ public int secondsBeforeTimeout() { return secondsBeforeTimeout; } /** * Clears HTML5's localStorage. */ public void clearLocalStorage() { getSeleniumHelper().executeJavascript("localStorage.clear();"); } /** * @param directory sets base directory where screenshots will be stored. */ public void screenshotBaseDirectory(String directory) { if (directory.equals("") || directory.endsWith("/") || directory.endsWith("\\")) { screenshotBase = directory; } else { screenshotBase = directory + "/"; } } /** * @param height height to use to display screenshot images */ public void screenshotShowHeight(String height) { screenshotHeight = height; } /** * Takes screenshot from current page * @param basename filename (below screenshot base directory). * @return location of screenshot. */ public String takeScreenshot(String basename) { String screenshotFile = createScreenshot(basename); if (screenshotFile == null) { throw new RuntimeException("Unable to take screenshot: does the webdriver support it?"); } else { if (screenshotFile.startsWith(filesDir)) { // make href to screenshot String relativeFile = screenshotFile.substring(filesDir.length()); relativeFile = relativeFile.replace('\\', '/'); String wikiUrl = "files" + relativeFile; if ("".equals(screenshotHeight)) { wikiUrl = String.format("<a href=\"%s\">%s</a>", wikiUrl, screenshotFile); } else { wikiUrl = String.format("<a href=\"%1$s\"><img src=\"%1$s\" title=\"%2$s\" height=\"%3$s\"></a>", wikiUrl, screenshotFile, screenshotHeight); } screenshotFile = wikiUrl; } } return screenshotFile; } private String createScreenshot(String basename) { String name = screenshotBase + basename; return getSeleniumHelper().takeScreenshot(name); } /** * Implementations should wait until the condition evaluates to a value that is neither null nor * false. Because of this contract, the return type must not be Void. * @param <T> the return type of the method, which must not be Void * @param condition condition to evaluate to determine whether waiting can be stopped. * @throws org.openqa.selenium.TimeoutException if condition was not met before secondsBeforeTimeout. * @return result of condition. */ protected <T> T waitUntil(ExpectedCondition<T> condition) { try { FluentWait<WebDriver> wait = waitDriver().withTimeout(secondsBeforeTimeout(), TimeUnit.SECONDS); return wait.until(condition); } catch (TimeoutException e) { // take a screenshot of what was on screen String screenShotFile = null; try { screenShotFile = createScreenshot("timeouts/" + getClass().getSimpleName() + "/timeout"); } catch (Exception sse) { // unable to take screenshot sse.printStackTrace(); } if (screenShotFile == null) { throw new TimeoutStopTestException(e); } else { throw new TimeoutStopTestException("Screenshot available at: " + screenShotFile, e); } } } private WebDriverWait waitDriver() { return getSeleniumHelper().waitDriver(); } /** * @return helper to use. */ protected final SeleniumHelper getSeleniumHelper() { return seleniumHelper; } /** * Sets SeleniumHelper to use, for testing purposes. * @param helper helper to use. */ void setSeleniumHelper(SeleniumHelper helper) { seleniumHelper = helper; } public int currentBrowserWidth() { WebDriver.Window window = getSeleniumHelper().driver().manage().window(); window.setPosition(new Point(0, 0)); return window.getSize().getWidth(); } public void setBrowserWidth(int newWidth) { WebDriver.Window window = getSeleniumHelper().driver().manage().window(); window.setPosition(new Point(0, 0)); int currentBrowserHeight = window.getSize().getHeight(); window.setSize(new Dimension(newWidth, currentBrowserHeight)); } }
package nl.hsac.fitnesse.fixture.slim.web; import java.io.File; import java.lang.reflect.Method; import java.util.List; import java.util.Set; import nl.hsac.fitnesse.fixture.slim.SlimFixture; import nl.hsac.fitnesse.fixture.slim.SlimFixtureException; import nl.hsac.fitnesse.fixture.util.BinaryHttpResponse; import nl.hsac.fitnesse.fixture.util.FileUtil; import nl.hsac.fitnesse.fixture.util.HttpResponse; import nl.hsac.fitnesse.fixture.util.SeleniumHelper; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.cookie.BasicClientCookie; import org.openqa.selenium.*; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; public class BrowserTest extends SlimFixture { private SeleniumHelper seleniumHelper = getEnvironment().getSeleniumHelper(); private NgBrowserTest ngBrowserTest; private int secondsBeforeTimeout; private int waitAfterScroll = 150; private String screenshotBase = new File(filesDir, "screenshots").getPath() + "/"; private String screenshotHeight = "200"; private String downloadBase = new File(filesDir, "downloads").getPath() + "/"; @Override protected void beforeInvoke(Method method, Object[] arguments) { super.beforeInvoke(method, arguments); waitForAngularIfNeeded(method); } /** * Determines whether the current method might require waiting for angular given the currently open site, * and ensure it does if needed. * @param method */ protected void waitForAngularIfNeeded(Method method) { if (ngBrowserTest == null) { ngBrowserTest = new NgBrowserTest(); } if (ngBrowserTest.requiresWaitForAngular(method) && currentSiteUsesAngular()) { ngBrowserTest.waitForAngularRequestsToFinish(); } } protected boolean currentSiteUsesAngular() { Object windowHasAngular = getSeleniumHelper().executeJavascript("return window.angular?1:0;"); return Long.valueOf(1).equals(windowHasAngular); } @Override protected Throwable handleException(Method method, Object[] arguments, Throwable t) { Throwable result; if (!(t instanceof SlimFixtureException)) { String msg = getSlimFixtureExceptionMessage("exception", null, t); result = new SlimFixtureException(false, msg, t); } else { result = super.handleException(method, arguments, t); } return result; } public BrowserTest() { secondsBeforeTimeout(seleniumHelper.getDefaultTimeoutSeconds()); ensureActiveTabIsNotClosed(); } public BrowserTest(int secondsBeforeTimeout) { secondsBeforeTimeout(secondsBeforeTimeout); ensureActiveTabIsNotClosed(); } public boolean open(String address) { final String url = getUrl(address); try { getNavigation().to(url); } catch (TimeoutException e) { handleTimeoutException(e); } waitUntil(new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver webDriver) { String readyState = getSeleniumHelper().executeJavascript("return document.readyState").toString(); // IE 7 is reported to return "loaded" boolean done = "complete".equalsIgnoreCase(readyState) || "loaded".equalsIgnoreCase(readyState); if (!done) { System.err.printf("Open of %s returned while document.readyState was %s", url, readyState); System.err.println(); } return done; } }); return true; } public boolean back() { getNavigation().back(); // firefox sometimes prevents immediate back, if previous page was reached via POST waitMilliseconds(500); WebElement element = getSeleniumHelper().findElement(By.id("errorTryAgain")); if (element != null) { element.click(); // don't use confirmAlert as this may be overridden in subclass and to get rid of the // firefox pop-up we need the basic behavior getSeleniumHelper().getAlert().accept(); } return true; } public boolean forward() { getNavigation().forward(); return true; } public boolean refresh() { getNavigation().refresh(); return true; } private WebDriver.Navigation getNavigation() { return getSeleniumHelper().navigate(); } public String alertText() { return waitUntilOrNull(new ExpectedCondition<String>() { @Override public String apply(WebDriver webDriver) { Alert alert = getAlert(); String text = null; if (alert != null) { text = alert.getText(); } return text; } }); } public boolean confirmAlert() { return waitUntil(new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver webDriver) { Alert alert = getAlert(); boolean result = false; if (alert != null) { alert.accept(); result = true; } return result; } }); } public boolean dismissAlert() { return waitUntil(new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver webDriver) { Alert alert = getAlert(); boolean result = false; if (alert != null) { alert.dismiss(); result = true; } return result; } }); } protected Alert getAlert() { return getSeleniumHelper().getAlert(); } public boolean openInNewTab(String url) { String cleanUrl = getUrl(url); final int tabCount = tabCount(); getSeleniumHelper().executeJavascript("window.open('%s', '_blank')", cleanUrl); // ensure new window is open waitUntil(new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver webDriver) { return tabCount() > tabCount; } }); return switchToNextTab(); } public boolean switchToNextTab() { boolean result = false; List<String> tabs = getTabHandles(); if (tabs.size() > 1) { int currentTab = getCurrentTabIndex(tabs); int nextTab = currentTab + 1; if (nextTab == tabs.size()) { nextTab = 0; } goToTab(tabs, nextTab); result = true; } return result; } public boolean switchToPreviousTab() { boolean result = false; List<String> tabs = getTabHandles(); if (tabs.size() > 1) { int currentTab = getCurrentTabIndex(tabs); int nextTab = currentTab - 1; if (nextTab < 0) { nextTab = tabs.size() - 1; } goToTab(tabs, nextTab); result = true; } return result; } public boolean closeTab() { boolean result = false; List<String> tabs = getTabHandles(); int currentTab = getCurrentTabIndex(tabs); int tabToGoTo = -1; if (currentTab > 0) { tabToGoTo = currentTab - 1; } else { if (tabs.size() > 1) { tabToGoTo = 1; } } if (tabToGoTo > -1) { WebDriver driver = getSeleniumHelper().driver(); driver.close(); goToTab(tabs, tabToGoTo); result = true; } return result; } public void ensureOnlyOneTab() { ensureActiveTabIsNotClosed(); int tabCount = tabCount(); for (int i = 1; i < tabCount; i++) { closeTab(); } } public boolean ensureActiveTabIsNotClosed() { boolean result = false; List<String> tabHandles = getTabHandles(); int currentTab = getCurrentTabIndex(tabHandles); if (currentTab < 0) { result = true; goToTab(tabHandles, 0); } return result; } public int tabCount() { return getTabHandles().size(); } public int currentTabIndex() { return getCurrentTabIndex(getTabHandles()) + 1; } protected int getCurrentTabIndex(List<String> tabHandles) { return getSeleniumHelper().getCurrentTabIndex(tabHandles); } protected void goToTab(List<String> tabHandles, int indexToGoTo) { getSeleniumHelper().goToTab(tabHandles, indexToGoTo); } protected List<String> getTabHandles() { return getSeleniumHelper().getTabHandles(); } public String pageTitle() { return getSeleniumHelper().getPageTitle(); } /** * @return current page's content type. */ public String pageContentType() { String result = null; Object ct = getSeleniumHelper().executeJavascript("return document.contentType;"); if (ct != null) { result = ct.toString(); } return result; } /** * Replaces content at place by value. * @param value value to set. * @param place element to set value on. * @return true, if element was found. */ public boolean enterAs(String value, String place) { return enter(value, place, true); } /** * Adds content to place. * @param value value to add. * @param place element to add value to. * @return true, if element was found. */ public boolean enterFor(String value, String place) { return enter(value, place, false); } protected boolean enter(final String value, final String place, final boolean shouldClear) { return waitUntil(new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver webDriver) { WebElement element = getElementToSendValue(place); boolean result = element != null && isInteractable(element); if (result) { if (shouldClear) { element.clear(); } sendValue(element, value); } return result; } }); } protected WebElement getElementToSendValue(String place) { return getElement(place); } /** * Simulates pressing the 'Tab' key. * @return true, if an element was active the key could be sent to. */ public boolean pressTab() { return sendKeysToActiveElement(Keys.TAB); } /** * Simulates pressing the 'Enter' key. * @return true, if an element was active the key could be sent to. */ public boolean pressEnter() { return sendKeysToActiveElement(Keys.ENTER); } /** * Simulates pressing the 'Esc' key. * @return true, if an element was active the key could be sent to. */ public boolean pressEsc() { return sendKeysToActiveElement(Keys.ESCAPE); } /** * Simulates typing a text to the current active element. * @param text text to type. * @return true, if an element was active the text could be sent to. */ public boolean type(String text) { String value = cleanupValue(text); return sendKeysToActiveElement(value); } public boolean press(String key) { CharSequence s; String[] parts = key.split("\\s*\\+\\s*"); if (parts.length > 1 && !"".equals(parts[0]) && !"".equals(parts[1])) { CharSequence[] sequence = new CharSequence[parts.length]; for (int i = 0; i < parts.length; i++) { sequence[i] = parseKey(parts[i]); } s = Keys.chord(sequence); } else { s = parseKey(key); } return sendKeysToActiveElement(s); } protected CharSequence parseKey(String key) { CharSequence s; try { s = Keys.valueOf(key.toUpperCase()); } catch (IllegalArgumentException e) { s = key; } return s; } /** * Simulates pressing keys. * @param keys keys to press. * @return true, if an element was active the keys could be sent to. */ protected boolean sendKeysToActiveElement(CharSequence keys) { boolean result = false; WebElement element = getSeleniumHelper().getActiveElement(); if (element != null) { element.sendKeys(keys); result = true; } return result; } /** * Sends Fitnesse cell content to element. * @param element element to call sendKeys() on. * @param value cell content. */ protected void sendValue(WebElement element, String value) { if (StringUtils.isNotEmpty(value)) { String keys = cleanupValue(value); element.sendKeys(keys); } } public boolean selectAs(String value, String place) { return selectFor(value, place); } public boolean selectFor(final String value, final String place) { return waitUntil(new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver webDriver) { // choose option for select, if possible boolean result = clickSelectOption(place, value); if (!result) { // try to click the first element with right value result = click(value); } return result; } }); } public boolean enterForHidden(final String value, final String idOrName) { return waitUntil(new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver webDriver) { return getSeleniumHelper().setHiddenInputValue(idOrName, value); } }); } private boolean clickSelectOption(String selectPlace, String optionValue) { WebElement element = getElementToSelectFor(selectPlace); return clickSelectOption(element, optionValue); } protected WebElement getElementToSelectFor(String selectPlace) { return getElement(selectPlace); } protected boolean clickSelectOption(WebElement element, String optionValue) { boolean result = false; if (element != null) { if (isSelect(element)) { By xpath = getSeleniumHelper().byXpath(".//option[normalize-space(text()) = '%s']", optionValue); WebElement option = getSeleniumHelper().findElement(element, true, xpath); if (option == null) { xpath = getSeleniumHelper().byXpath(".//option[contains(normalize-space(text()), '%s')]", optionValue); option = getSeleniumHelper().findElement(element, true, xpath); } if (option != null) { result = clickElement(option); } } } return result; } public boolean click(final String place) { // if other element hides the element (in Chrome) an exception is thrown // we retry clicking the element a few times before giving up. return waitUntil(new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver webDriver) { boolean result = false; try { result = clickImpl(place); } catch (WebDriverException e) { String msg = e.getMessage(); if (msg == null || !msg.contains("Other element would receive the click")) { throw e; } } return result; } }); } protected boolean clickImpl(String place) { WebElement element = getElementToClick(place); return clickElement(element); } protected WebElement getElementToClick(String place) { WebElement element = getSeleniumHelper().findElement(By.linkText(place)); WebElement firstFound = element; if (!isInteractable(element)) { element = getSeleniumHelper().findElement(By.partialLinkText(place)); if (firstFound == null) { firstFound = element; } if (!isInteractable(element)) { element = getElement(place); if (firstFound == null) { firstFound = element; } if (!isInteractable(element)) { // find element with specified text and 'onclick' attribute /** * Downloads the target of a link in a grid's row. * @param place which link to download. * @param rowNumber (1-based) row number to retrieve link from. * @return downloaded file if any, null otherwise. */ public String downloadFromRowNumber(String place, int rowNumber) { String columnXPath = String.format("(//tr[boolean(td)])[%s]/td", rowNumber); return downloadFromRow(columnXPath, place); } /** * Downloads the target of a link in a grid, finding the row based on one of the other columns' value. * @param place which link to download. * @param selectOnColumn column header of cell whose value must be selectOnValue. * @param selectOnValue value to be present in selectOnColumn to find correct row. * @return downloaded file if any, null otherwise. */ public String downloadFromRowWhereIs(String place, String selectOnColumn, String selectOnValue) { String columnXPath = getXPathForColumnInRowByValueInOtherColumn(selectOnColumn, selectOnValue); return downloadFromRow(columnXPath, place); } protected String downloadFromRow(final String columnXPath, final String place) { String result = waitUntil(new ExpectedCondition<String>() { @Override public String apply(WebDriver webDriver) { String result = null; // find an a to download from based on its text() WebElement element = findByXPath("%s//a[contains(normalize-space(text()),'%s')]", columnXPath, place); if (element == null) { // find an a to download based on its column header String requestedIndex = getXPathForColumnIndex(place); element = findByXPath("%s[%s]//a", columnXPath, requestedIndex); if (element == null) { // find an a to download in the row by its title (aka tooltip) element = findByXPath("%s//a[contains(@title, '%s')]", columnXPath, place); } } if (element != null) { result = downloadLinkTarget(element); } return result; } }); return result; } /** * Creates an XPath expression that will find a cell in a row, selecting the row based on the * text in a specific column (identified by its header text). * @param columnName header text of the column to find value in. * @param value text to find in column with the supplied header. * @return XPath expression selecting a td in the row */ protected String getXPathForColumnInRowByValueInOtherColumn(String columnName, String value) { String selectIndex = getXPathForColumnIndex(columnName); return String.format("//tr[td[%s]/descendant-or-self::text()[normalize-space(.)='%s']]/td", selectIndex, value); } /** * Creates an XPath expression that will determine, for a row, which index to use to select the cell in the column * with the supplied header text value. * @param columnName name of column in header (th) * @return XPath expression which can be used to select a td in a row */ protected String getXPathForColumnIndex(String columnName) { // determine how many columns are before the column with the requested name // the column with the requested name will have an index of the value +1 (since XPath indexes are 1 based) return String.format("count(ancestor::table[1]//tr/th/descendant-or-self::text()[normalize-space(.)='%s']/ancestor-or-self::th[1]/preceding-sibling::th)+1", columnName); } protected WebElement getElement(String place) { return getSeleniumHelper().getElement(place); } public boolean clickByXPath(final String xPath) { return waitUntil(new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver webDriver) { WebElement element = findByXPath(xPath); return clickElement(element); } }); } public String textByXPath(String xPath) { return getTextByXPath(xPath); } protected String getTextByXPath(final String xpathPattern, final String... params) { return waitUntilOrNull(new ExpectedCondition<String>() { @Override public String apply(WebDriver webDriver) { WebElement element = findByXPath(xpathPattern, params); return getElementText(element); } }); } public String textByClassName(String className) { return getTextByClassName(className); } protected String getTextByClassName(final String className) { return waitUntilOrNull(new ExpectedCondition<String>() { @Override public String apply(WebDriver webDriver) { WebElement element = findByClassName(className); return getElementText(element); } }); } protected WebElement findByClassName(String className) { By by = By.className(className); return getSeleniumHelper().findElement(by); } protected WebElement findByXPath(String xpathPattern, String... params) { By by = getSeleniumHelper().byXpath(xpathPattern, params); return getSeleniumHelper().findElement(by); } protected WebElement findByJavascript(String script, Object... parameters) { By by = getSeleniumHelper().byJavascript(script, parameters); return getSeleniumHelper().findElement(by); } protected List<WebElement> findAllByXPath(String xpathPattern, String... params) { By by = getSeleniumHelper().byXpath(xpathPattern, params); return findElements(by); } protected List<WebElement> findAllByCss(String cssPattern, String... params) { By by = getSeleniumHelper().byCss(cssPattern, params); return findElements(by); } protected List<WebElement> findAllByJavascript(String script, Object... parameters) { By by = getSeleniumHelper().byJavascript(script, parameters); return findElements(by); } protected List<WebElement> findElements(By by) { return getSeleniumHelper().driver().findElements(by); } public void waitMilliSecondAfterScroll(int msToWait) { waitAfterScroll = msToWait; } protected String getElementText(WebElement element) { String result = null; if (element != null) { scrollIfNotOnScreen(element); result = element.getText(); } return result; } /** * Scrolls browser window so top of place becomes visible. * @param place element to scroll to. */ public void scrollTo(final String place) { waitUntil(new ExpectedCondition<WebElement>() { @Override public WebElement apply(WebDriver webDriver) { WebElement element = getElementToScrollTo(place); if (place != null) { scrollTo(element); } return element; } }); } protected WebElement getElementToScrollTo(String place) { return getElementToCheckVisibility(place); } /** * Scrolls browser window so top of element becomes visible. * @param element element to scroll to. */ protected void scrollTo(WebElement element) { getSeleniumHelper().scrollTo(element); if (waitAfterScroll > 0) { waitMilliseconds(waitAfterScroll); } } /** * Scrolls browser window if element is not currently visible so top of element becomes visible. * @param element element to scroll to. */ protected void scrollIfNotOnScreen(WebElement element) { if (!element.isDisplayed() || !isElementOnScreen(element)) { scrollTo(element); } } /** * Determines whether element can be see in browser's window. * @param place element to check. * @return true if element is displayed and in viewport. */ public boolean isVisible(final String place) { Boolean r = waitUntilOrNull(new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver webDriver) { Boolean result = null; WebElement element = getElementToCheckVisibility(place); if (element != null) { result = element.isDisplayed() && isElementOnScreen(element); } return result; } }); return r != null && r.booleanValue(); } protected WebElement getElementToCheckVisibility(String place) { return getElement(place); } /** * Checks whether element is in browser's viewport. * @param element element to check * @return true if element is in browser's viewport. */ protected boolean isElementOnScreen(WebElement element) { Boolean onScreen = getSeleniumHelper().isElementOnScreen(element); return onScreen == null || onScreen.booleanValue(); } /** * @param timeout number of seconds before waitUntil() and waitForJavascriptCallback() throw TimeOutException. */ public void secondsBeforeTimeout(int timeout) { secondsBeforeTimeout = timeout; int timeoutInMs = timeout * 1000; getSeleniumHelper().setPageLoadWait(timeoutInMs); getSeleniumHelper().setScriptWait(timeoutInMs); } /** * @return number of seconds waitUntil() will wait at most. */ public int secondsBeforeTimeout() { return secondsBeforeTimeout; } /** * Clears HTML5's localStorage (for the domain of the current open page in the browser). */ public void clearLocalStorage() { getSeleniumHelper().executeJavascript("localStorage.clear();"); } /** * Deletes all cookies(for the domain of the current open page in the browser). */ public void deleteAllCookies() { getSeleniumHelper().deleteAllCookies(); } /** * @param directory sets base directory where screenshots will be stored. */ public void screenshotBaseDirectory(String directory) { if (directory.equals("") || directory.endsWith("/") || directory.endsWith("\\")) { screenshotBase = directory; } else { screenshotBase = directory + "/"; } } /** * @param height height to use to display screenshot images */ public void screenshotShowHeight(String height) { screenshotHeight = height; } /** * Takes screenshot from current page * @param basename filename (below screenshot base directory). * @return location of screenshot. */ public String takeScreenshot(String basename) { String screenshotFile = createScreenshot(basename); if (screenshotFile == null) { throw new SlimFixtureException(false, "Unable to take screenshot: does the webdriver support it?"); } else { screenshotFile = getScreenshotLink(screenshotFile); } return screenshotFile; } private String getScreenshotLink(String screenshotFile) { String wikiUrl = getWikiUrl(screenshotFile); if (wikiUrl != null) { // make href to screenshot if ("".equals(screenshotHeight)) { wikiUrl = String.format("<a href=\"%s\">%s</a>", wikiUrl, screenshotFile); } else { wikiUrl = String.format("<a href=\"%1$s\"><img src=\"%1$s\" title=\"%2$s\" height=\"%3$s\"/></a>", wikiUrl, screenshotFile, screenshotHeight); } screenshotFile = wikiUrl; } return screenshotFile; } private String createScreenshot(String basename) { String name = getScreenshotBasename(basename); return getSeleniumHelper().takeScreenshot(name); } private String createScreenshot(String basename, Throwable t) { String screenshotFile; byte[] screenshotInException = getSeleniumHelper().findScreenshot(t); if (screenshotInException == null || screenshotInException.length == 0) { screenshotFile = createScreenshot(basename); } else { String name = getScreenshotBasename(basename); screenshotFile = getSeleniumHelper().writeScreenshot(name, screenshotInException); } return screenshotFile; } private String getScreenshotBasename(String basename) { return screenshotBase + basename; } /** * Waits until the condition evaluates to a value that is neither null nor * false. Because of this contract, the return type must not be Void. * @param <T> the return type of the method, which must not be Void * @param condition condition to evaluate to determine whether waiting can be stopped. * @throws SlimFixtureException if condition was not met before secondsBeforeTimeout. * @return result of condition. */ protected <T> T waitUntil(ExpectedCondition<T> condition) { try { return waitUntilImpl(condition); } catch (TimeoutException e) { String message = getTimeoutMessage(e); throw new SlimFixtureException(false, message, e); } } /** * Waits until the condition evaluates to a value that is neither null nor * false. If that does not occur the whole test is stopped. * Because of this contract, the return type must not be Void. * @param <T> the return type of the method, which must not be Void * @param condition condition to evaluate to determine whether waiting can be stopped. * @throws TimeoutStopTestException if condition was not met before secondsBeforeTimeout. * @return result of condition. */ protected <T> T waitUntilOrStop(ExpectedCondition<T> condition) { try { return waitUntilImpl(condition); } catch (TimeoutException e) { return handleTimeoutException(e); } } /** * Waits until the condition evaluates to a value that is neither null nor * false. If that does not occur null is returned. * Because of this contract, the return type must not be Void. * @param <T> the return type of the method, which must not be Void * @param condition condition to evaluate to determine whether waiting can be stopped. * @return result of condition. */ protected <T> T waitUntilOrNull(ExpectedCondition<T> condition) { try { return waitUntilImpl(condition); } catch (TimeoutException e) { return null; } } protected <T> T waitUntilImpl(ExpectedCondition<T> condition) { return getSeleniumHelper().waitUntil(secondsBeforeTimeout(), condition); } protected <T> T handleTimeoutException(TimeoutException e) { String message = getTimeoutMessage(e); throw new TimeoutStopTestException(false, message, e); } private String getTimeoutMessage(TimeoutException e) { String messageBase = String.format("Timed-out waiting (after %ss)", secondsBeforeTimeout()); return getSlimFixtureExceptionMessage("timeouts", "timeout", messageBase, e); } protected void handleRequiredElementNotFound(String toFind) { handleRequiredElementNotFound(toFind, null); } protected void handleRequiredElementNotFound(String toFind, Throwable t) { String messageBase = String.format("Unable to find: %s", toFind); String message = getSlimFixtureExceptionMessage("notFound", toFind, messageBase, t); throw new SlimFixtureException(false, message, t); } protected String getSlimFixtureExceptionMessage(String screenshotFolder, String screenshotFile, String messageBase, Throwable t) { String screenshotBaseName = String.format("%s/%s/%s", screenshotFolder, getClass().getSimpleName(), screenshotFile); return getSlimFixtureExceptionMessage(screenshotBaseName, messageBase, t); } protected String getSlimFixtureExceptionMessage(String screenshotBaseName, String messageBase, Throwable t) { // take a screenshot of what was on screen String screenShotFile = null; try { screenShotFile = createScreenshot(screenshotBaseName, t); } catch (Exception sse) { // unable to take screenshot sse.printStackTrace(); } String message = messageBase; if (message == null) { if (t == null) { message = ""; } else { message = ExceptionUtils.getStackTrace(t); } } if (screenShotFile != null) { String exceptionMsg = formatExceptionMsg(message); message = String.format("<div><div>%s.</div><div>Page content:%s</div></div>", exceptionMsg, getScreenshotLink(screenShotFile)); } return message; } protected String formatExceptionMsg(String value) { return StringEscapeUtils.escapeHtml4(value); } private WebDriverWait waitDriver() { return getSeleniumHelper().waitDriver(); } /** * @return helper to use. */ protected final SeleniumHelper getSeleniumHelper() { return seleniumHelper; } /** * Sets SeleniumHelper to use, for testing purposes. * @param helper helper to use. */ void setSeleniumHelper(SeleniumHelper helper) { seleniumHelper = helper; } public int currentBrowserWidth() { return getSeleniumHelper().getWindowSize().getWidth(); } public int currentBrowserHeight() { return getSeleniumHelper().getWindowSize().getHeight(); } public void setBrowserWidth(int newWidth) { int currentHeight = getSeleniumHelper().getWindowSize().getHeight(); setBrowserSizeToBy(newWidth, currentHeight); } public void setBrowserHeight(int newHeight) { int currentWidth = getSeleniumHelper().getWindowSize().getWidth(); setBrowserSizeToBy(currentWidth, newHeight); } public void setBrowserSizeToBy(int newWidth, int newHeight) { getSeleniumHelper().setWindowSize(newWidth, newHeight); Dimension actualSize = getSeleniumHelper().getWindowSize(); if (actualSize.getHeight() != newHeight || actualSize.getWidth() != newWidth) { String message = String.format("Unable to change size to: %s x %s; size is: %s x %s", newWidth, newHeight, actualSize.getWidth(), actualSize.getHeight()); throw new SlimFixtureException(false, message); } } /** * Downloads the target of the supplied link. * @param place link to follow. * @return downloaded file if any, null otherwise. */ public String download(final String place) { return waitUntil(new ExpectedCondition<String>() { @Override public String apply(WebDriver webDriver) { By selector = By.linkText(place); WebElement element = getSeleniumHelper().findElement(selector); if (element == null) { selector = By.partialLinkText(place); element = getSeleniumHelper().findElement(selector); if (element == null) { selector = By.id(place); element = getSeleniumHelper().findElement(selector); if (element == null) { selector = By.name(place); element = getSeleniumHelper().findElement(selector); } } } return downloadLinkTarget(element); } }); } /** * Downloads the target of the supplied link. * @param element link to follow. * @return downloaded file if any, null otherwise. */ protected String downloadLinkTarget(WebElement element) { String result = null; if (element != null) { String href = element.getAttribute("href"); if (href != null) { result = downloadContentFrom(href); } else { throw new SlimFixtureException(false, "Could not determine url to download from"); } } return result; } /** * Downloads binary content from specified url (using the browser's cookies). * @param urlOrLink url to download from * @return link to downloaded file */ public String downloadContentFrom(String urlOrLink) { String result = null; if (urlOrLink != null) { String url = getUrl(urlOrLink); BinaryHttpResponse resp = new BinaryHttpResponse(); getUrlContent(url, resp); byte[] content = resp.getResponseContent(); if (content == null) { result = resp.getResponse(); } else { String fileName = resp.getFileName(); String baseName = FilenameUtils.getBaseName(fileName); String ext = FilenameUtils.getExtension(fileName); String downloadedFile = FileUtil.saveToFile(getDownloadName(baseName), ext, content); String wikiUrl = getWikiUrl(downloadedFile); if (wikiUrl != null) { // make href to file result = String.format("<a href=\"%s\">%s</a>", wikiUrl, fileName); } else { result = downloadedFile; } } } return result; } /** * Selects a file using a file upload control. * @param fileName file to upload * @param place file input to select the file for * @return true, if place was a file input and file existed. */ public boolean selectFileFor(String fileName, final String place) { boolean result = false; if (fileName != null) { final String fullPath = getFilePathFromWikiUrl(fileName); if (new File(fullPath).exists()) { result = waitUntil(new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver webDriver) { boolean result = false; WebElement element = getElementToSelectFile(place); if (element != null) { element.sendKeys(fullPath); result = true; } return result; } }); } else { throw new SlimFixtureException(false, "Unable to find file: " + fullPath); } } return result; } protected WebElement getElementToSelectFile(String place) { WebElement result = null; WebElement element = getElement(place); if (element != null && "input".equalsIgnoreCase(element.getTagName()) && "file".equalsIgnoreCase(element.getAttribute("type"))) { result = element; } return result; } private String getDownloadName(String baseName) { return downloadBase + baseName; } /** * GETs content of specified URL, using the browsers cookies. * @param url url to retrieve content from * @param resp response to store content in */ protected void getUrlContent(String url, HttpResponse resp) { Set<Cookie> browserCookies = getSeleniumHelper().getCookies(); BasicCookieStore cookieStore = new BasicCookieStore(); for (Cookie browserCookie : browserCookies) { BasicClientCookie cookie = convertCookie(browserCookie); cookieStore.addCookie(cookie); } resp.setCookieStore(cookieStore); getEnvironment().doGet(url, resp); } private BasicClientCookie convertCookie(Cookie browserCookie) { BasicClientCookie cookie = new BasicClientCookie(browserCookie.getName(), browserCookie.getValue()); cookie.setDomain(browserCookie.getDomain()); cookie.setPath(browserCookie.getPath()); cookie.setExpiryDate(browserCookie.getExpiry()); return cookie; } protected Object waitForJavascriptCallback(String statement, Object... parameters) { try { return getSeleniumHelper().waitForJavascriptCallback(statement, parameters); } catch (TimeoutException e) { return handleTimeoutException(e); } } public NgBrowserTest getNgBrowserTest() { return ngBrowserTest; } public void setNgBrowserTest(NgBrowserTest ngBrowserTest) { this.ngBrowserTest = ngBrowserTest; } }
package no.difi.sdp.client.internal; import no.difi.begrep.sdp.schema_v10.*; import no.difi.sdp.client.domain.Feil; import no.difi.sdp.client.domain.Feiltype; import no.difi.sdp.client.domain.Prioritet; import no.difi.sdp.client.domain.kvittering.*; import no.posten.dpost.offentlig.api.representations.*; import java.util.Date; public class KvitteringBuilder { public EbmsPullRequest buildEbmsPullRequest(Organisasjonsnummer meldingsformidlerOrgNummer, Prioritet prioritet) { EbmsMottaker meldingsformidler = new EbmsMottaker(meldingsformidlerOrgNummer); if (prioritet == Prioritet.PRIORITERT) { return new EbmsPullRequest(meldingsformidler, EbmsOutgoingMessage.Prioritet.PRIORITERT); } return new EbmsPullRequest(meldingsformidler); } public ForretningsKvittering buildForretningsKvittering(EbmsApplikasjonsKvittering applikasjonsKvittering) { SimpleStandardBusinessDocument sbd = applikasjonsKvittering.getStandardBusinessDocument(); if (sbd.erKvittering()) { SimpleStandardBusinessDocument.SimpleKvittering kvittering = sbd.getKvittering(); SDPKvittering sdpKvittering = kvittering.kvittering; String konversasjonsId = kvittering.getKonversasjonsId(); Date tidspunkt = sdpKvittering.getTidspunkt().toDate(); if (sdpKvittering.getAapning() != null) { return AapningsKvittering.builder(tidspunkt, konversasjonsId).build(); } else if (sdpKvittering.getLevering() != null) { return LeveringsKvittering.builder(tidspunkt, konversasjonsId).build(); } else if (sdpKvittering.getTilbaketrekking() != null) { return tilbaketrekkingsKvittering(sdpKvittering, konversasjonsId, tidspunkt); } else if (sdpKvittering.getVarslingfeilet() != null) { return varslingFeiletKvittering(sdpKvittering, konversasjonsId, tidspunkt); } } else if (sbd.erFeil()) { return feil(sbd); } //todo: proper exception handling throw new RuntimeException("Kvittering tilbake fra meldingsformidler var hverken kvittering eller feil."); } private ForretningsKvittering feil(SimpleStandardBusinessDocument sbd) { SDPFeil feil = sbd.getFeil(); return Feil.builder(feil.getTidspunkt().toDate(), feil.getKonversasjonsId(), mapFeilType(feil.getFeiltype())) .detaljer(feil.getDetaljer()) .build(); } private ForretningsKvittering tilbaketrekkingsKvittering(SDPKvittering sdpKvittering, String konversasjonsId, Date tidspunkt) { SDPTilbaketrekkingsresultat tilbaketrekking = sdpKvittering.getTilbaketrekking(); TilbaketrekkingsStatus status = mapTilbaketrekkingsStatus(tilbaketrekking.getStatus()); return TilbaketrekkingsKvittering.builder(tidspunkt, konversasjonsId, status) .beskrivelse(tilbaketrekking.getBeskrivelse()) .build(); } private ForretningsKvittering varslingFeiletKvittering(SDPKvittering sdpKvittering, String konversasjonsId, Date tidspunkt) { SDPVarslingfeilet varslingfeilet = sdpKvittering.getVarslingfeilet(); Varslingskanal varslingskanal = mapVarslingsKanal(varslingfeilet.getVarslingskanal()); return VarslingFeiletKvittering.builder(tidspunkt, konversasjonsId, varslingskanal) .beskrivelse(varslingfeilet.getBeskrivelse()) .build(); } private Feiltype mapFeilType(SDPFeiltype feiltype) { if (feiltype == SDPFeiltype.KLIENT) { return Feiltype.KLIENT; } return Feiltype.SERVER; } private Varslingskanal mapVarslingsKanal(SDPVarslingskanal varslingskanal) { if (varslingskanal == SDPVarslingskanal.EPOST) { return Varslingskanal.EPOST; } return Varslingskanal.SMS; } private TilbaketrekkingsStatus mapTilbaketrekkingsStatus(SDPTilbaketrekkingsstatus status) { if (status == SDPTilbaketrekkingsstatus.OK) { return TilbaketrekkingsStatus.OK; } return TilbaketrekkingsStatus.FEILET; } }
package no.uio.ifi.trackfind.frontend; import com.fasterxml.jackson.databind.ObjectMapper; import com.vaadin.annotations.Theme; import com.vaadin.annotations.Title; import com.vaadin.annotations.Widgetset; import com.vaadin.data.HasValue; import com.vaadin.event.ShortcutAction; import com.vaadin.event.ShortcutListener; import com.vaadin.server.*; import com.vaadin.shared.ui.MarginInfo; import com.vaadin.shared.ui.ValueChangeMode; import com.vaadin.shared.ui.dnd.DropEffect; import com.vaadin.shared.ui.dnd.EffectAllowed; import com.vaadin.spring.annotation.SpringUI; import com.vaadin.ui.*; import com.vaadin.ui.components.grid.TreeGridDragSource; import com.vaadin.ui.dnd.DropTargetExtension; import com.vaadin.util.FileTypeResolver; import lombok.extern.slf4j.Slf4j; import no.uio.ifi.trackfind.backend.data.TreeNode; import no.uio.ifi.trackfind.backend.pojo.SearchResult; import no.uio.ifi.trackfind.backend.pojo.TfHub; import no.uio.ifi.trackfind.backend.pojo.TfObjectType; import no.uio.ifi.trackfind.backend.services.impl.GSuiteService; import no.uio.ifi.trackfind.backend.services.impl.MetamodelService; import no.uio.ifi.trackfind.backend.services.impl.SearchService; import no.uio.ifi.trackfind.frontend.components.KeyboardInterceptorExtension; import no.uio.ifi.trackfind.frontend.components.TrackFindTree; import no.uio.ifi.trackfind.frontend.filters.TreeFilter; import no.uio.ifi.trackfind.frontend.listeners.AddToQueryButtonClickListener; import no.uio.ifi.trackfind.frontend.listeners.TextAreaDropListener; import no.uio.ifi.trackfind.frontend.listeners.TreeItemClickListener; import no.uio.ifi.trackfind.frontend.listeners.TreeSelectionListener; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import java.io.ByteArrayInputStream; import java.nio.charset.Charset; import java.sql.SQLException; import java.util.Calendar; import java.util.Collection; import java.util.Collections; /** * Main Vaadin UI of the application. * Capable of displaying metadata for repositories, constructing and executing search queries along with exporting the results. * Uses custom theme (VAADIN/themes/trackfind/trackfind.scss). * Uses custom WidgetSet (TrackFindWidgetSet.gwt.xml). * * @author Dmytro Titov */ @SpringUI(path = "/") @Widgetset("TrackFindWidgetSet") @Title("TrackFind") @Theme("trackfind") @Slf4j public class TrackFindMainUI extends AbstractUI { private ObjectMapper mapper; private MetamodelService metamodelService; private GSuiteService gSuiteService; private SearchService searchService; private int numberOfResults; private CheckBoxGroup<String> categoriesChecklist = new CheckBoxGroup<>(); private TextArea queryTextArea; private TextField limitTextField; private TextArea resultsTextArea; private Collection<SearchResult> results; private String jsonResult; private FileDownloader gSuiteFileDownloader; private FileDownloader jsonFileDownloader; @Override protected void init(VaadinRequest vaadinRequest) { HorizontalLayout headerLayout = buildHeaderLayout(); VerticalLayout treeLayout = buildTreeLayout(); VerticalLayout queryLayout = buildQueryLayout(); VerticalLayout resultsLayout = buildResultsLayout(); HorizontalLayout mainLayout = buildMainLayout(treeLayout, queryLayout, resultsLayout); HorizontalLayout footerLayout = buildFooterLayout(); VerticalLayout outerLayout = buildOuterLayout(headerLayout, mainLayout, footerLayout); setContent(outerLayout); String implementationVersion = getClass().getPackage().getImplementationVersion(); implementationVersion = implementationVersion == null ? "dev" : implementationVersion; Page currentPage = Page.getCurrent(); currentPage.setTitle("TrackFind: " + implementationVersion); // GoogleAnalyticsTracker tracker = new GoogleAnalyticsTracker("UA-143208550-1"); // tracker.trackPageview("/"); // tracker.extend(getUI()); } protected VerticalLayout buildTreeLayout() { tabSheet = new TabSheet(); tabSheet.setSizeFull(); for (TfHub hub : trackFindService.getTrackHubs(true)) { TrackFindTree<TreeNode> tree = buildTree(hub); tabSheet.addTab(tree, hub.getName()); } tabSheet.addSelectedTabChangeListener((TabSheet.SelectedTabChangeListener) event -> refreshCategoriesCheckList()); Panel treePanel = new Panel("Model browser", tabSheet); treePanel.setSizeFull(); // TextField attributesFilterTextField = createFilter(true); TextField valuesFilterTextField = createFilter(false); Button addToQueryButton = new Button("Add to query (⌥: OR, ⇧: NOT)"); KeyboardInterceptorExtension keyboardInterceptorExtension = new KeyboardInterceptorExtension(addToQueryButton); AddToQueryButtonClickListener addToQueryButtonClickListener = new AddToQueryButtonClickListener(this, keyboardInterceptorExtension, separator); addToQueryButton.addClickListener(addToQueryButtonClickListener); addToQueryButton.setWidth(100, Unit.PERCENTAGE); VerticalLayout treeLayout = new VerticalLayout(treePanel, valuesFilterTextField, addToQueryButton); treeLayout.setSizeFull(); treeLayout.setExpandRatio(treePanel, 1f); return treeLayout; } @SuppressWarnings("unchecked") protected TrackFindTree<TreeNode> buildTree(TfHub hub) { TrackFindTree<TreeNode> tree = new TrackFindTree<>(hub); tree.setDataProvider(trackFindDataProvider); tree.setSelectionMode(Grid.SelectionMode.MULTI); tree.addItemClickListener(new TreeItemClickListener(tree)); TreeGrid<TreeNode> treeGrid = (TreeGrid<TreeNode>) tree.getCompositionRoot(); TreeFilter filter = new TreeFilter(hub, "", ""); treeGrid.setFilter(filter); tree.addSelectionListener(new TreeSelectionListener(tree, filter, new KeyboardInterceptorExtension(tree))); tree.setSizeFull(); tree.setStyleGenerator((StyleGenerator<TreeNode>) item -> { if (item.isAttribute()) { if (item.isStandard()) { return "standard-tree-node"; } else { return null; } } else { return "value-tree-node"; } }); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (!(authentication instanceof AnonymousAuthenticationToken)) { TreeGridDragSource<TreeNode> dragSource = new TreeGridDragSource<>(treeGrid); dragSource.setEffectAllowed(EffectAllowed.COPY); } return tree; } private HorizontalLayout buildMainLayout(VerticalLayout treeLayout, VerticalLayout queryLayout, VerticalLayout resultsLayout) { MarginInfo marginInfo = new MarginInfo(true, true, false, true); treeLayout.setMargin(marginInfo); resultsLayout.setMargin(marginInfo); HorizontalLayout mainLayout = new HorizontalLayout(treeLayout, queryLayout, resultsLayout); mainLayout.setSizeFull(); return mainLayout; } private VerticalLayout buildResultsLayout() { Button exportGSuiteButton = new Button("Export as GSuite file"); exportGSuiteButton.setEnabled(false); exportGSuiteButton.setWidth(100, Unit.PERCENTAGE); Button exportJSONButton = new Button("Export as JSON file"); exportJSONButton.setEnabled(false); exportJSONButton.setWidth(100, Unit.PERCENTAGE); gSuiteFileDownloader = new FileDownloader(new ExternalResource("")); gSuiteFileDownloader.extend(exportGSuiteButton); jsonFileDownloader = new FileDownloader(new ExternalResource("")); jsonFileDownloader.extend(exportJSONButton); resultsTextArea = new TextArea(); resultsTextArea.setSizeFull(); resultsTextArea.setReadOnly(true); resultsTextArea.addStyleName("scrollable-text-area"); resultsTextArea.addValueChangeListener((HasValue.ValueChangeListener<String>) event -> { if (StringUtils.isEmpty(event.getValue())) { exportGSuiteButton.setEnabled(false); exportGSuiteButton.setCaption("Export as GSuite file"); exportJSONButton.setEnabled(false); exportJSONButton.setCaption("Export as JSON file"); } else { exportGSuiteButton.setEnabled(true); exportGSuiteButton.setCaption("Export (" + numberOfResults + ") entries as GSuite file"); exportJSONButton.setEnabled(true); exportJSONButton.setCaption("Export (" + numberOfResults + ") entries as JSON file"); } }); Panel resultsPanel = new Panel("Data", resultsTextArea); resultsPanel.setSizeFull(); VerticalLayout resultsLayout = new VerticalLayout(resultsPanel, exportGSuiteButton, exportJSONButton); resultsLayout.setSizeFull(); resultsLayout.setExpandRatio(resultsPanel, 1f); return resultsLayout; } private VerticalLayout buildQueryLayout() { queryTextArea = new TextArea(); queryTextArea.setSizeFull(); queryTextArea.addShortcutListener(new ShortcutListener("Execute query", ShortcutAction.KeyCode.ENTER, new int[]{ShortcutAction.ModifierKey.CTRL}) { @Override public void handleAction(Object sender, Object target) { executeQuery(queryTextArea.getValue()); } }); queryTextArea.addShortcutListener(new ShortcutListener("Execute query", ShortcutAction.KeyCode.ENTER, new int[]{ShortcutAction.ModifierKey.META}) { @Override public void handleAction(Object sender, Object target) { executeQuery(queryTextArea.getValue()); } }); Button clearAllButton = new Button("Clear all"); clearAllButton.setSizeFull(); clearAllButton.addClickListener((Button.ClickListener) event -> queryTextArea.clear()); Button searchButton = new Button("Search ", (Button.ClickListener) clickEvent -> executeQuery(queryTextArea.getValue())); queryTextArea.addValueChangeListener((HasValue.ValueChangeListener<String>) event -> searchButton.setEnabled(StringUtils.isNotEmpty(queryTextArea.getValue()))); queryTextArea.addStyleName("scrollable-text-area"); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (!(authentication instanceof AnonymousAuthenticationToken)) { DropTargetExtension<TextArea> dropTarget = new DropTargetExtension<>(queryTextArea); dropTarget.setDropEffect(DropEffect.COPY); TextAreaDropListener textAreaDropListener = new TextAreaDropListener(queryTextArea, separator); dropTarget.addDropListener(textAreaDropListener); } Panel queryPanel = new Panel("Search query", queryTextArea); queryPanel.setSizeFull(); searchButton.setWidth(100, Unit.PERCENTAGE); searchButton.setEnabled(false); limitTextField = new TextField("Limit", "10"); limitTextField.setWidth(100, Unit.PERCENTAGE); limitTextField.setValueChangeMode(ValueChangeMode.EAGER); limitTextField.addValueChangeListener((HasValue.ValueChangeListener<String>) valueChangeEvent -> { String value = valueChangeEvent.getValue(); value = StringUtils.isEmpty(value) ? "0" : value; try { Integer.parseInt(value); limitTextField.setComponentError(null); queryTextArea.setEnabled(true); searchButton.setEnabled(true); } catch (NumberFormatException e) { limitTextField.setComponentError(new UserError("Should be a valid integer number only!")); queryTextArea.setEnabled(false); searchButton.setEnabled(false); } }); refreshCategoriesCheckList(); HorizontalLayout searchLayout = new HorizontalLayout(limitTextField, searchButton); searchLayout.setWidth("100%"); searchLayout.setComponentAlignment(searchButton, Alignment.BOTTOM_RIGHT); Panel categoriesChecklistPanel = new Panel("Categories", new VerticalLayout(categoriesChecklist)); categoriesChecklistPanel.setSizeFull(); VerticalLayout queryLayout = new VerticalLayout(queryPanel, clearAllButton, categoriesChecklistPanel, searchLayout); queryLayout.setExpandRatio(queryPanel, 0.4f); queryLayout.setExpandRatio(clearAllButton, 0.1f); queryLayout.setExpandRatio(categoriesChecklistPanel, 0.4f); queryLayout.setExpandRatio(searchLayout, 0.1f); queryLayout.setSizeFull(); queryLayout.setExpandRatio(queryPanel, 1f); return queryLayout; } private void refreshCategoriesCheckList() { Collection<TfObjectType> objectTypes = metamodelService.getObjectTypes(getCurrentHub().getRepository(), getCurrentHub().getName()); categoriesChecklist.setItems(objectTypes.stream().map(TfObjectType::getName)); } private void executeQuery(String query) { TfHub hub = getCurrentHub(); String limit = limitTextField.getValue(); limit = StringUtils.isEmpty(limit) ? "0" : limit; try { results = searchService.search(hub.getRepository(), hub.getName(), query, categoriesChecklist.getSelectedItems(), Long.parseLong(limit)).getValue(); } catch (SQLException e) { results = Collections.emptyList(); log.error(e.getMessage(), e); } if (results.isEmpty()) { resultsTextArea.setValue(""); Notification.show("Nothing found for such request"); return; } numberOfResults = results.size(); try { jsonResult = mapper.writeValueAsString(results); } catch (Exception e) { log.error(e.getMessage(), e); } resultsTextArea.setValue(jsonResult); gSuiteFileDownloader.setFileDownloadResource(getStreamResource(null, ".gsuite")); jsonFileDownloader.setFileDownloadResource(getStreamResource(jsonResult, ".json")); } private Resource getStreamResource(String content, String extension) { return new StreamResource(null, null) { @Override public StreamSource getStreamSource() { if (".json".equalsIgnoreCase(extension)) { return (StreamResource.StreamSource) () -> new ByteArrayInputStream(content.getBytes(Charset.defaultCharset())); } else { String gSuiteResult = gSuiteService.apply(results); return (StreamResource.StreamSource) () -> new ByteArrayInputStream(gSuiteResult.getBytes(Charset.defaultCharset())); } } @Override public String getFilename() { return Calendar.getInstance().getTime().toString() + extension; } @Override public String getMIMEType() { return FileTypeResolver.getMIMEType(getFilename()); } }; } public TextArea getQueryTextArea() { return queryTextArea; } @Autowired public void setMapper(ObjectMapper mapper) { this.mapper = mapper; } @Autowired public void setMetamodelService(MetamodelService metamodelService) { this.metamodelService = metamodelService; } @Autowired public void setGSuiteService(GSuiteService gSuiteService) { this.gSuiteService = gSuiteService; } @Autowired public void setSearchService(SearchService searchService) { this.searchService = searchService; } }
package org.agmip.translators.dssat; import java.io.File; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import org.agmip.core.types.TranslatorOutput; import static org.agmip.util.MapUtil.*; /** * DSSAT Experiment Data I/O API Class * * @author Meng Zhang * @version 1.0 */ public abstract class DssatCommonOutput implements TranslatorOutput { // Default value for each type of value (R: real number; C: String; I: Integer; D: Date) protected String defValR = "0.00"; protected String defValC = ""; protected String defValI = "0"; protected String defValD = "-99"; protected String defValBlank = ""; // construct the error message in the output protected StringBuilder sbError; protected File outputFile; protected static HashMap<String, String> exToFileMap = new HashMap(); protected static HashSet<String> fileNameSet = new HashSet(); protected static DssatWthFileHelper wthHelper = new DssatWthFileHelper(); protected static DssatSoilFileHelper soilHelper = new DssatSoilFileHelper(); /** * Translate data str from "yyyymmdd" to "yyddd" * * 2012/3/19 change input format from "yy/mm/dd" to "yyyymmdd" * * @param str date string with format of "yyyymmdd" * @return result date string with format of "yyddd" */ protected String formatDateStr2(String str) { // Initial Calendar object Calendar cal = Calendar.getInstance(); str = str.replaceAll("/", ""); try { // Set date with input value cal.set(Integer.parseInt(str.substring(0, 4)), Integer.parseInt(str.substring(4, 6)) - 1, Integer.parseInt(str.substring(6))); // translatet to yyddd format return String.format("%1$02d%2$03d", cal.get(Calendar.YEAR) % 100, cal.get(Calendar.DAY_OF_YEAR)); } catch (Exception e) { // if tranlate failed, then use default value for date //sbError.append("! Waring: There is a invalid date [").append(str).append("]\r\n"); return formatDateStr2(defValD); } } /** * Format the number with maximum length and type * * @param bits Maximum length of the output string * @param m the experiment data holder * @param key the key of field in the map * @param defVal the default return value when error happens * @return formated string of number */ protected String formatNumStr(int bits, HashMap m, Object key, String defVal) { String ret = ""; String str = getObjectOr(m, key, defVal); double decimalPower; long decimalPart; double input; String[] inputStr = str.split("\\."); if (str.trim().equals("")) { return String.format("%" + bits + "s", defVal); } else if (inputStr[0].length() > bits) { //throw new Exception(); sbError.append("! Waring: There is a variable [").append(key).append("] with oversized number [").append(ret).append("] (Limitation is ").append(bits).append(" bits)\r\n"); return String.format("%" + bits + "s", defVal); } else { ret = inputStr[0]; if (inputStr.length > 1 && inputStr[0].length() < bits) { if (inputStr[1].length() <= bits - inputStr[0].length() - 1) { ret = ret + "." + inputStr[1]; } else { try { input = Math.abs(Double.valueOf(str)); } catch (Exception e) { // TODO throw exception return str; } //decimalPower = Math.pow(10, Math.min(bits - inputStr[0].length(), inputStr[1].length()) - 1); decimalPower = Math.pow(10, bits - inputStr[0].length() - 1); decimalPart = Double.valueOf(Math.round(input * decimalPower) % decimalPower).longValue(); ret = ret + "." + (decimalPart == 0 && (bits - inputStr[0].length() < 2) ? "" : decimalPart); } } if (ret.length() < bits) { ret = String.format("%1$" + bits + "s", ret); } } return ret; } /** * Format the output string with maximum length * * @param bits Maximum length of the output string * @param m the experiment data holder * @param key the key of field in the map * @param defVal the default return value when error happens * @return formated string of number */ protected String formatStr(int bits, HashMap m, Object key, String defVal) { String ret = getObjectOr(m, key, defVal).trim(); if (ret.equals("")) { return ret; } else if (ret.length() > bits) { //throw new Exception(); sbError.append("! Waring: There is a variable [").append(key).append("] with oversized content [").append(ret).append("], only first ").append(bits).append(" bits will be applied.\r\n"); return ret.substring(0, bits); } return ret; } /** * Translate data str from "yyyymmdd" to "yyddd" * * 2012/3/19 change input format from "yy/mm/dd" to "yyyymmdd" * * @param str date string with format of "yyyymmdd" * @return result date string with format of "yyddd" */ protected String formatDateStr(String str) { return formatDateStr(str, "0"); } /** * Translate data str from "yyyymmdd" to "yyddd" plus days you want * * @param startDate date string with format of "yyyymmdd" * @param strDays the number of days need to be added on * @return result date string with format of "yyddd" */ protected String formatDateStr(String startDate, String strDays) { // Initial Calendar object Calendar cal = Calendar.getInstance(); int days; startDate = startDate.replaceAll("/", ""); try { days = Double.valueOf(strDays).intValue(); // Set date with input value cal.set(Integer.parseInt(startDate.substring(0, 4)), Integer.parseInt(startDate.substring(4, 6)) - 1, Integer.parseInt(startDate.substring(6))); cal.add(Calendar.DATE, days); // translatet to yyddd format return String.format("%1$02d%2$03d", cal.get(Calendar.YEAR) % 100, cal.get(Calendar.DAY_OF_YEAR)); } catch (Exception e) { // if tranlate failed, then use default value for date // sbError.append("! Waring: There is a invalid date [").append(startDate).append("]\r\n"); return "-99"; //formatDateStr(defValD); } } /** * Get experiment name without any extention content after first underscore * * @param result date holder for experiment data * @return experiment name */ protected String getExName(Map result) { String ret = getValueOr(result, "exname", ""); if (ret.contains(".")) { ret = ret.substring(0, ret.length() - 1).replace(".", ""); } // TODO need to be updated with a translate rule for other models' exname if (ret.matches("[\\w ]+(_+\\d+)+$")) { ret = ret.replaceAll("(_+\\d+)+$", ""); } return ret; } /** * Get crop id with 2-bit format * * @param result date holder for experiment data * @return crop id */ protected String getCrid(Map result) { HashMap mgnData = getObjectOr(result, "management", new HashMap()); ArrayList<HashMap> events = getObjectOr(mgnData, "events", new ArrayList()); String crid = null; for (int i = 0; i < events.size(); i++) { if (events.get(i).get("event").equals("planting")) { if (crid == null) { crid = (String) events.get(i).get("crid"); } else if (!crid.equals(events.get(i).get("crid"))) { crid = "SQ"; break; } } } DssatCRIDHelper crids = new DssatCRIDHelper(); return crids.get2BitCrid(crid); } /** * Generate output file name * * @param result date holder for experiment data * @param fileType the last letter from file extend name * @return file name */ protected String getFileName(Map result, String fileType) { String exname = getExName(result); String crid = getCrid(result); if (exname.length() == 10) { if (crid.equals("XX")) { crid = exname.substring(exname.length() - 2, exname.length()); } } String ret; if (exToFileMap.containsKey(exname + "_" + crid)) { return exToFileMap.get(exname + "_" + crid) + fileType; } else { ret = exname; if (ret == null || ret.equals("")) { ret = "TEMP0001"; } else { try { if (ret.endsWith(crid)) { ret = ret.substring(0, ret.length() - crid.length()); } // If the exname is too long if (ret.length() > 8) { ret = ret.substring(0, 8); } // If the exname do not follow the Dssat rule if (!ret.matches("[\\w ]{1,6}\\d{2}$")) { if (ret.length() > 6) { ret = ret.substring(0 ,6); } ret += "01"; } } catch (Exception e) { ret = "TEMP0001"; } } // Find a non-repeated file name int count; while (fileNameSet.contains(ret + "." + crid)) { try { count = Integer.parseInt(ret.substring(ret.length() - 2, ret.length())); count++; } catch (Exception e) { count = 1; } ret = ret.replaceAll("\\w{2}$", String.format("%02d", count)); } } exToFileMap.put(exname + "_" + crid, ret + "." + crid); fileNameSet.add(ret + "." + crid); return ret + "." + crid + fileType; } /** * Revise output path * * @param path the output path * @return revised path */ public static String revisePath(String path) { if (!path.trim().equals("")) { // path = path.replaceAll("/", File.separator); if (!path.endsWith(File.separator)) { path += File.separator; } File f = new File(path); if (f.isFile()) { f = f.getParentFile(); } if (f != null && !f.exists()) { f.mkdirs(); } } return path; } /** * Get output file object */ public File getOutputFile() { return outputFile; } /** * decompress the data in a map object * * @param m input map */ protected void decompressData(HashMap m) { for (Object key : m.keySet()) { if (m.get(key) instanceof ArrayList) { // iterate sub array nodes decompressData((ArrayList) m.get(key)); } else if (m.get(key) instanceof HashMap) { // iterate sub data nodes decompressData((HashMap) m.get(key)); } else { // ignore other type nodes } } } /** * decompress the data in an ArrayList object * * @param arr input ArrayList * */ protected void decompressData(ArrayList arr) { HashMap fstData = null; // The first data record (Map type) HashMap cprData; // The following data record which will be compressed for (int i = 0; i < arr.size(); i++) { if (arr.get(i) instanceof ArrayList) { // iterate sub array nodes decompressData((ArrayList) arr.get(i)); } else if (arr.get(i) instanceof HashMap) { // iterate sub data nodes decompressData((HashMap) arr.get(i)); // Compress data for current array if (fstData == null) { // Get first data node fstData = (HashMap) arr.get(i); } else { cprData = (HashMap) arr.get(i); // The omitted data will be recovered to the following map; Only data item (String type) will be processed for (Object key : fstData.keySet()) { if (!cprData.containsKey(key)) { cprData.put(key, fstData.get(key)); } } } } else { } } } /** * Get plating date from experiment management event * * @param result the experiment data object * @return plating date */ protected String getPdate(Map result) { HashMap management = getObjectOr(result, "management", new HashMap()); ArrayList<HashMap> events = getObjectOr(management, "events", new ArrayList<HashMap>()); for (int i = 0; i < events.size(); i++) { if (getValueOr(events.get(i), "event", "").equals("planting")) { return getValueOr(events.get(i), "date", ""); } } return ""; } /** * Get the weather file name for auto-generating (extend name not included) * * @param data experiment data holder or weather data holder * @return the weather file name */ protected String getWthFileName(HashMap data) { // String agmipFileHack = getValueOr(wthFile, "wst_name", ""); // if (agmipFileHack.length() == 8) { // return agmipFileHack; String ret = getObjectOr(data, "wst_id", "").toString(); if (ret.equals("") || ret.length() > 8) { ret = wthHelper.createWthFileName(getObjectOr(data, "weather", data)); if (ret.equals("")) { ret = "AGMP"; } } return ret; } protected String getSoilID(HashMap data) { return soilHelper.getSoilID(data); // String ret = getObjectOr(data, "soil_id", ""); // ret = ret.trim(); // if (ret.equals("")) { // return ret; // while (ret.length() < 8) { // ret += "_"; // return ret; } /** * Set default value for missing data * */ protected void setDefVal() { // defValD = ""; No need to set default value for Date type in weather file defValR = "-99"; defValC = "-99"; defValI = "-99"; sbError = new StringBuilder(); outputFile = null; } protected static String getStackTrace(Throwable aThrowable) { final Writer result = new StringWriter(); final PrintWriter printWriter = new PrintWriter(result); aThrowable.printStackTrace(printWriter); return result.toString(); } }
package org.b3log.symphony.service; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.b3log.latke.Keys; import org.b3log.latke.event.Event; import org.b3log.latke.event.EventException; import org.b3log.latke.event.EventManager; import org.b3log.latke.ioc.inject.Inject; import org.b3log.latke.logging.Level; import org.b3log.latke.logging.Logger; import org.b3log.latke.model.User; import org.b3log.latke.repository.*; import org.b3log.latke.repository.annotation.Transactional; import org.b3log.latke.repository.jdbc.JdbcRepository; import org.b3log.latke.service.LangPropsService; import org.b3log.latke.service.ServiceException; import org.b3log.latke.service.annotation.Service; import org.b3log.latke.util.Ids; import org.b3log.symphony.event.EventTypes; import org.b3log.symphony.model.*; import org.b3log.symphony.repository.*; import org.b3log.symphony.util.Emotions; import org.b3log.symphony.util.Pangu; import org.b3log.symphony.util.Runes; import org.b3log.symphony.util.Symphonys; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.jsoup.Jsoup; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.*; @Service public class ArticleMgmtService { /** * Logger. */ private static final Logger LOGGER = Logger.getLogger(ArticleMgmtService.class); /** * Tag max count. */ private static final int TAG_MAX_CNT = 4; /** * Comment repository. */ @Inject private CommentRepository commentRepository; /** * Article repository. */ @Inject private ArticleRepository articleRepository; /** * Tag repository. */ @Inject private TagRepository tagRepository; /** * Tag-Article repository. */ @Inject private TagArticleRepository tagArticleRepository; /** * User repository. */ @Inject private UserRepository userRepository; /** * User-Tag repository. */ @Inject private UserTagRepository userTagRepository; /** * Option repository. */ @Inject private OptionRepository optionRepository; /** * Notification repository. */ @Inject private NotificationRepository notificationRepository; /** * Revision repository. */ @Inject private RevisionRepository revisionRepository; /** * Tag management service. */ @Inject private TagMgmtService tagMgmtService; /** * Event manager. */ @Inject private EventManager eventManager; /** * Language service. */ @Inject private LangPropsService langPropsService; /** * Pointtransfer management service. */ @Inject private PointtransferMgmtService pointtransferMgmtService; /** * Reward management service. */ @Inject private RewardMgmtService rewardMgmtService; /** * Reward query service. */ @Inject private RewardQueryService rewardQueryService; /** * Follow query service. */ @Inject private FollowQueryService followQueryService; /** * Tag query service. */ @Inject private TagQueryService tagQueryService; /** * Notification management service. */ @Inject private NotificationMgmtService notificationMgmtService; /** * Liveness management service. */ @Inject private LivenessMgmtService livenessMgmtService; /** * Search management service. */ @Inject private SearchMgmtService searchMgmtService; /** * Audio management service. */ @Inject private AudioMgmtService audioMgmtService; /** * Determines whether the specified tag title exists in the specified tags. * * @param tagTitle the specified tag title * @param tags the specified tags * @return {@code true} if it exists, {@code false} otherwise * @throws JSONException json exception */ private static boolean tagExists(final String tagTitle, final List<JSONObject> tags) throws JSONException { for (final JSONObject tag : tags) { if (tag.getString(Tag.TAG_TITLE).equals(tagTitle)) { return true; } } return false; } public void removeArticle(final String articleId) throws ServiceException { JSONObject article = null; try { article = articleRepository.get(articleId); } catch (final Exception e) { LOGGER.log(Level.ERROR, "Gets article [id=" + articleId + "] failed", e); } if (null == article) { return; } final int commentCnt = article.optInt(Article.ARTICLE_COMMENT_CNT); if (commentCnt > 0) { throw new ServiceException(langPropsService.get("removeArticleFoundCmtLabel")); } final int watchCnt = article.optInt(Article.ARTICLE_WATCH_CNT); final int collectCnt = article.optInt(Article.ARTICLE_COLLECT_CNT); final int ups = article.optInt(Article.ARTICLE_GOOD_CNT); final int downs = article.optInt(Article.ARTICLE_BAD_CNT); if (watchCnt > 0 || collectCnt > 0 || ups > 0 || downs > 0) { throw new ServiceException("removeArticleFoundWatchEtcLabel"); } final int rewardCnt = (int) rewardQueryService.rewardedCount(articleId, Reward.TYPE_C_ARTICLE); if (rewardCnt > 0) { throw new ServiceException("removeArticleFoundRewardLabel"); } final int thankCnt = (int) rewardQueryService.rewardedCount(articleId, Reward.TYPE_C_THANK_ARTICLE); if (thankCnt > 0) { throw new ServiceException("removeArticleFoundThankLabel"); } // Perform removal removeArticleByAdmin(articleId); } /** * Generates article's audio. * * @param article the specified article * @param userId the specified user id */ public void genArticleAudio(final JSONObject article, final String userId) { if (Article.ARTICLE_TYPE_C_THOUGHT == article.optInt(Article.ARTICLE_TYPE)) { return; } final String articleId = article.optString(Keys.OBJECT_ID); String previewContent = article.optString(Article.ARTICLE_CONTENT); previewContent = Emotions.clear(Jsoup.parse(previewContent).text()); previewContent = StringUtils.substring(previewContent, 0, 512); final String contentToTTS = previewContent; new Thread(() -> { final Transaction transaction = articleRepository.beginTransaction(); String audioURL = ""; if (StringUtils.length(contentToTTS) < 96 || Runes.getChinesePercent(contentToTTS) < 40) { LOGGER.trace("Content is too short to TTS [contentToTTS=" + contentToTTS + "]"); } else { audioURL = audioMgmtService.tts(contentToTTS, Article.ARTICLE, articleId, userId); } article.put(Article.ARTICLE_AUDIO_URL, audioURL); try { final JSONObject toUpdate = articleRepository.get(articleId); toUpdate.put(Article.ARTICLE_AUDIO_URL, audioURL); articleRepository.update(articleId, toUpdate); transaction.commit(); if (StringUtils.isNotBlank(audioURL)) { LOGGER.debug("Generated article [id=" + articleId + "] audio"); } } catch (final Exception e) { if (transaction.isActive()) { transaction.rollback(); } LOGGER.log(Level.ERROR, "Updates article's audio URL failed", e); } JdbcRepository.dispose(); }).start(); } /** * Removes an article specified with the given article id. Calls this method will remove all existed data related * with the specified article forcibly. * * @param articleId the given article id */ @Transactional public void removeArticleByAdmin(final String articleId) { try { final JSONObject article = articleRepository.get(articleId); if (null == article) { return; } Query query = new Query().setFilter(new PropertyFilter( Comment.COMMENT_ON_ARTICLE_ID, FilterOperator.EQUAL, articleId)).setPageCount(1); final JSONArray comments = commentRepository.get(query).optJSONArray(Keys.RESULTS); final int commentCnt = comments.length(); for (int i = 0; i < commentCnt; i++) { final JSONObject comment = comments.optJSONObject(i); final String commentId = comment.optString(Keys.OBJECT_ID); commentRepository.removeComment(commentId); } final String authorId = article.optString(Article.ARTICLE_AUTHOR_ID); final JSONObject author = userRepository.get(authorId); author.put(UserExt.USER_ARTICLE_COUNT, author.optInt(UserExt.USER_ARTICLE_COUNT) - 1); userRepository.update(author.optString(Keys.OBJECT_ID), author); final String city = article.optString(Article.ARTICLE_CITY); final String cityStatId = city + "-ArticleCount"; final JSONObject cityArticleCntOption = optionRepository.get(cityStatId); if (null != cityArticleCntOption) { cityArticleCntOption.put(Option.OPTION_VALUE, cityArticleCntOption.optInt(Option.OPTION_VALUE) - 1); optionRepository.update(cityStatId, cityArticleCntOption); } final JSONObject articleCntOption = optionRepository.get(Option.ID_C_STATISTIC_ARTICLE_COUNT); articleCntOption.put(Option.OPTION_VALUE, articleCntOption.optInt(Option.OPTION_VALUE) - 1); optionRepository.update(Option.ID_C_STATISTIC_ARTICLE_COUNT, articleCntOption); articleRepository.remove(articleId); // Remove article revisions query = new Query().setFilter(CompositeFilterOperator.and( new PropertyFilter(Revision.REVISION_DATA_ID, FilterOperator.EQUAL, articleId), new PropertyFilter(Revision.REVISION_DATA_TYPE, FilterOperator.EQUAL, Revision.DATA_TYPE_C_ARTICLE) )); final JSONArray articleRevisions = revisionRepository.get(query).optJSONArray(Keys.RESULTS); for (int i = 0; i < articleRevisions.length(); i++) { final JSONObject articleRevision = articleRevisions.optJSONObject(i); revisionRepository.remove(articleRevision.optString(Keys.OBJECT_ID)); } final List<JSONObject> tagArticleRels = tagArticleRepository.getByArticleId(articleId); for (final JSONObject tagArticleRel : tagArticleRels) { final String tagId = tagArticleRel.optString(Tag.TAG + "_" + Keys.OBJECT_ID); final JSONObject tag = tagRepository.get(tagId); int cnt = tag.optInt(Tag.TAG_REFERENCE_CNT) - 1; cnt = cnt < 0 ? 0 : cnt; tag.put(Tag.TAG_REFERENCE_CNT, cnt); tag.put(Tag.TAG_RANDOM_DOUBLE, Math.random()); tagRepository.update(tagId, tag); } tagArticleRepository.removeByArticleId(articleId); notificationRepository.removeByDataId(articleId); if (Symphonys.getBoolean("algolia.enabled")) { searchMgmtService.removeAlgoliaDocument(article); } if (Symphonys.getBoolean("es.enabled")) { searchMgmtService.removeESDocument(article, Article.ARTICLE); } } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Removes an article error [id=" + articleId + "]", e); } } /** * Increments the view count of the specified article by the given article id. * * @param articleId the given article id * @throws ServiceException service exception */ public void incArticleViewCount(final String articleId) throws ServiceException { Symphonys.EXECUTOR_SERVICE.submit(new Runnable() { @Override public void run() { final Transaction transaction = articleRepository.beginTransaction(); try { final JSONObject article = articleRepository.get(articleId); if (null == article) { return; } final int viewCnt = article.optInt(Article.ARTICLE_VIEW_CNT); article.put(Article.ARTICLE_VIEW_CNT, viewCnt + 1); article.put(Article.ARTICLE_RANDOM_DOUBLE, Math.random()); articleRepository.update(articleId, article); transaction.commit(); } catch (final RepositoryException e) { if (transaction.isActive()) { transaction.rollback(); } LOGGER.log(Level.ERROR, "Incs an article view count failed", e); } } }); } /** * Adds an article with the specified request json object. * * @param requestJSONObject the specified request json object, for example, * "articleTitle": "", * "articleTags": "", * "articleContent": "", * "articleEditorType": "", * "articleAuthorId": "", * "articleCommentable": boolean, // optional, default to true * "syncWithSymphonyClient": boolean, // optional * "clientArticleId": "", // optional * "clientArticlePermalink": "", // optional * "isBroadcast": boolean, // Client broadcast, optional * "articleType": int, // optional, default to 0 * "articleRewardContent": "", // optional, default to "" * "articleRewardPoint": int, // optional, default to 0 * "articleIP": "", // optional, default to "" * "articleUA": "", // optional, default to "" * "articleAnonymous": int, // optional, default to 0 (public) * "articleAnonymousView": int // optional, default to 0 (use global) * , see {@link Article} for more details * @return generated article id * @throws ServiceException service exception */ public synchronized String addArticle(final JSONObject requestJSONObject) throws ServiceException { final long currentTimeMillis = System.currentTimeMillis(); final boolean fromClient = requestJSONObject.has(Article.ARTICLE_CLIENT_ARTICLE_ID); final String authorId = requestJSONObject.optString(Article.ARTICLE_AUTHOR_ID); JSONObject author = null; final int rewardPoint = requestJSONObject.optInt(Article.ARTICLE_REWARD_POINT, 0); if (rewardPoint < 0) { throw new ServiceException(langPropsService.get("invalidRewardPointLabel")); } final int articleAnonymous = requestJSONObject.optInt(Article.ARTICLE_ANONYMOUS); final boolean syncWithSymphonyClient = requestJSONObject.optBoolean(Article.ARTICLE_SYNC_TO_CLIENT); String articleTitle = requestJSONObject.optString(Article.ARTICLE_TITLE); articleTitle = Emotions.toAliases(articleTitle); articleTitle = Pangu.spacingText(articleTitle); articleTitle = StringUtils.trim(articleTitle); final int articleType = requestJSONObject.optInt(Article.ARTICLE_TYPE, Article.ARTICLE_TYPE_C_NORMAL); try { // check if admin allow to add article final JSONObject option = optionRepository.get(Option.ID_C_MISC_ALLOW_ADD_ARTICLE); if (!"0".equals(option.optString(Option.OPTION_VALUE))) { throw new ServiceException(langPropsService.get("notAllowAddArticleLabel")); } author = userRepository.get(authorId); if (currentTimeMillis - author.optLong(UserExt.USER_LATEST_ARTICLE_TIME) < Symphonys.getLong("minStepArticleTime") && !Role.ROLE_ID_C_ADMIN.equals(author.optString(User.USER_ROLE))) { LOGGER.log(Level.WARN, "Adds article too frequent [userName={0}]", author.optString(User.USER_NAME)); throw new ServiceException(langPropsService.get("tooFrequentArticleLabel")); } final int balance = author.optInt(UserExt.USER_POINT); if (Article.ARTICLE_ANONYMOUS_C_ANONYMOUS == articleAnonymous) { final int anonymousPoint = Symphonys.getInt("anonymous.point"); if (balance < anonymousPoint) { String anonymousEnabelPointLabel = langPropsService.get("anonymousEnabelPointLabel"); anonymousEnabelPointLabel = anonymousEnabelPointLabel.replace("${point}", String.valueOf(anonymousPoint)); throw new ServiceException(anonymousEnabelPointLabel); } } if (!fromClient && Article.ARTICLE_ANONYMOUS_C_PUBLIC == articleAnonymous) { // Point final long followerCnt = followQueryService.getFollowerCount(authorId, Follow.FOLLOWING_TYPE_C_USER); final int addition = (int) Math.round(Math.sqrt(followerCnt)); final int broadcast = Article.ARTICLE_TYPE_C_CITY_BROADCAST == articleType ? Pointtransfer.TRANSFER_SUM_C_ADD_ARTICLE_BROADCAST : 0; final int sum = Pointtransfer.TRANSFER_SUM_C_ADD_ARTICLE + addition + rewardPoint + broadcast; if (balance - sum < 0) { throw new ServiceException(langPropsService.get("insufficientBalanceLabel")); } } if (Article.ARTICLE_TYPE_C_DISCUSSION != articleType && Article.ARTICLE_TYPE_C_BOOK != articleType) { final JSONObject maybeExist = articleRepository.getByTitle(articleTitle); if (null != maybeExist) { final String existArticleAuthorId = maybeExist.optString(Article.ARTICLE_AUTHOR_ID); String msg; if (existArticleAuthorId.equals(authorId)) { msg = langPropsService.get("duplicatedArticleTitleSelfLabel"); msg = msg.replace("{article}", "<a target='_blank' href='/article/" + maybeExist.optString(Keys.OBJECT_ID) + "'>" + articleTitle + "</a>"); } else { final JSONObject existArticleAuthor = userRepository.get(existArticleAuthorId); final String userName = existArticleAuthor.optString(User.USER_NAME); msg = langPropsService.get("duplicatedArticleTitleLabel"); msg = msg.replace("{user}", "<a target='_blank' href='/member/" + userName + "'>" + userName + "</a>"); msg = msg.replace("{article}", "<a target='_blank' href='/article/" + maybeExist.optString(Keys.OBJECT_ID) + "'>" + articleTitle + "</a>"); } throw new ServiceException(msg); } } } catch (final RepositoryException e) { throw new ServiceException(e); } final Transaction transaction = articleRepository.beginTransaction(); try { final String ret = Ids.genTimeMillisId(); final JSONObject article = new JSONObject(); article.put(Keys.OBJECT_ID, ret); final String clientArticleId = requestJSONObject.optString(Article.ARTICLE_CLIENT_ARTICLE_ID, ret); final String clientArticlePermalink = requestJSONObject.optString(Article.ARTICLE_CLIENT_ARTICLE_PERMALINK); final boolean isBroadcast = requestJSONObject.optBoolean(Article.ARTICLE_T_IS_BROADCAST); article.put(Article.ARTICLE_TITLE, articleTitle); article.put(Article.ARTICLE_TAGS, requestJSONObject.optString(Article.ARTICLE_TAGS)); String articleContent = requestJSONObject.optString(Article.ARTICLE_CONTENT); articleContent = Emotions.toAliases(articleContent); articleContent = StringUtils.replace(articleContent, langPropsService.get("uploadingLabel", Locale.SIMPLIFIED_CHINESE), ""); articleContent = StringUtils.replace(articleContent, langPropsService.get("uploadingLabel", Locale.US), ""); article.put(Article.ARTICLE_CONTENT, articleContent); article.put(Article.ARTICLE_REWARD_CONTENT, requestJSONObject.optString(Article.ARTICLE_REWARD_CONTENT)); article.put(Article.ARTICLE_EDITOR_TYPE, requestJSONObject.optString(Article.ARTICLE_EDITOR_TYPE)); article.put(Article.ARTICLE_SYNC_TO_CLIENT, fromClient ? true : author.optBoolean(UserExt.SYNC_TO_CLIENT)); article.put(Article.ARTICLE_AUTHOR_ID, authorId); article.put(Article.ARTICLE_COMMENT_CNT, 0); article.put(Article.ARTICLE_VIEW_CNT, 0); article.put(Article.ARTICLE_GOOD_CNT, 0); article.put(Article.ARTICLE_BAD_CNT, 0); article.put(Article.ARTICLE_COLLECT_CNT, 0); article.put(Article.ARTICLE_WATCH_CNT, 0); article.put(Article.ARTICLE_COMMENTABLE, requestJSONObject.optBoolean(Article.ARTICLE_COMMENTABLE, true)); article.put(Article.ARTICLE_CREATE_TIME, currentTimeMillis); article.put(Article.ARTICLE_UPDATE_TIME, currentTimeMillis); article.put(Article.ARTICLE_LATEST_CMT_TIME, 0); article.put(Article.ARTICLE_LATEST_CMTER_NAME, ""); article.put(Article.ARTICLE_PERMALINK, "/article/" + ret); if (isBroadcast) { article.put(Article.ARTICLE_CLIENT_ARTICLE_ID, "aBroadcast"); } else { article.put(Article.ARTICLE_CLIENT_ARTICLE_ID, clientArticleId); } article.put(Article.ARTICLE_CLIENT_ARTICLE_PERMALINK, clientArticlePermalink); article.put(Article.ARTICLE_RANDOM_DOUBLE, Math.random()); article.put(Article.REDDIT_SCORE, 0); article.put(Article.ARTICLE_STATUS, Article.ARTICLE_STATUS_C_VALID); article.put(Article.ARTICLE_TYPE, articleType); article.put(Article.ARTICLE_REWARD_POINT, rewardPoint); String city = ""; if (UserExt.USER_GEO_STATUS_C_PUBLIC == author.optInt(UserExt.USER_GEO_STATUS)) { city = author.optString(UserExt.USER_CITY); } article.put(Article.ARTICLE_CITY, city); article.put(Article.ARTICLE_ANONYMOUS, articleAnonymous); article.put(Article.ARTICLE_SYNC_TO_CLIENT, syncWithSymphonyClient); article.put(Article.ARTICLE_PERFECT, Article.ARTICLE_PERFECT_C_NOT_PERFECT); article.put(Article.ARTICLE_ANONYMOUS_VIEW, requestJSONObject.optInt(Article.ARTICLE_ANONYMOUS_VIEW, Article.ARTICLE_ANONYMOUS_VIEW_C_USE_GLOBAL)); article.put(Article.ARTICLE_AUDIO_URL, ""); String articleTags = article.optString(Article.ARTICLE_TAGS); articleTags = Tag.formatTags(articleTags); boolean sandboxEnv = false; if (StringUtils.containsIgnoreCase(articleTags, Tag.TAG_TITLE_C_SANDBOX)) { articleTags = Tag.TAG_TITLE_C_SANDBOX; sandboxEnv = true; } String[] tagTitles = articleTags.split(","); if (!sandboxEnv && tagTitles.length < TAG_MAX_CNT && tagTitles.length < 3 && Article.ARTICLE_TYPE_C_DISCUSSION != articleType && Article.ARTICLE_TYPE_C_THOUGHT != articleType && !Tag.containsReservedTags(articleTags)) { final String content = article.optString(Article.ARTICLE_TITLE) + " " + Jsoup.parse("<p>" + article.optString(Article.ARTICLE_CONTENT) + "</p>").text(); final List<String> genTags = tagQueryService.generateTags(content, 1); if (!genTags.isEmpty()) { articleTags = articleTags + "," + StringUtils.join(genTags, ","); articleTags = Tag.formatTags(articleTags); articleTags = Tag.useHead(articleTags, TAG_MAX_CNT); } } if (StringUtils.isBlank(articleTags)) { articleTags = "B3log"; } articleTags = Tag.formatTags(articleTags); article.put(Article.ARTICLE_TAGS, articleTags); tagTitles = articleTags.split(","); tag(tagTitles, article, author); final String ip = requestJSONObject.optString(Article.ARTICLE_IP); article.put(Article.ARTICLE_IP, ip); String ua = requestJSONObject.optString(Article.ARTICLE_UA); if (StringUtils.length(ua) > Common.MAX_LENGTH_UA) { ua = StringUtils.substring(ua, 0, Common.MAX_LENGTH_UA); } article.put(Article.ARTICLE_UA, ua); article.put(Article.ARTICLE_STICK, 0L); final JSONObject articleCntOption = optionRepository.get(Option.ID_C_STATISTIC_ARTICLE_COUNT); final int articleCnt = articleCntOption.optInt(Option.OPTION_VALUE); articleCntOption.put(Option.OPTION_VALUE, articleCnt + 1); optionRepository.update(Option.ID_C_STATISTIC_ARTICLE_COUNT, articleCntOption); if (!StringUtils.isBlank(city)) { final String cityStatId = city + "-ArticleCount"; JSONObject cityArticleCntOption = optionRepository.get(cityStatId); if (null == cityArticleCntOption) { cityArticleCntOption = new JSONObject(); cityArticleCntOption.put(Keys.OBJECT_ID, cityStatId); cityArticleCntOption.put(Option.OPTION_VALUE, 1); cityArticleCntOption.put(Option.OPTION_CATEGORY, city + "-statistic"); optionRepository.add(cityArticleCntOption); } else { final int cityArticleCnt = cityArticleCntOption.optInt(Option.OPTION_VALUE); cityArticleCntOption.put(Option.OPTION_VALUE, cityArticleCnt + 1); optionRepository.update(cityStatId, cityArticleCntOption); } } author.put(UserExt.USER_ARTICLE_COUNT, author.optInt(UserExt.USER_ARTICLE_COUNT) + 1); author.put(UserExt.USER_LATEST_ARTICLE_TIME, currentTimeMillis); // Updates user article count (and new tag count), latest article time userRepository.update(author.optString(Keys.OBJECT_ID), author); final String articleId = articleRepository.add(article); if (Article.ARTICLE_TYPE_C_THOUGHT != articleType) { // Revision final JSONObject revision = new JSONObject(); revision.put(Revision.REVISION_AUTHOR_ID, authorId); final JSONObject revisionData = new JSONObject(); revisionData.put(Article.ARTICLE_TITLE, articleTitle); revisionData.put(Article.ARTICLE_CONTENT, articleContent); revision.put(Revision.REVISION_DATA, revisionData.toString()); revision.put(Revision.REVISION_DATA_ID, articleId); revision.put(Revision.REVISION_DATA_TYPE, Revision.DATA_TYPE_C_ARTICLE); revisionRepository.add(revision); } transaction.commit(); try { Thread.sleep(50); // wait for db write to avoid artitle duplication } catch (final Exception e) { } // Grows the tag graph tagMgmtService.relateTags(article.optString(Article.ARTICLE_TAGS)); if (!fromClient && Article.ARTICLE_ANONYMOUS_C_PUBLIC == articleAnonymous) { // Point final long followerCnt = followQueryService.getFollowerCount(authorId, Follow.FOLLOWING_TYPE_C_USER); final int addition = (int) Math.round(Math.sqrt(followerCnt)); pointtransferMgmtService.transfer(authorId, Pointtransfer.ID_C_SYS, Pointtransfer.TRANSFER_TYPE_C_ADD_ARTICLE, Pointtransfer.TRANSFER_SUM_C_ADD_ARTICLE + addition, articleId, System.currentTimeMillis()); if (rewardPoint > 0) { // Enabe reward pointtransferMgmtService.transfer(authorId, Pointtransfer.ID_C_SYS, Pointtransfer.TRANSFER_TYPE_C_ADD_ARTICLE_REWARD, Pointtransfer.TRANSFER_SUM_C_ADD_ARTICLE_REWARD, articleId, System.currentTimeMillis()); } if (Article.ARTICLE_TYPE_C_CITY_BROADCAST == articleType) { pointtransferMgmtService.transfer(authorId, Pointtransfer.ID_C_SYS, Pointtransfer.TRANSFER_TYPE_C_ADD_ARTICLE_BROADCAST, Pointtransfer.TRANSFER_SUM_C_ADD_ARTICLE_BROADCAST, articleId, System.currentTimeMillis()); } // Liveness livenessMgmtService.incLiveness(authorId, Liveness.LIVENESS_ARTICLE); } // Event final JSONObject eventData = new JSONObject(); eventData.put(Common.FROM_CLIENT, fromClient); eventData.put(Article.ARTICLE, article); try { eventManager.fireEventAsynchronously(new Event<>(EventTypes.ADD_ARTICLE, eventData)); } catch (final EventException e) { LOGGER.log(Level.ERROR, e.getMessage(), e); } return ret; } catch (final RepositoryException e) { if (transaction.isActive()) { transaction.rollback(); } LOGGER.log(Level.ERROR, "Adds an article failed", e); throw new ServiceException(e); } } /** * Updates an article with the specified request json object. * * @param requestJSONObject the specified request json object, for example, * "oId": "", * "articleTitle": "", * "articleTags": "", * "articleContent": "", * "articleEditorType": "", * "articleCommentable": boolean, // optional, default to true * "clientArticlePermalink": "", // optional * "articleType": int // optional, default to 0 * "articleRewardContent": "", // optional, default to "" * "articleRewardPoint": int, // optional, default to 0 * "articleIP": "", // optional, default to "" * "articleUA": "", // optional default to "" * , see {@link Article} for more details * @throws ServiceException service exception */ public synchronized void updateArticle(final JSONObject requestJSONObject) throws ServiceException { String articleTitle = requestJSONObject.optString(Article.ARTICLE_TITLE); final boolean fromClient = requestJSONObject.has(Article.ARTICLE_CLIENT_ARTICLE_ID); String articleId; JSONObject oldArticle; String authorId; JSONObject author; int updatePointSum; int articleAnonymous = 0; try { // check if admin allow to add article final JSONObject option = optionRepository.get(Option.ID_C_MISC_ALLOW_ADD_ARTICLE); if (!"0".equals(option.optString(Option.OPTION_VALUE))) { throw new ServiceException(langPropsService.get("notAllowAddArticleLabel")); } articleId = requestJSONObject.optString(Keys.OBJECT_ID); oldArticle = articleRepository.get(articleId); authorId = oldArticle.optString(Article.ARTICLE_AUTHOR_ID); author = userRepository.get(authorId); final long followerCnt = followQueryService.getFollowerCount(authorId, Follow.FOLLOWING_TYPE_C_USER); int addition = (int) Math.round(Math.sqrt(followerCnt)); final long collectCnt = followQueryService.getFollowerCount(articleId, Follow.FOLLOWING_TYPE_C_ARTICLE); final long watchCnt = followQueryService.getFollowerCount(articleId, Follow.FOLLOWING_TYPE_C_ARTICLE_WATCH); addition += (collectCnt + watchCnt) * 2; updatePointSum = Pointtransfer.TRANSFER_SUM_C_UPDATE_ARTICLE + addition; articleAnonymous = oldArticle.optInt(Article.ARTICLE_ANONYMOUS); if (!fromClient && Article.ARTICLE_ANONYMOUS_C_PUBLIC == articleAnonymous) { // Point final int balance = author.optInt(UserExt.USER_POINT); if (balance - updatePointSum < 0) { throw new ServiceException(langPropsService.get("insufficientBalanceLabel")); } } final JSONObject maybeExist = articleRepository.getByTitle(articleTitle); if (null != maybeExist) { if (!oldArticle.optString(Article.ARTICLE_TITLE).equals(articleTitle)) { final String existArticleAuthorId = maybeExist.optString(Article.ARTICLE_AUTHOR_ID); String msg; if (existArticleAuthorId.equals(authorId)) { msg = langPropsService.get("duplicatedArticleTitleSelfLabel"); msg = msg.replace("{article}", "<a target='_blank' href='/article/" + maybeExist.optString(Keys.OBJECT_ID) + "'>" + articleTitle + "</a>"); } else { final JSONObject existArticleAuthor = userRepository.get(existArticleAuthorId); final String userName = existArticleAuthor.optString(User.USER_NAME); msg = langPropsService.get("duplicatedArticleTitleLabel"); msg = msg.replace("{user}", "<a target='_blank' href='/member/" + userName + "'>" + userName + "</a>"); msg = msg.replace("{article}", "<a target='_blank' href='/article/" + maybeExist.optString(Keys.OBJECT_ID) + "'>" + articleTitle + "</a>"); } throw new ServiceException(msg); } } } catch (final RepositoryException e) { throw new ServiceException(e); } final int articleType = requestJSONObject.optInt(Article.ARTICLE_TYPE, Article.ARTICLE_TYPE_C_NORMAL); final Transaction transaction = articleRepository.beginTransaction(); try { requestJSONObject.put(Article.ARTICLE_ANONYMOUS, articleAnonymous); processTagsForArticleUpdate(oldArticle, requestJSONObject, author); userRepository.update(author.optString(Keys.OBJECT_ID), author); articleTitle = Emotions.toAliases(articleTitle); articleTitle = Pangu.spacingText(articleTitle); final String oldTitle = oldArticle.optString(Article.ARTICLE_TITLE); oldArticle.put(Article.ARTICLE_TITLE, articleTitle); oldArticle.put(Article.ARTICLE_TAGS, requestJSONObject.optString(Article.ARTICLE_TAGS)); oldArticle.put(Article.ARTICLE_COMMENTABLE, requestJSONObject.optBoolean(Article.ARTICLE_COMMENTABLE, true)); oldArticle.put(Article.ARTICLE_TYPE, articleType); String articleContent = requestJSONObject.optString(Article.ARTICLE_CONTENT); articleContent = Emotions.toAliases(articleContent); articleContent = articleContent.replace(langPropsService.get("uploadingLabel", Locale.SIMPLIFIED_CHINESE), ""); articleContent = articleContent.replace(langPropsService.get("uploadingLabel", Locale.US), ""); final String oldContent = oldArticle.optString(Article.ARTICLE_CONTENT); oldArticle.put(Article.ARTICLE_CONTENT, articleContent); final long currentTimeMillis = System.currentTimeMillis(); final long createTime = oldArticle.optLong(Keys.OBJECT_ID); oldArticle.put(Article.ARTICLE_UPDATE_TIME, currentTimeMillis); final int rewardPoint = requestJSONObject.optInt(Article.ARTICLE_REWARD_POINT, 0); boolean enableReward = false; if (0 < rewardPoint) { if (1 > oldArticle.optInt(Article.ARTICLE_REWARD_POINT)) { enableReward = true; } oldArticle.put(Article.ARTICLE_REWARD_CONTENT, requestJSONObject.optString(Article.ARTICLE_REWARD_CONTENT)); oldArticle.put(Article.ARTICLE_REWARD_POINT, rewardPoint); } final String ip = requestJSONObject.optString(Article.ARTICLE_IP); oldArticle.put(Article.ARTICLE_IP, ip); String ua = requestJSONObject.optString(Article.ARTICLE_UA); if (StringUtils.length(ua) > Common.MAX_LENGTH_UA) { ua = StringUtils.substring(ua, 0, Common.MAX_LENGTH_UA); } oldArticle.put(Article.ARTICLE_UA, ua); final String clientArticlePermalink = requestJSONObject.optString(Article.ARTICLE_CLIENT_ARTICLE_PERMALINK); oldArticle.put(Article.ARTICLE_CLIENT_ARTICLE_PERMALINK, clientArticlePermalink); articleRepository.update(articleId, oldArticle); if (Article.ARTICLE_TYPE_C_THOUGHT != articleType && (!oldContent.equals(articleContent) || !oldTitle.equals(articleTitle))) { // Revision final JSONObject revision = new JSONObject(); revision.put(Revision.REVISION_AUTHOR_ID, authorId); final JSONObject revisionData = new JSONObject(); revisionData.put(Article.ARTICLE_TITLE, articleTitle); revisionData.put(Article.ARTICLE_CONTENT, articleContent); revision.put(Revision.REVISION_DATA, revisionData.toString()); revision.put(Revision.REVISION_DATA_ID, articleId); revision.put(Revision.REVISION_DATA_TYPE, Revision.DATA_TYPE_C_ARTICLE); revisionRepository.add(revision); } transaction.commit(); try { Thread.sleep(50); // wait for db write to avoid artitle duplication } catch (final Exception e) { } if (!fromClient && Article.ARTICLE_ANONYMOUS_C_PUBLIC == articleAnonymous) { if (currentTimeMillis - createTime > 1000 * 60 * 5) { pointtransferMgmtService.transfer(authorId, Pointtransfer.ID_C_SYS, Pointtransfer.TRANSFER_TYPE_C_UPDATE_ARTICLE, updatePointSum, articleId, System.currentTimeMillis()); } if (enableReward) { pointtransferMgmtService.transfer(authorId, Pointtransfer.ID_C_SYS, Pointtransfer.TRANSFER_TYPE_C_ADD_ARTICLE_REWARD, Pointtransfer.TRANSFER_SUM_C_ADD_ARTICLE_REWARD, articleId, System.currentTimeMillis()); } } // Event final JSONObject eventData = new JSONObject(); eventData.put(Common.FROM_CLIENT, fromClient); eventData.put(Article.ARTICLE, oldArticle); try { eventManager.fireEventAsynchronously(new Event<>(EventTypes.UPDATE_ARTICLE, eventData)); } catch (final EventException e) { LOGGER.log(Level.ERROR, e.getMessage(), e); } } catch (final Exception e) { if (transaction.isActive()) { transaction.rollback(); } LOGGER.log(Level.ERROR, "Updates an article failed", e); throw new ServiceException(e); } } /** * Updates the specified article by the given article id. * <p> * <b>Note</b>: This method just for admin console. * </p> * * @param articleId the given article id * @param article the specified article * @throws ServiceException service exception */ public void updateArticleByAdmin(final String articleId, final JSONObject article) throws ServiceException { final Transaction transaction = articleRepository.beginTransaction(); try { final String authorId = article.optString(Article.ARTICLE_AUTHOR_ID); final JSONObject author = userRepository.get(authorId); article.put(Article.ARTICLE_COMMENTABLE, Boolean.valueOf(article.optBoolean(Article.ARTICLE_COMMENTABLE))); article.put(Article.ARTICLE_SYNC_TO_CLIENT, author.optBoolean(UserExt.SYNC_TO_CLIENT)); final JSONObject oldArticle = articleRepository.get(articleId); if (Article.ARTICLE_STATUS_C_INVALID == article.optInt(Article.ARTICLE_STATUS)) { article.put(Article.ARTICLE_TAGS, ""); } processTagsForArticleUpdate(oldArticle, article, author); String articleTitle = article.optString(Article.ARTICLE_TITLE); articleTitle = Emotions.toAliases(articleTitle); article.put(Article.ARTICLE_TITLE, articleTitle); if (Article.ARTICLE_TYPE_C_THOUGHT == article.optInt(Article.ARTICLE_TYPE)) { article.put(Article.ARTICLE_CONTENT, oldArticle.optString(Article.ARTICLE_CONTENT)); } else { String articleContent = article.optString(Article.ARTICLE_CONTENT); articleContent = Emotions.toAliases(articleContent); article.put(Article.ARTICLE_CONTENT, articleContent); } final int perfect = article.optInt(Article.ARTICLE_PERFECT); if (Article.ARTICLE_PERFECT_C_PERFECT == perfect) { // if it is perfect, allow anonymous view article.put(Article.ARTICLE_ANONYMOUS_VIEW, Article.ARTICLE_ANONYMOUS_VIEW_C_ALLOW); // updates tag-article perfect final List<JSONObject> tagArticleRels = tagArticleRepository.getByArticleId(articleId); for (final JSONObject tagArticleRel : tagArticleRels) { tagArticleRel.put(Article.ARTICLE_PERFECT, Article.ARTICLE_PERFECT_C_PERFECT); tagArticleRepository.update(tagArticleRel.optString(Keys.OBJECT_ID), tagArticleRel); } } userRepository.update(authorId, author); articleRepository.update(articleId, article); transaction.commit(); if (Article.ARTICLE_PERFECT_C_NOT_PERFECT == oldArticle.optInt(Article.ARTICLE_PERFECT) && Article.ARTICLE_PERFECT_C_PERFECT == perfect) { final JSONObject notification = new JSONObject(); notification.put(Notification.NOTIFICATION_USER_ID, authorId); notification.put(Notification.NOTIFICATION_DATA_ID, articleId); notificationMgmtService.addPerfectArticleNotification(notification); pointtransferMgmtService.transfer(Pointtransfer.ID_C_SYS, authorId, Pointtransfer.TRANSFER_TYPE_C_PERFECT_ARTICLE, Pointtransfer.TRANSFER_SUM_C_PERFECT_ARTICLE, articleId, System.currentTimeMillis()); } if (Article.ARTICLE_STATUS_C_VALID != article.optInt(Article.ARTICLE_STATUS)) { if (Symphonys.getBoolean("algolia.enabled")) { searchMgmtService.removeAlgoliaDocument(article); } if (Symphonys.getBoolean("es.enabled")) { searchMgmtService.removeESDocument(article, Article.ARTICLE); } } } catch (final Exception e) { if (transaction.isActive()) { transaction.rollback(); } LOGGER.log(Level.ERROR, "Updates an article[id=" + articleId + "] failed", e); throw new ServiceException(e); } } /** * A user specified by the given sender id rewards the author of an article specified by the given article id. * * @param articleId the given article id * @param senderId the given sender id * @throws ServiceException service exception */ public void reward(final String articleId, final String senderId) throws ServiceException { try { final JSONObject article = articleRepository.get(articleId); if (null == article) { return; } if (Article.ARTICLE_STATUS_C_INVALID == article.optInt(Article.ARTICLE_STATUS)) { return; } final JSONObject sender = userRepository.get(senderId); if (null == sender) { return; } if (UserExt.USER_STATUS_C_VALID != sender.optInt(UserExt.USER_STATUS)) { return; } final String receiverId = article.optString(Article.ARTICLE_AUTHOR_ID); final JSONObject receiver = userRepository.get(receiverId); if (null == receiver) { return; } if (UserExt.USER_STATUS_C_VALID != receiver.optInt(UserExt.USER_STATUS)) { return; } if (receiverId.equals(senderId)) { return; } final int rewardPoint = article.optInt(Article.ARTICLE_REWARD_POINT); if (rewardPoint < 1) { return; } if (rewardQueryService.isRewarded(senderId, articleId, Reward.TYPE_C_ARTICLE)) { return; } final String rewardId = Ids.genTimeMillisId(); if (Article.ARTICLE_ANONYMOUS_C_PUBLIC == article.optInt(Article.ARTICLE_ANONYMOUS)) { final boolean succ = null != pointtransferMgmtService.transfer(senderId, receiverId, Pointtransfer.TRANSFER_TYPE_C_ARTICLE_REWARD, rewardPoint, rewardId, System.currentTimeMillis()); if (!succ) { throw new ServiceException(); } } final JSONObject reward = new JSONObject(); reward.put(Keys.OBJECT_ID, rewardId); reward.put(Reward.SENDER_ID, senderId); reward.put(Reward.DATA_ID, articleId); reward.put(Reward.TYPE, Reward.TYPE_C_ARTICLE); rewardMgmtService.addReward(reward); final JSONObject notification = new JSONObject(); notification.put(Notification.NOTIFICATION_USER_ID, receiverId); notification.put(Notification.NOTIFICATION_DATA_ID, rewardId); notificationMgmtService.addArticleRewardNotification(notification); livenessMgmtService.incLiveness(senderId, Liveness.LIVENESS_REWARD); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Rewards an article[id=" + articleId + "] failed", e); throw new ServiceException(e); } } /** * A user specified by the given sender id thanks the author of an article specified by the given article id. * * @param articleId the given article id * @param senderId the given sender id * @throws ServiceException service exception */ public void thank(final String articleId, final String senderId) throws ServiceException { try { final JSONObject article = articleRepository.get(articleId); if (null == article) { return; } if (Article.ARTICLE_STATUS_C_INVALID == article.optInt(Article.ARTICLE_STATUS)) { return; } final JSONObject sender = userRepository.get(senderId); if (null == sender) { return; } if (UserExt.USER_STATUS_C_VALID != sender.optInt(UserExt.USER_STATUS)) { return; } final String receiverId = article.optString(Article.ARTICLE_AUTHOR_ID); final JSONObject receiver = userRepository.get(receiverId); if (null == receiver) { return; } if (UserExt.USER_STATUS_C_VALID != receiver.optInt(UserExt.USER_STATUS)) { return; } if (receiverId.equals(senderId)) { return; } if (rewardQueryService.isRewarded(senderId, articleId, Reward.TYPE_C_THANK_ARTICLE)) { return; } final String thankId = Ids.genTimeMillisId(); if (Article.ARTICLE_ANONYMOUS_C_PUBLIC == article.optInt(Article.ARTICLE_ANONYMOUS)) { final boolean succ = null != pointtransferMgmtService.transfer(senderId, receiverId, Pointtransfer.TRANSFER_TYPE_C_ARTICLE_THANK, Pointtransfer.TRANSFER_SUM_C_ARTICLE_THANK, thankId, System.currentTimeMillis()); if (!succ) { throw new ServiceException(); } } final JSONObject reward = new JSONObject(); reward.put(Keys.OBJECT_ID, thankId); reward.put(Reward.SENDER_ID, senderId); reward.put(Reward.DATA_ID, articleId); reward.put(Reward.TYPE, Reward.TYPE_C_THANK_ARTICLE); rewardMgmtService.addReward(reward); final JSONObject notification = new JSONObject(); notification.put(Notification.NOTIFICATION_USER_ID, receiverId); notification.put(Notification.NOTIFICATION_DATA_ID, thankId); notificationMgmtService.addArticleThankNotification(notification); livenessMgmtService.incLiveness(senderId, Liveness.LIVENESS_REWARD); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Thanks an article[id=" + articleId + "] failed", e); throw new ServiceException(e); } } /** * Sticks an article specified by the given article id. * * @param articleId the given article id * @throws ServiceException service exception */ public synchronized void stick(final String articleId) throws ServiceException { final Transaction transaction = articleRepository.beginTransaction(); try { final JSONObject article = articleRepository.get(articleId); if (null == article) { return; } final String authorId = article.optString(Article.ARTICLE_AUTHOR_ID); final JSONObject author = userRepository.get(authorId); final int balance = author.optInt(UserExt.USER_POINT); if (balance - Pointtransfer.TRANSFER_SUM_C_STICK_ARTICLE < 0) { throw new ServiceException(langPropsService.get("insufficientBalanceLabel")); } final Query query = new Query(). setFilter(new PropertyFilter(Article.ARTICLE_STICK, FilterOperator.GREATER_THAN, 0L)); final JSONArray articles = articleRepository.get(query).optJSONArray(Keys.RESULTS); if (articles.length() > 1) { final Set<String> ids = new HashSet<>(); for (int i = 0; i < articles.length(); i++) { ids.add(articles.optJSONObject(i).optString(Keys.OBJECT_ID)); } if (!ids.contains(articleId)) { throw new ServiceException(langPropsService.get("stickExistLabel")); } } article.put(Article.ARTICLE_STICK, System.currentTimeMillis()); articleRepository.update(articleId, article); transaction.commit(); final boolean succ = null != pointtransferMgmtService.transfer(article.optString(Article.ARTICLE_AUTHOR_ID), Pointtransfer.ID_C_SYS, Pointtransfer.TRANSFER_TYPE_C_STICK_ARTICLE, Pointtransfer.TRANSFER_SUM_C_STICK_ARTICLE, articleId, System.currentTimeMillis()); if (!succ) { throw new ServiceException(langPropsService.get("stickFailedLabel")); } } catch (final RepositoryException e) { if (transaction.isActive()) { transaction.rollback(); } LOGGER.log(Level.ERROR, "Sticks an article[id=" + articleId + "] failed", e); throw new ServiceException(langPropsService.get("stickFailedLabel")); } } /** * Admin sticks an article specified by the given article id. * * @param articleId the given article id * @throws ServiceException service exception */ @Transactional public synchronized void adminStick(final String articleId) throws ServiceException { try { final JSONObject article = articleRepository.get(articleId); if (null == article) { return; } article.put(Article.ARTICLE_STICK, Long.MAX_VALUE); articleRepository.update(articleId, article); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Admin sticks an article[id=" + articleId + "] failed", e); throw new ServiceException(langPropsService.get("stickFailedLabel")); } } /** * Admin cancels stick an article specified by the given article id. * * @param articleId the given article id * @throws ServiceException service exception */ @Transactional public synchronized void adminCancelStick(final String articleId) throws ServiceException { try { final JSONObject article = articleRepository.get(articleId); if (null == article) { return; } article.put(Article.ARTICLE_STICK, 0L); articleRepository.update(articleId, article); } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Admin cancel sticks an article[id=" + articleId + "] failed", e); throw new ServiceException(langPropsService.get("operationFailedLabel")); } } /** * Expires sticked articles. * * @throws ServiceException service exception */ @Transactional public void expireStick() throws ServiceException { try { final Query query = new Query(). setFilter(new PropertyFilter(Article.ARTICLE_STICK, FilterOperator.GREATER_THAN, 0L)); final JSONArray articles = articleRepository.get(query).optJSONArray(Keys.RESULTS); if (articles.length() < 1) { return; } final long stepTime = Symphonys.getLong("stickArticleTime"); final long now = System.currentTimeMillis(); for (int i = 0; i < articles.length(); i++) { final JSONObject article = articles.optJSONObject(i); final long stick = article.optLong(Article.ARTICLE_STICK); if (stick >= Long.MAX_VALUE) { continue; // Skip admin stick } final long expired = stick + stepTime; if (expired < now) { article.put(Article.ARTICLE_STICK, 0L); articleRepository.update(article.optString(Keys.OBJECT_ID), article); } } } catch (final RepositoryException e) { LOGGER.log(Level.ERROR, "Expires sticked articles failed", e); throw new ServiceException(); } } /** * Processes tags for article update. * <p> * <ul> * <li>Un-tags old article, decrements tag reference count</li> * <li>Removes old article-tag relations</li> * <li>Saves new article-tag relations with tag reference count</li> * </ul> * </p> * * @param oldArticle the specified old article * @param newArticle the specified new article * @param author the specified author * @throws Exception exception */ private synchronized void processTagsForArticleUpdate(final JSONObject oldArticle, final JSONObject newArticle, final JSONObject author) throws Exception { final String oldArticleId = oldArticle.getString(Keys.OBJECT_ID); final List<JSONObject> oldTags = tagRepository.getByArticleId(oldArticleId); String tagsString = newArticle.getString(Article.ARTICLE_TAGS); tagsString = Tag.formatTags(tagsString); boolean sandboxEnv = false; if (StringUtils.containsIgnoreCase(tagsString, Tag.TAG_TITLE_C_SANDBOX)) { tagsString = Tag.TAG_TITLE_C_SANDBOX; sandboxEnv = true; } String[] tagStrings = tagsString.split(","); final int articleType = newArticle.optInt(Article.ARTICLE_TYPE); if (!sandboxEnv && tagStrings.length < TAG_MAX_CNT && tagStrings.length < 3 && Article.ARTICLE_TYPE_C_DISCUSSION != articleType && Article.ARTICLE_TYPE_C_THOUGHT != articleType && !Tag.containsReservedTags(tagsString)) { final String content = newArticle.optString(Article.ARTICLE_TITLE) + " " + Jsoup.parse("<p>" + newArticle.optString(Article.ARTICLE_CONTENT) + "</p>").text(); final List<String> genTags = tagQueryService.generateTags(content, 1); if (!genTags.isEmpty()) { tagsString = tagsString + "," + StringUtils.join(genTags, ","); tagsString = Tag.formatTags(tagsString); tagsString = Tag.useHead(tagsString, TAG_MAX_CNT); } } if (StringUtils.isBlank(tagsString)) { tagsString = "B3log"; } tagsString = Tag.formatTags(tagsString); newArticle.put(Article.ARTICLE_TAGS, tagsString); tagStrings = tagsString.split(","); final List<JSONObject> newTags = new ArrayList<>(); for (final String tagString : tagStrings) { final String tagTitle = tagString.trim(); JSONObject newTag = tagRepository.getByTitle(tagTitle); if (null == newTag) { newTag = new JSONObject(); newTag.put(Tag.TAG_TITLE, tagTitle); } newTags.add(newTag); } final List<JSONObject> tagsDropped = new ArrayList<>(); final List<JSONObject> tagsNeedToAdd = new ArrayList<>(); for (final JSONObject newTag : newTags) { final String newTagTitle = newTag.getString(Tag.TAG_TITLE); if (!tagExists(newTagTitle, oldTags)) { LOGGER.log(Level.DEBUG, "Tag need to add[title={0}]", newTagTitle); tagsNeedToAdd.add(newTag); } } for (final JSONObject oldTag : oldTags) { final String oldTagTitle = oldTag.getString(Tag.TAG_TITLE); if (!tagExists(oldTagTitle, newTags)) { LOGGER.log(Level.DEBUG, "Tag dropped[title={0}]", oldTag); tagsDropped.add(oldTag); } } final int articleCmtCnt = oldArticle.getInt(Article.ARTICLE_COMMENT_CNT); for (final JSONObject tagDropped : tagsDropped) { final String tagId = tagDropped.getString(Keys.OBJECT_ID); int refCnt = tagDropped.getInt(Tag.TAG_REFERENCE_CNT) - 1; refCnt = refCnt < 0 ? 0 : refCnt; tagDropped.put(Tag.TAG_REFERENCE_CNT, refCnt); final int tagCmtCnt = tagDropped.getInt(Tag.TAG_COMMENT_CNT); tagDropped.put(Tag.TAG_COMMENT_CNT, tagCmtCnt - articleCmtCnt); tagDropped.put(Tag.TAG_RANDOM_DOUBLE, Math.random()); tagRepository.update(tagId, tagDropped); } final String[] tagIdsDropped = new String[tagsDropped.size()]; for (int i = 0; i < tagIdsDropped.length; i++) { final JSONObject tag = tagsDropped.get(i); final String id = tag.getString(Keys.OBJECT_ID); tagIdsDropped[i] = id; } if (0 != tagIdsDropped.length) { removeTagArticleRelations(oldArticleId, tagIdsDropped); removeUserTagRelations(oldArticle.optString(Article.ARTICLE_AUTHOR_ID), Tag.TAG_TYPE_C_ARTICLE, tagIdsDropped); } tagStrings = new String[tagsNeedToAdd.size()]; for (int i = 0; i < tagStrings.length; i++) { final JSONObject tag = tagsNeedToAdd.get(i); final String tagTitle = tag.getString(Tag.TAG_TITLE); tagStrings[i] = tagTitle; } newArticle.put(Article.ARTICLE_COMMENT_CNT, articleCmtCnt); tag(tagStrings, newArticle, author); } /** * Removes tag-article relations by the specified article id and tag ids of the relations to be removed. * <p> * Removes all relations if not specified the tag ids. * </p> * * @param articleId the specified article id * @param tagIds the specified tag ids of the relations to be removed * @throws JSONException json exception * @throws RepositoryException repository exception */ private void removeTagArticleRelations(final String articleId, final String... tagIds) throws JSONException, RepositoryException { final List<String> tagIdList = Arrays.asList(tagIds); final List<JSONObject> tagArticleRelations = tagArticleRepository.getByArticleId(articleId); for (int i = 0; i < tagArticleRelations.size(); i++) { final JSONObject tagArticleRelation = tagArticleRelations.get(i); String relationId; if (tagIdList.isEmpty()) { // Removes all if un-specified relationId = tagArticleRelation.getString(Keys.OBJECT_ID); tagArticleRepository.remove(relationId); } else if (tagIdList.contains(tagArticleRelation.getString(Tag.TAG + "_" + Keys.OBJECT_ID))) { relationId = tagArticleRelation.getString(Keys.OBJECT_ID); tagArticleRepository.remove(relationId); } } } /** * Removes User-Tag relations by the specified user id, type and tag ids of the relations to be removed. * * @param userId the specified article id * @param type the specified type * @param tagIds the specified tag ids of the relations to be removed * @throws RepositoryException repository exception */ private void removeUserTagRelations(final String userId, final int type, final String... tagIds) throws RepositoryException { for (final String tagId : tagIds) { userTagRepository.removeByUserIdAndTagId(userId, tagId, type); } } /** * Tags the specified article with the specified tag titles. * * @param tagTitles the specified (new) tag titles * @param article the specified article * @param author the specified author * @throws RepositoryException repository exception */ private synchronized void tag(final String[] tagTitles, final JSONObject article, final JSONObject author) throws RepositoryException { String articleTags = article.optString(Article.ARTICLE_TAGS); for (final String t : tagTitles) { final String tagTitle = t.trim(); JSONObject tag = tagRepository.getByTitle(tagTitle); String tagId; int userTagType; final int articleCmtCnt = article.optInt(Article.ARTICLE_COMMENT_CNT); if (null == tag) { LOGGER.log(Level.TRACE, "Found a new tag[title={0}] in article[title={1}]", new Object[]{tagTitle, article.optString(Article.ARTICLE_TITLE)}); tag = new JSONObject(); tag.put(Tag.TAG_TITLE, tagTitle); String tagURI = tagTitle; try { tagURI = URLEncoder.encode(tagTitle, "UTF-8"); } catch (final UnsupportedEncodingException e) { LOGGER.log(Level.ERROR, "Encode tag title [" + tagTitle + "] error", e); } tag.put(Tag.TAG_URI, tagURI); tag.put(Tag.TAG_CSS, ""); tag.put(Tag.TAG_REFERENCE_CNT, 1); tag.put(Tag.TAG_COMMENT_CNT, articleCmtCnt); tag.put(Tag.TAG_FOLLOWER_CNT, 0); tag.put(Tag.TAG_LINK_CNT, 0); tag.put(Tag.TAG_DESCRIPTION, ""); tag.put(Tag.TAG_ICON_PATH, ""); tag.put(Tag.TAG_STATUS, 0); tag.put(Tag.TAG_GOOD_CNT, 0); tag.put(Tag.TAG_BAD_CNT, 0); tag.put(Tag.TAG_SEO_TITLE, tagTitle); tag.put(Tag.TAG_SEO_KEYWORDS, tagTitle); tag.put(Tag.TAG_SEO_DESC, ""); tag.put(Tag.TAG_RANDOM_DOUBLE, Math.random()); tagId = tagRepository.add(tag); tag.put(Keys.OBJECT_ID, tagId); userTagType = Tag.TAG_TYPE_C_CREATOR; final JSONObject tagCntOption = optionRepository.get(Option.ID_C_STATISTIC_TAG_COUNT); final int tagCnt = tagCntOption.optInt(Option.OPTION_VALUE); tagCntOption.put(Option.OPTION_VALUE, tagCnt + 1); optionRepository.update(Option.ID_C_STATISTIC_TAG_COUNT, tagCntOption); author.put(UserExt.USER_TAG_COUNT, author.optInt(UserExt.USER_TAG_COUNT) + 1); } else { tagId = tag.optString(Keys.OBJECT_ID); LOGGER.log(Level.TRACE, "Found a existing tag[title={0}, id={1}] in article[title={2}]", tag.optString(Tag.TAG_TITLE), tag.optString(Keys.OBJECT_ID), article.optString(Article.ARTICLE_TITLE)); final JSONObject tagTmp = new JSONObject(); tagTmp.put(Keys.OBJECT_ID, tagId); final String title = tag.optString(Tag.TAG_TITLE); tagTmp.put(Tag.TAG_TITLE, title); tagTmp.put(Tag.TAG_COMMENT_CNT, tag.optInt(Tag.TAG_COMMENT_CNT) + articleCmtCnt); tagTmp.put(Tag.TAG_STATUS, tag.optInt(Tag.TAG_STATUS)); tagTmp.put(Tag.TAG_REFERENCE_CNT, tag.optInt(Tag.TAG_REFERENCE_CNT) + 1); tagTmp.put(Tag.TAG_FOLLOWER_CNT, tag.optInt(Tag.TAG_FOLLOWER_CNT)); tagTmp.put(Tag.TAG_LINK_CNT, tag.optInt(Tag.TAG_LINK_CNT)); tagTmp.put(Tag.TAG_DESCRIPTION, tag.optString(Tag.TAG_DESCRIPTION)); tagTmp.put(Tag.TAG_ICON_PATH, tag.optString(Tag.TAG_ICON_PATH)); tagTmp.put(Tag.TAG_GOOD_CNT, tag.optInt(Tag.TAG_GOOD_CNT)); tagTmp.put(Tag.TAG_BAD_CNT, tag.optInt(Tag.TAG_BAD_CNT)); tagTmp.put(Tag.TAG_SEO_DESC, tag.optString(Tag.TAG_SEO_DESC)); tagTmp.put(Tag.TAG_SEO_KEYWORDS, tag.optString(Tag.TAG_SEO_KEYWORDS)); tagTmp.put(Tag.TAG_SEO_TITLE, tag.optString(Tag.TAG_SEO_TITLE)); tagTmp.put(Tag.TAG_RANDOM_DOUBLE, Math.random()); tagTmp.put(Tag.TAG_URI, tag.optString(Tag.TAG_URI)); tagTmp.put(Tag.TAG_CSS, tag.optString(Tag.TAG_CSS)); tagRepository.update(tagId, tagTmp); userTagType = Tag.TAG_TYPE_C_ARTICLE; } // Tag-Article relation final JSONObject tagArticleRelation = new JSONObject(); tagArticleRelation.put(Tag.TAG + "_" + Keys.OBJECT_ID, tagId); tagArticleRelation.put(Article.ARTICLE + "_" + Keys.OBJECT_ID, article.optString(Keys.OBJECT_ID)); tagArticleRelation.put(Article.ARTICLE_LATEST_CMT_TIME, article.optLong(Article.ARTICLE_LATEST_CMT_TIME)); tagArticleRelation.put(Article.ARTICLE_COMMENT_CNT, article.optInt(Article.ARTICLE_COMMENT_CNT)); tagArticleRelation.put(Article.REDDIT_SCORE, article.optDouble(Article.REDDIT_SCORE, 0D)); tagArticleRelation.put(Article.ARTICLE_PERFECT, article.optInt(Article.ARTICLE_PERFECT)); tagArticleRepository.add(tagArticleRelation); final String authorId = article.optString(Article.ARTICLE_AUTHOR_ID); // User-Tag relation if (Tag.TAG_TYPE_C_ARTICLE == userTagType) { userTagRepository.removeByUserIdAndTagId(authorId, tagId, Tag.TAG_TYPE_C_ARTICLE); } final JSONObject userTagRelation = new JSONObject(); userTagRelation.put(Tag.TAG + '_' + Keys.OBJECT_ID, tagId); if (Article.ARTICLE_ANONYMOUS_C_ANONYMOUS == article.optInt(Article.ARTICLE_ANONYMOUS)) { userTagRelation.put(User.USER + '_' + Keys.OBJECT_ID, "0"); } else { userTagRelation.put(User.USER + '_' + Keys.OBJECT_ID, authorId); } userTagRelation.put(Common.TYPE, userTagType); userTagRepository.add(userTagRelation); } final String[] tags = articleTags.split(","); final StringBuilder builder = new StringBuilder(); for (final String tagTitle : tags) { final JSONObject tag = tagRepository.getByTitle(tagTitle); builder.append(tag.optString(Tag.TAG_TITLE)).append(","); } if (builder.length() > 0) { builder.deleteCharAt(builder.length() - 1); } article.put(Article.ARTICLE_TAGS, builder.toString()); } /** * Filters the specified article tags. * * @param articleTags the specified article tags * @return filtered tags string */ public String filterReservedTags(final String articleTags) { final String[] tags = articleTags.split(","); final StringBuilder retBuilder = new StringBuilder(); for (final String tag : tags) { if (!ArrayUtils.contains(Symphonys.RESERVED_TAGS, tag)) { retBuilder.append(tag).append(","); } } if (retBuilder.length() > 0) { retBuilder.deleteCharAt(retBuilder.length() - 1); } return retBuilder.toString(); } /** * Adds an article with the specified request json object. * <p> * <b>Note</b>: This method just for admin console. * </p> * * @param requestJSONObject the specified request json object, for example, * "articleTitle": "", * "articleTags": "", * "articleContent": "", * "articleRewardContent": "", * "articleRewardPoint": int, * "userName": "", * "time": long * , see {@link Article} for more details * @return generated article id * @throws ServiceException service exception */ public synchronized String addArticleByAdmin(final JSONObject requestJSONObject) throws ServiceException { JSONObject author; try { author = userRepository.getByName(requestJSONObject.optString(User.USER_NAME)); if (null == author) { throw new ServiceException(langPropsService.get("notFoundUserLabel")); } } catch (final RepositoryException e) { LOGGER.log(Level.DEBUG, "Admin adds article failed", e); throw new ServiceException(e.getMessage()); } final Transaction transaction = articleRepository.beginTransaction(); try { final long time = requestJSONObject.optLong(Common.TIME); final String ret = String.valueOf(time); final JSONObject article = new JSONObject(); article.put(Keys.OBJECT_ID, ret); article.put(Article.ARTICLE_CLIENT_ARTICLE_ID, ret); article.put(Article.ARTICLE_CLIENT_ARTICLE_PERMALINK, ""); article.put(Article.ARTICLE_AUTHOR_ID, author.optString(Keys.OBJECT_ID)); article.put(Article.ARTICLE_TITLE, Emotions.toAliases(requestJSONObject.optString(Article.ARTICLE_TITLE))); article.put(Article.ARTICLE_CONTENT, Emotions.toAliases(requestJSONObject.optString(Article.ARTICLE_CONTENT))); article.put(Article.ARTICLE_REWARD_CONTENT, requestJSONObject.optString(Article.ARTICLE_REWARD_CONTENT)); article.put(Article.ARTICLE_EDITOR_TYPE, 0); article.put(Article.ARTICLE_SYNC_TO_CLIENT, false); article.put(Article.ARTICLE_COMMENT_CNT, 0); article.put(Article.ARTICLE_VIEW_CNT, 0); article.put(Article.ARTICLE_GOOD_CNT, 0); article.put(Article.ARTICLE_BAD_CNT, 0); article.put(Article.ARTICLE_COLLECT_CNT, 0); article.put(Article.ARTICLE_WATCH_CNT, 0); article.put(Article.ARTICLE_COMMENTABLE, true); article.put(Article.ARTICLE_CREATE_TIME, time); article.put(Article.ARTICLE_UPDATE_TIME, time); article.put(Article.ARTICLE_LATEST_CMT_TIME, 0); article.put(Article.ARTICLE_LATEST_CMTER_NAME, ""); article.put(Article.ARTICLE_PERMALINK, "/article/" + ret); article.put(Article.ARTICLE_RANDOM_DOUBLE, Math.random()); article.put(Article.REDDIT_SCORE, 0); article.put(Article.ARTICLE_STATUS, Article.ARTICLE_STATUS_C_VALID); article.put(Article.ARTICLE_TYPE, Article.ARTICLE_TYPE_C_NORMAL); article.put(Article.ARTICLE_REWARD_POINT, requestJSONObject.optInt(Article.ARTICLE_REWARD_POINT)); article.put(Article.ARTICLE_CITY, ""); String articleTags = requestJSONObject.optString(Article.ARTICLE_TAGS); articleTags = Tag.formatTags(articleTags); boolean sandboxEnv = false; if (StringUtils.containsIgnoreCase(articleTags, Tag.TAG_TITLE_C_SANDBOX)) { articleTags = Tag.TAG_TITLE_C_SANDBOX; sandboxEnv = true; } String[] tagTitles = articleTags.split(","); if (!sandboxEnv && tagTitles.length < TAG_MAX_CNT && tagTitles.length < 3 && !Tag.containsReservedTags(articleTags)) { final String content = article.optString(Article.ARTICLE_TITLE) + " " + Jsoup.parse("<p>" + article.optString(Article.ARTICLE_CONTENT) + "</p>").text(); final List<String> genTags = tagQueryService.generateTags(content, TAG_MAX_CNT); if (!genTags.isEmpty()) { articleTags = articleTags + "," + StringUtils.join(genTags, ","); articleTags = Tag.formatTags(articleTags); articleTags = Tag.useHead(articleTags, TAG_MAX_CNT); } } if (StringUtils.isBlank(articleTags)) { articleTags = "B3log"; } articleTags = Tag.formatTags(articleTags); article.put(Article.ARTICLE_TAGS, articleTags); tagTitles = articleTags.split(","); tag(tagTitles, article, author); final String ip = requestJSONObject.optString(Article.ARTICLE_IP); article.put(Article.ARTICLE_IP, ip); String ua = requestJSONObject.optString(Article.ARTICLE_UA); if (StringUtils.length(ua) > Common.MAX_LENGTH_UA) { ua = StringUtils.substring(ua, 0, Common.MAX_LENGTH_UA); } article.put(Article.ARTICLE_UA, ua); article.put(Article.ARTICLE_STICK, 0L); article.put(Article.ARTICLE_ANONYMOUS, Article.ARTICLE_ANONYMOUS_C_PUBLIC); article.put(Article.ARTICLE_PERFECT, Article.ARTICLE_PERFECT_C_NOT_PERFECT); article.put(Article.ARTICLE_ANONYMOUS_VIEW, Article.ARTICLE_ANONYMOUS_VIEW_C_USE_GLOBAL); article.put(Article.ARTICLE_AUDIO_URL, ""); final JSONObject articleCntOption = optionRepository.get(Option.ID_C_STATISTIC_ARTICLE_COUNT); final int articleCnt = articleCntOption.optInt(Option.OPTION_VALUE); articleCntOption.put(Option.OPTION_VALUE, articleCnt + 1); optionRepository.update(Option.ID_C_STATISTIC_ARTICLE_COUNT, articleCntOption); author.put(UserExt.USER_ARTICLE_COUNT, author.optInt(UserExt.USER_ARTICLE_COUNT) + 1); author.put(UserExt.USER_LATEST_ARTICLE_TIME, time); // Updates user article count (and new tag count), latest article time userRepository.update(author.optString(Keys.OBJECT_ID), author); final String articleId = articleRepository.add(article); // Revision final JSONObject revision = new JSONObject(); revision.put(Revision.REVISION_AUTHOR_ID, author.optString(Keys.OBJECT_ID)); final JSONObject revisionData = new JSONObject(); revisionData.put(Article.ARTICLE_TITLE, article.optString(Article.ARTICLE_TITLE)); revisionData.put(Article.ARTICLE_CONTENT, article.optString(Article.ARTICLE_CONTENT)); revision.put(Revision.REVISION_DATA, revisionData.toString()); revision.put(Revision.REVISION_DATA_ID, articleId); revision.put(Revision.REVISION_DATA_TYPE, Revision.DATA_TYPE_C_ARTICLE); revisionRepository.add(revision); transaction.commit(); // Grows the tag graph tagMgmtService.relateTags(article.optString(Article.ARTICLE_TAGS)); // Event final JSONObject eventData = new JSONObject(); eventData.put(Common.FROM_CLIENT, false); eventData.put(Article.ARTICLE, article); try { eventManager.fireEventAsynchronously(new Event<>(EventTypes.ADD_ARTICLE, eventData)); } catch (final EventException e) { LOGGER.log(Level.ERROR, e.getMessage(), e); } return ret; } catch (final RepositoryException e) { if (transaction.isActive()) { transaction.rollback(); } LOGGER.log(Level.ERROR, "Admin adds an article failed", e); throw new ServiceException(e.getMessage()); } } }
package org.commcare.cases.util; import org.commcare.cases.query.*; import org.commcare.cases.query.IndexedSetMemberLookup; import org.commcare.cases.query.IndexedValueLookup; import org.commcare.cases.query.PredicateProfile; import org.commcare.cases.query.handlers.BasicStorageBackedCachingQueryHandler; import org.commcare.modern.engine.cases.RecordSetResultCache; import org.commcare.modern.util.PerformanceTuningUtil; import org.javarosa.core.model.condition.EvaluationContext; import org.javarosa.core.model.instance.AbstractTreeElement; import org.javarosa.core.model.instance.TreeReference; import org.javarosa.core.model.trace.EvaluationTrace; import org.javarosa.core.services.storage.IStorageUtilityIndexed; import org.javarosa.core.util.DataUtil; import org.javarosa.xpath.expr.FunctionUtils; import org.javarosa.xpath.expr.XPathEqExpr; import org.javarosa.xpath.expr.XPathExpression; import org.javarosa.xpath.expr.XPathPathExpr; import org.javarosa.xpath.expr.XPathSelectedFunc; import java.util.Collection; import java.util.Enumeration; import java.util.Hashtable; import java.util.LinkedHashSet; import java.util.List; import java.util.Vector; /** * @author ctsims */ public abstract class StorageBackedTreeRoot<T extends AbstractTreeElement> implements AbstractTreeElement<T> { protected QueryPlanner queryPlanner; protected BasicStorageBackedCachingQueryHandler defaultCacher; protected final Hashtable<Integer, Integer> objectIdMapping = new Hashtable<>(); protected abstract String getChildHintName(); protected abstract Hashtable<XPathPathExpr, String> getStorageIndexMap(); protected abstract IStorageUtilityIndexed<?> getStorage(); protected abstract void initStorageCache(); protected String translateFilterExpr(XPathPathExpr expressionTemplate, XPathPathExpr matchingExpr, Hashtable<XPathPathExpr, String> indices) { return indices.get(expressionTemplate); } @Override public Collection<TreeReference> tryBatchChildFetch(String name, int mult, Vector<XPathExpression> predicates, EvaluationContext evalContext) { //Restrict what we'll handle for now. All we want to deal with is predicate expressions on case blocks if (!name.equals(getChildHintName()) || mult != TreeReference.INDEX_UNBOUND || predicates == null) { return null; } Hashtable<XPathPathExpr, String> indices = getStorageIndexMap(); Vector<PredicateProfile> profiles = new Vector<>(); QueryContext queryContext = evalContext.getCurrentQueryContext(); //First, attempt to use 'preferred' optimizations detectable by the query planner //using advanced inspection of the predicates Vector<PredicateProfile> preferredProfiles = new Vector<>(); preferredProfiles.addAll(getQueryPlanner().collectPredicateProfiles( predicates, queryContext, evalContext)); //For now we are going to skip looking deeper if we trigger //any of the planned optimizations if(preferredProfiles.size() > 0) { Collection<TreeReference> response = processPredicatesAndPrepareResponse(preferredProfiles, queryContext, predicates); //For now if there are any results we should press forward. We don't have a meaningful //way to combine these results with native optimizations if(response != null) { return response; } } //Otherwise, identify predicates that we _might_ be able to evaluate more efficiently //based on normal keyed behavior collectNativePredicateProfiles(predicates, indices, evalContext, profiles); return processPredicatesAndPrepareResponse(profiles, queryContext, predicates); } private Collection<TreeReference> processPredicatesAndPrepareResponse(Vector<PredicateProfile> profiles, QueryContext queryContext, Vector<XPathExpression> predicates) { //Now go through each profile and see if we can match / process any of them. If not, we // will return null and move on Vector<Integer> toRemove = new Vector<>(); Collection<Integer> selectedElements = processPredicates(toRemove, profiles, queryContext); //if we weren't able to evaluate any predicates, signal that. if (selectedElements == null) { return null; } //otherwise, remove all of the predicates we've already evaluated for (int i = toRemove.size() - 1; i >= 0; i predicates.removeElementAt(toRemove.elementAt(i)); } return buildReferencesFromFetchResults(selectedElements); } private void collectNativePredicateProfiles(Vector<XPathExpression> predicates, Hashtable<XPathPathExpr, String> indices, EvaluationContext evalContext, Vector<PredicateProfile> optimizations) { predicate: for (XPathExpression xpe : predicates) { //what we want here is a static evaluation of the expression to see if it consists of evaluating //something we index with something static. if (xpe instanceof XPathEqExpr && ((XPathEqExpr)xpe).op == XPathEqExpr.EQ) { XPathExpression left = ((XPathEqExpr)xpe).a; if (left instanceof XPathPathExpr) { for (Enumeration en = indices.keys(); en.hasMoreElements(); ) { XPathPathExpr expr = (XPathPathExpr)en.nextElement(); if (expr.matches(left)) { String filterIndex = translateFilterExpr(expr, (XPathPathExpr)left, indices); //TODO: We need a way to determine that this value does not also depend on anything in the current context, not //sure the best way to do that....? Maybe tell the evaluation context to skip out here if it detects a request //to resolve in a certain area? Object o = FunctionUtils.unpack(((XPathEqExpr)xpe).b.eval(evalContext)); optimizations.addElement(new IndexedValueLookup(filterIndex, o)); continue predicate; } } } } else if (xpe instanceof XPathSelectedFunc) { XPathExpression lookupArg = ((XPathSelectedFunc)xpe).args[1]; if (lookupArg instanceof XPathPathExpr) { for (Enumeration en = indices.keys(); en.hasMoreElements(); ) { XPathPathExpr expr = (XPathPathExpr)en.nextElement(); if (expr.matches(lookupArg)) { String filterIndex = translateFilterExpr(expr, (XPathPathExpr)lookupArg, indices); //TODO: We need a way to determine that this value does not also depend on anything in the current context, not //sure the best way to do that....? Maybe tell the evaluation context to skip out here if it detects a request //to resolve in a certain area? Object o = FunctionUtils.unpack(((XPathSelectedFunc)xpe).args[0].eval(evalContext)); optimizations.addElement(new IndexedSetMemberLookup(filterIndex, o)); continue predicate; } } } } //There's only one case where we want to keep moving along, and we would have triggered it if it were going to happen, //so otherwise, just get outta here. break; } } protected QueryPlanner getQueryPlanner() { if(queryPlanner == null) { queryPlanner = new QueryPlanner(); initBasicQueryHandlers(queryPlanner); } return queryPlanner; } protected void initBasicQueryHandlers(QueryPlanner queryPlanner) { defaultCacher = new BasicStorageBackedCachingQueryHandler(); //TODO: Move the actual indexed query optimization used in this //method into its own (or a matching) cache method queryPlanner.addQueryHandler(defaultCacher); } private Collection<Integer> processPredicates(Vector<Integer> toRemove, Vector<PredicateProfile> profiles, QueryContext currentQueryContext) { Collection<Integer> selectedElements = null; IStorageUtilityIndexed<?> storage = getStorage(); int predicatesProcessed = 0; while (profiles.size() > 0) { int startCount = profiles.size(); List<Integer> plannedQueryResults = this.getQueryPlanner().attemptProfiledQuery(profiles, currentQueryContext); if (plannedQueryResults != null) { // merge with any other sets of cases if (selectedElements == null) { selectedElements = plannedQueryResults; } else { selectedElements = DataUtil.intersection(selectedElements, plannedQueryResults); } } else { Collection<Integer> cases = null; try { //Get all of the cases that meet this criteria cases = this.getNextIndexMatch(profiles, storage, currentQueryContext); } catch (IllegalArgumentException IAE) { // Encountered a new index type break; } // merge with any other sets of cases if (selectedElements == null) { selectedElements = cases; } else { selectedElements = DataUtil.intersection(selectedElements, cases); } } if(selectedElements != null && selectedElements.size() == 0) { //There's nothing left! We can completely wipe the remaining profiles profiles.clear(); } int numPredicatesRemoved = startCount - profiles.size(); for (int i = 0; i < numPredicatesRemoved; ++i) { //Note that this predicate is evaluated and doesn't need to be evaluated in the future. toRemove.addElement(DataUtil.integer(predicatesProcessed)); predicatesProcessed++; } currentQueryContext = currentQueryContext.testForInlineScopeEscalation(selectedElements.size()); } return selectedElements; } private Collection<TreeReference> buildReferencesFromFetchResults(Collection<Integer> selectedElements) { TreeReference base = this.getRef(); initStorageCache(); Vector<TreeReference> filtered = new Vector<>(); for (Integer i : selectedElements) { //this takes _waaaaay_ too long, we need to refactor this TreeReference ref = base.clone(); int realIndex = objectIdMapping.get(i); ref.add(this.getChildHintName(), realIndex); filtered.addElement(ref); } return filtered; } protected Collection<Integer> getNextIndexMatch(Vector<PredicateProfile> profiles, IStorageUtilityIndexed<?> storage, QueryContext currentQueryContext) throws IllegalArgumentException { if(!(profiles.elementAt(0) instanceof IndexedValueLookup)) { throw new IllegalArgumentException("No optimization path found for optimization type"); } IndexedValueLookup op = (IndexedValueLookup)profiles.elementAt(0); EvaluationTrace trace = new EvaluationTrace("Model Index[" + op.key + "] Lookup"); //Get matches if it works List<Integer> ids = storage.getIDsForValue(op.key, op.value); boolean triggeredRecordSetCache = false; if(getStorageCacheName() != null && ids.size() > 50 && ids.size() < PerformanceTuningUtil.getMaxPrefetchCaseBlock()) { RecordSetResultCache cue = currentQueryContext.getQueryCache(RecordSetResultCache.class); String bulkRecordSetKey = String.format("%s|%s", op.key, op.value); cue.reportBulkRecordSet(bulkRecordSetKey, getStorageCacheName(), new LinkedHashSet(ids)); triggeredRecordSetCache = true; } trace.setOutcome("results: " + ids.size()); if (currentQueryContext != null) { currentQueryContext.reportTrace(trace); } //Don't cache anything that's recorded as a record set, since it will prevent that set //from being cued into future contexts (storing the defaultCacher outside of the //QueryContext gives it some bad semantics that should be reviewed...) if(defaultCacher != null && !triggeredRecordSetCache) { defaultCacher.cacheResult(op.key, op.value, ids); } //If we processed this, pop it off the queue profiles.removeElementAt(0); return ids; } /** * @return A string which will provide a unique name for the storage that is used in this tree * root. Used to differentiate the record ID's retrieved during operations on this root in * internal caches */ public abstract String getStorageCacheName(); }
package org.daisy.pipeline.gui.databridge; import java.util.HashMap; import java.util.List; import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import org.daisy.common.xproc.XProcOptionInfo; import org.daisy.common.xproc.XProcPortInfo; import org.daisy.pipeline.datatypes.DatatypeRegistry; import org.daisy.pipeline.datatypes.DatatypeService; import org.daisy.pipeline.datatypes.UrlBasedDatatypeService; import org.daisy.pipeline.script.XProcOptionMetadata; import org.daisy.pipeline.script.XProcOptionMetadata.Output; import org.daisy.pipeline.script.XProcPortMetadata; public class ScriptField { public enum FieldType {INPUT, OUTPUT, OPTION}; public static class DataType { private DataType() {} public static DataType FILE = new DataType(); public static DataType DIRECTORY = new DataType(); public static DataType STRING = new DataType(); public static DataType BOOLEAN = new DataType(); public static DataType INTEGER = new DataType(); public static class Enumeration extends DataType { private final List<String> values; private Enumeration(List<String> values) { this.values = ImmutableList.copyOf(values); } public List<String> getValues() { return values; } } } public static HashMap<String, DataType> dataTypeMap; static { dataTypeMap = new HashMap<String, DataType>(); dataTypeMap.put("anyFileURI", DataType.FILE); dataTypeMap.put("anyDirURI", DataType.DIRECTORY); dataTypeMap.put("boolean", DataType.BOOLEAN); dataTypeMap.put("string", DataType.STRING); dataTypeMap.put("integer", DataType.INTEGER); dataTypeMap.put("xs:boolean", DataType.BOOLEAN); dataTypeMap.put("xs:string", DataType.STRING); dataTypeMap.put("xs:integer", DataType.INTEGER); } private String name; private String niceName; private String description; private FieldType fieldType; /* input, output, or option */ private String mediaType; /* @media-type attribute of script XML; e.g. "application/xhtml+xml" */ private boolean isRequired; private boolean isSequence; private DataType dataType; /* @type attribute of script XML; e.g. anyFileURI */ private boolean isOrdered; /* ONLY for options */ private boolean isPrimary; /* ONLY for input/output */ private boolean isTemp; /* ONLY for options */ private boolean isResult; /* ONLY for options */ private String defaultValue; /*ONLY for options */ public ScriptField(XProcPortInfo portInfo, XProcPortMetadata metadata, FieldType fieldType) { name = portInfo.getName(); description = metadata.getDescription(); niceName = metadata.getNiceName(); isSequence = portInfo.isSequence(); mediaType = metadata.getMediaType(); this.fieldType = fieldType; isRequired = metadata.isRequired(); isOrdered = false; dataType = DataType.FILE; isPrimary = portInfo.isPrimary(); isTemp = false; isResult = false; defaultValue = ""; } public ScriptField(XProcOptionInfo optionInfo, XProcOptionMetadata metadata, DatatypeRegistry datatypeRegistry) { name = optionInfo.getName().toString(); description = metadata.getDescription(); niceName = metadata.getNiceName(); isSequence = metadata.isSequence(); dataType = getDataType(metadata.getType(), datatypeRegistry); mediaType = metadata.getMediaType(); fieldType = FieldType.OPTION; isRequired = optionInfo.isRequired(); isOrdered = metadata.isOrdered(); isPrimary = false; isResult = metadata.getOutput() == Output.RESULT; isTemp = metadata.getOutput() == Output.TEMP; defaultValue = optionInfo.getSelect(); // trim single quotes from start/end of string if (defaultValue != null && defaultValue.isEmpty() == false) { defaultValue = defaultValue.replaceAll("^'|'$", ""); } } public String getName() { return name; } public String getNiceName() { return niceName; } public String getDescription() { return description; } public FieldType getFieldType() { return fieldType; } public String getMediaType() { return mediaType; } public boolean isRequired() { return isRequired; } public boolean isSequence() { return isSequence; } public DataType getDataType() { return dataType; } public boolean isOrdered() { return isOrdered; } public boolean isPrimary() { return isPrimary; } public boolean isTemp() { return isTemp; } public boolean isResult() { return isResult; } public String getDefaultValue() { return defaultValue; } private DataType getDataType(String dataType, DatatypeRegistry datatypeRegistry) { if (dataTypeMap.containsKey(dataType)) { return dataTypeMap.get(dataType); } else if (dataType != null) { //System.out.println(" Optional<DatatypeService> o = datatypeRegistry.getDatatype(dataType); if (o.isPresent()) { if (o.get() instanceof UrlBasedDatatypeService) { UrlBasedDatatypeService service = (UrlBasedDatatypeService)o.get(); if (service.isEnumeration()) { return new DataType.Enumeration(service.getEnumerationValues()); } } } } return DataType.STRING; // default to string } }
package org.dasein.cloud.azure.compute.disk; import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; import org.dasein.cloud.*; import org.dasein.cloud.azure.Azure; import org.dasein.cloud.azure.AzureConfigException; import org.dasein.cloud.azure.AzureMethod; import org.dasein.cloud.azure.compute.vm.AzureVM; import org.dasein.cloud.compute.AbstractVolumeSupport; import org.dasein.cloud.compute.Platform; import org.dasein.cloud.compute.VirtualMachine; import org.dasein.cloud.compute.Volume; import org.dasein.cloud.compute.VolumeCreateOptions; import org.dasein.cloud.compute.VolumeFilterOptions; import org.dasein.cloud.compute.VolumeFormat; import org.dasein.cloud.compute.VolumeProduct; import org.dasein.cloud.compute.VolumeState; import org.dasein.cloud.compute.VolumeSupport; import org.dasein.cloud.compute.VolumeType; import org.dasein.cloud.dc.DataCenter; import org.dasein.cloud.identity.ServiceAction; import org.dasein.util.uom.storage.Gigabyte; import org.dasein.util.uom.storage.Storage; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.servlet.http.HttpServletResponse; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collections; import java.util.Locale; public class AzureDisk extends AbstractVolumeSupport { static private final Logger logger = Azure.getLogger(AzureDisk.class); static private final String DISK_SERVICES = "/services/disks"; static private final String HOSTED_SERVICES = "/services/hostedservices"; private Azure provider; public AzureDisk(Azure provider) { super(provider); this.provider = provider; } @Override public void attach(@Nonnull String volumeId, @Nonnull String toServer, @Nonnull String device) throws InternalException, CloudException { if( logger.isTraceEnabled() ) { logger.trace("ENTER: " + AzureDisk.class.getName() + ".attach(" + volumeId + "," + toServer+ "," + device+ ")"); } try { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new AzureConfigException("No context was specified for this request"); } if (device != null) { if (device.startsWith("/dev/")) { device = device.substring(5); } } VirtualMachine server = provider.getComputeServices().getVirtualMachineSupport().getVirtualMachine(toServer); Volume disk ; StringBuilder xml = new StringBuilder(); if(volumeId != null){ disk = getVolume(volumeId); if(disk == null ){ throw new InternalException("Can not find the source snapshot !"); } xml.append("<DataVirtualHardDisk xmlns=\"http: xml.append("<HostCaching>ReadWrite</HostCaching>"); xml.append("<DiskName>" + disk.getName() + "</DiskName>"); if(device != null && isWithinDeviceList(device)){ xml.append("<Lun>" + device + "</Lun>"); } xml.append("<LogicalDiskSizeInGB>" + disk.getSizeInGigabytes() + "</LogicalDiskSizeInGB>"); xml.append("<MediaLink>" + disk.getMediaLink()+"</MediaLink>"); xml.append("</DataVirtualHardDisk>"); }else{ //throw new InternalException("volumeId is null !"); //dmayne: assume we are attaching a new empty disk? xml.append("<DataVirtualHardDisk xmlns=\"http: xml.append("<HostCaching>ReadWrite</HostCaching>"); if(device != null && isWithinDeviceList(device)){ xml.append("<Lun>" + device + "</Lun>"); } //todo get actual disk size xml.append("<LogicalDiskSizeInGB>").append("1").append("</LogicalDiskSizeInGB>"); xml.append("<MediaLink>").append(provider.getStorageEndpoint()).append("vhds/").append(server.getTag("roleName")).append(System.currentTimeMillis()%10000).append(".vhd</MediaLink>"); xml.append("</DataVirtualHardDisk>"); } String resourceDir = HOSTED_SERVICES + "/" +server.getTag("serviceName") + "/deployments" + "/" + server.getTag("deploymentName") + "/roles"+"/" + server.getTag("roleName") + "/DataDisks"; AzureMethod method = new AzureMethod(provider); if( logger.isDebugEnabled() ) { try { method.parseResponse(xml.toString(), false); } catch( Exception e ) { logger.warn("Unable to parse outgoing XML locally: " + e.getMessage()); logger.warn("XML:"); logger.warn(xml.toString()); } } method.post(ctx.getAccountNumber(), resourceDir, xml.toString()); } finally { if( logger.isTraceEnabled() ) { logger.trace("EXIT: " + AzureDisk.class.getName() + ".attach()"); } } } @Override public @Nonnull String createVolume(@Nonnull VolumeCreateOptions options) throws InternalException, CloudException { throw new OperationNotSupportedException("Azure does not support creating standalone volumes"); } @Override public void detach(@Nonnull String volumeId, boolean force) throws InternalException, CloudException { if( logger.isTraceEnabled() ) { logger.trace("ENTER: " + AzureDisk.class.getName() + ".detach(" + volumeId+")"); } try { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new AzureConfigException("No context was specified for this request"); } Volume disk ; if(volumeId != null){ disk = getVolume(volumeId); if(disk == null ){ throw new InternalException("Can not find the source snapshot !"); } }else{ throw new InternalException("volumeId is null !"); } String providerVirtualMachineId = disk.getProviderVirtualMachineId(); VirtualMachine vm = null; if( providerVirtualMachineId != null ) { vm = provider.getComputeServices().getVirtualMachineSupport().getVirtualMachine(providerVirtualMachineId); } if( vm == null ) { logger.trace("Sorry, the disk is not attached to the VM with id " + providerVirtualMachineId + " or the VM id is not in the desired format !!!"); throw new InternalException("Sorry, the disk is not attached to the VM with id " + providerVirtualMachineId + " or the VM id is not in the desired format !!!"); } String lun = getDiskLun(disk.getProviderVolumeId(), providerVirtualMachineId); if(lun == null){ logger.trace("Can not identify the lun number"); throw new InternalException("logical unit number of disk is null, detach operation can not be continue!"); } String resourceDir = HOSTED_SERVICES + "/" + vm.getTag("serviceName") + "/deployments" + "/" + vm.getTag("deploymentName") + "/roles"+"/" + vm.getTag("roleName") + "/DataDisks" + "/" + lun; AzureMethod method = new AzureMethod(provider); method.invoke("DELETE",ctx.getAccountNumber(), resourceDir, null); } finally { if( logger.isTraceEnabled() ) { logger.trace("EXIT: " + AzureDisk.class.getName() + ".detach()"); } } } private String getDiskLun(String providerVolumeId, String providerVirtualMachineId) throws InternalException, CloudException { AzureMethod method = new AzureMethod(provider); VirtualMachine vm = provider.getComputeServices().getVirtualMachineSupport().getVirtualMachine(providerVirtualMachineId); String resourceDir = HOSTED_SERVICES + "/"+ vm.getTag("serviceName") + "/deployments" + "/" + vm.getTag("deploymentName"); Document doc = method.getAsXML(provider.getContext().getAccountNumber(),resourceDir); if( doc == null ) { return null; } NodeList entries = doc.getElementsByTagName("DataVirtualHardDisk"); if( entries.getLength() < 1 ) { return null; } for( int i=0; i<entries.getLength(); i++ ) { Node detail = entries.item(i); NodeList attributes = detail.getChildNodes(); String diskName = null, lunValue = null; for( int j=0; j<attributes.getLength(); j++ ) { Node attribute = attributes.item(j); if(attribute.getNodeType() == Node.TEXT_NODE) continue; if( attribute.getNodeName().equalsIgnoreCase("DiskName") && attribute.hasChildNodes() ) { diskName = attribute.getFirstChild().getNodeValue().trim(); } else if( attribute.getNodeName().equalsIgnoreCase("Lun") && attribute.hasChildNodes() ) { if (diskName != null && diskName.equalsIgnoreCase(providerVolumeId)) { lunValue = attribute.getFirstChild().getNodeValue().trim(); } } } if(diskName != null && diskName.equalsIgnoreCase(providerVolumeId)){ if(lunValue == null){ lunValue = "0"; } return lunValue; } } return null; } @Override public int getMaximumVolumeCount() throws InternalException, CloudException { return 16; } @Override public @Nullable Storage<Gigabyte> getMaximumVolumeSize() throws InternalException, CloudException { return new Storage<Gigabyte>(1024, Storage.GIGABYTE); } @Override public @Nonnull Storage<Gigabyte> getMinimumVolumeSize() throws InternalException, CloudException { return new Storage<Gigabyte>(1, Storage.GIGABYTE); } @Override public @Nonnull String getProviderTermForVolume(@Nonnull Locale locale) { return "disk"; } @Override public @Nullable Volume getVolume(@Nonnull String volumeId) throws InternalException, CloudException { //To change body of implemented methods use File | Settings | File Templates. ArrayList<Volume> list = (ArrayList<Volume>) listVolumes(); if(list == null) return null; for(Volume disk : list){ if(disk.getProviderVolumeId().equals(volumeId)){ return disk; } } return null; } @Nonnull @Override public Requirement getVolumeProductRequirement() throws InternalException, CloudException { return Requirement.NONE; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean isVolumeSizeDeterminedByProduct() throws InternalException, CloudException { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public @Nonnull Iterable<String> listPossibleDeviceIds(@Nonnull Platform platform) throws InternalException, CloudException { //To change body of implemented methods use File | Settings | File Templates. ArrayList<String> list = new ArrayList<String>(); for(int i= 0;i < this.getMaximumVolumeCount();i++){ list.add(String.valueOf(i)); } return list; } @Nonnull @Override public Iterable<VolumeFormat> listSupportedFormats() throws InternalException, CloudException { return Collections.singletonList(VolumeFormat.BLOCK); } @Nonnull @Override public Iterable<VolumeProduct> listVolumeProducts() throws InternalException, CloudException { return Collections.emptyList(); } @Nonnull @Override public Iterable<ResourceStatus> listVolumeStatus() throws InternalException, CloudException { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new AzureConfigException("No context was specified for this request"); } AzureMethod method = new AzureMethod(provider); Document doc = method.getAsXML(ctx.getAccountNumber(), DISK_SERVICES); NodeList entries = doc.getElementsByTagName("Disk"); ArrayList<ResourceStatus> list = new ArrayList<ResourceStatus>(); for( int i=0; i<entries.getLength(); i++ ) { Node entry = entries.item(i); ResourceStatus status = toStatus(ctx, entry); if( status != null ) { list.add(status); } } return list; } @Override public @Nonnull Iterable<Volume> listVolumes() throws InternalException, CloudException { //To change body of implemented methods use File | Settings | File Templates. ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new AzureConfigException("No context was specified for this request"); } AzureMethod method = new AzureMethod(provider); Document doc = method.getAsXML(ctx.getAccountNumber(), DISK_SERVICES); NodeList entries = doc.getElementsByTagName("Disk"); ArrayList<Volume> disks = new ArrayList<Volume>(); for( int i=0; i<entries.getLength(); i++ ) { Node entry = entries.item(i); Volume disk = toVolume(ctx, entry); if( disk != null ) { disks.add(disk); } } return disks; } @Nonnull @Override public Iterable<Volume> listVolumes(@Nullable VolumeFilterOptions volumeFilterOptions) throws InternalException, CloudException { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new AzureConfigException("No context was specified for this request"); } AzureMethod method = new AzureMethod(provider); Document doc = method.getAsXML(ctx.getAccountNumber(), DISK_SERVICES); NodeList entries = doc.getElementsByTagName("Disk"); ArrayList<Volume> disks = new ArrayList<Volume>(); for( int i=0; i<entries.getLength(); i++ ) { Node entry = entries.item(i); Volume disk = toVolume(ctx, entry); if( disk != null ) { disks.add(disk); } } return disks; } private boolean isWithinDeviceList(String device) throws InternalException, CloudException{ ArrayList<String> list = (ArrayList<String>) listPossibleDeviceIds(Platform.UNIX); for(String id : list){ if(id.equals(device)){ return true; } } return false; } @Override public boolean isSubscribed() throws CloudException, InternalException { return true; //To change body of implemented methods use File | Settings | File Templates. } @Override public void remove(@Nonnull String volumeId) throws InternalException, CloudException { if( logger.isTraceEnabled() ) { logger.trace("ENTER: " + AzureDisk.class.getName() + ".remove(" + volumeId + ")"); } try { ProviderContext ctx = provider.getContext(); if( ctx == null ) { throw new AzureConfigException("No context was specified for this request"); } AzureMethod method = new AzureMethod(provider); method.invoke("DELETE",ctx.getAccountNumber(), DISK_SERVICES+"/" + volumeId+"?comp=media", null); } finally { if( logger.isTraceEnabled() ) { logger.trace("EXIT: " + AzureDisk.class.getName() + ".remove()"); } } } @Override public void removeTags(@Nonnull String s, @Nonnull Tag... tags) throws CloudException, InternalException { //To change body of implemented methods use File | Settings | File Templates. } @Override public void removeTags(@Nonnull String[] strings, @Nonnull Tag... tags) throws CloudException, InternalException { //To change body of implemented methods use File | Settings | File Templates. } @Override public void updateTags(@Nonnull String s, @Nonnull Tag... tags) throws CloudException, InternalException { //To change body of implemented methods use File | Settings | File Templates. } @Override public void updateTags(@Nonnull String[] strings, @Nonnull Tag... tags) throws CloudException, InternalException { //To change body of implemented methods use File | Settings | File Templates. } @Override public @Nonnull String[] mapServiceAction(@Nonnull ServiceAction action) { return new String[0]; } private @Nullable Volume toVolume(@Nonnull ProviderContext ctx, @Nullable Node volumeNode) throws InternalException, CloudException { if( volumeNode == null ) { return null; } String regionId = ctx.getRegionId(); if( regionId == null ) { throw new AzureConfigException("No region ID was specified for this request"); } Volume disk = new Volume(); disk.setProviderRegionId(regionId); disk.setCurrentState(VolumeState.AVAILABLE); disk.setType(VolumeType.HDD); boolean mediaLocationFound = false; NodeList attributes = volumeNode.getChildNodes(); for( int i=0; i<attributes.getLength(); i++ ) { Node attribute = attributes.item(i); if(attribute.getNodeType() == Node.TEXT_NODE) continue; if( attribute.getNodeName().equalsIgnoreCase("AttachedTo") && attribute.hasChildNodes() ) { NodeList attachAttributes = attribute.getChildNodes(); String hostedServiceName = null; String deploymentName = null; String vmRoleName = null; for( int k=0; k<attachAttributes.getLength(); k++ ) { Node attach = attachAttributes.item(k); if(attach.getNodeType() == Node.TEXT_NODE) continue; if(attach.getNodeName().equalsIgnoreCase("HostedServiceName") && attach.hasChildNodes() ) { hostedServiceName = attach.getFirstChild().getNodeValue().trim(); } else if(attach.getNodeName().equalsIgnoreCase("DeploymentName") && attach.hasChildNodes() ) { deploymentName = attach.getFirstChild().getNodeValue().trim(); } else if(attach.getNodeName().equalsIgnoreCase("RoleName") && attach.hasChildNodes() ) { vmRoleName = attach.getFirstChild().getNodeValue().trim(); } } if(hostedServiceName != null && deploymentName != null && vmRoleName != null){ disk.setProviderVirtualMachineId(hostedServiceName+":"+deploymentName+":"+vmRoleName); } } else if( attribute.getNodeName().equalsIgnoreCase("OS") && attribute.hasChildNodes() ) { // not a volume so should not be returned here return null; //disk.setGuestOperatingSystem(Platform.guess(attribute.getFirstChild().getNodeValue().trim())); } // disk may have either affinity group or location depending on how storage account is set up else if( attribute.getNodeName().equalsIgnoreCase("AffinityGroup") && attribute.hasChildNodes() ) { //get the region for this affinity group String affinityGroup = attribute.getFirstChild().getNodeValue().trim(); if (affinityGroup != null && !affinityGroup.equals("")) { DataCenter dc = provider.getDataCenterServices().getDataCenter(affinityGroup); if (dc.getRegionId().equals(disk.getProviderRegionId())) { disk.setProviderDataCenterId(dc.getProviderDataCenterId()); mediaLocationFound = true; } else { // not correct region/datacenter return null; } } } else if( attribute.getNodeName().equalsIgnoreCase("Location") && attribute.hasChildNodes() ) { if( !mediaLocationFound && !regionId.equals(attribute.getFirstChild().getNodeValue().trim()) ) { return null; } } else if( attribute.getNodeName().equalsIgnoreCase("LogicalDiskSizeInGB") && attribute.hasChildNodes() ) { disk.setSize(Storage.valueOf(Integer.valueOf(attribute.getFirstChild().getNodeValue().trim()), "gigabyte")); } else if( attribute.getNodeName().equalsIgnoreCase("MediaLink") && attribute.hasChildNodes() ) { disk.setMediaLink(attribute.getFirstChild().getNodeValue().trim()); } else if( attribute.getNodeName().equalsIgnoreCase("Name") && attribute.hasChildNodes() ) { disk.setProviderVolumeId(attribute.getFirstChild().getNodeValue().trim()); } else if( attribute.getNodeName().equalsIgnoreCase("SourceImageName") && attribute.hasChildNodes() ) { disk.setProviderSnapshotId(attribute.getFirstChild().getNodeValue().trim()); } } if(disk.getGuestOperatingSystem() == null){ disk.setGuestOperatingSystem(Platform.UNKNOWN); } if( disk.getName() == null ) { disk.setName(disk.getProviderVolumeId()); } if( disk.getDescription() == null ) { disk.setDescription(disk.getName()); } if (disk.getProviderDataCenterId() == null) { DataCenter dc = provider.getDataCenterServices().listDataCenters(regionId).iterator().next(); disk.setProviderDataCenterId(dc.getProviderDataCenterId()); } return disk; } private @Nullable ResourceStatus toStatus(@Nonnull ProviderContext ctx, @Nullable Node volumeNode) throws InternalException, CloudException { if( volumeNode == null ) { return null; } String regionId = ctx.getRegionId(); if( regionId == null ) { throw new AzureConfigException("No region ID was specified for this request"); } String id = ""; boolean mediaLocationFound = false; NodeList attributes = volumeNode.getChildNodes(); for( int i=0; i<attributes.getLength(); i++ ) { Node attribute = attributes.item(i); if(attribute.getNodeType() == Node.TEXT_NODE) continue; if( attribute.getNodeName().equalsIgnoreCase("Name") && attribute.hasChildNodes() ) { id = attribute.getFirstChild().getNodeValue().trim(); } else if( attribute.getNodeName().equalsIgnoreCase("AffinityGroup") && attribute.hasChildNodes() ) { //get the region for this affinity group String affinityGroup = attribute.getFirstChild().getNodeValue().trim(); if (affinityGroup != null && !affinityGroup.equals("")) { DataCenter dc = provider.getDataCenterServices().getDataCenter(affinityGroup); if (dc.getRegionId().equals(regionId)) { mediaLocationFound = true; } else { // not correct region/datacenter return null; } } } else if( attribute.getNodeName().equalsIgnoreCase("Location") && attribute.hasChildNodes() ) { if( !mediaLocationFound && !regionId.equals(attribute.getFirstChild().getNodeValue().trim()) ) { return null; } } } ResourceStatus status = new ResourceStatus(id, VolumeState.AVAILABLE); return status; } }
package org.gestern.gringotts.api.impl; import java.util.ArrayList; import java.util.List; import net.milkbowl.vault.economy.Economy; import net.milkbowl.vault.economy.EconomyResponse; import net.milkbowl.vault.economy.EconomyResponse.ResponseType; import org.gestern.gringotts.Gringotts; import org.gestern.gringotts.api.Account; import org.gestern.gringotts.api.Eco; import org.gestern.gringotts.api.TransactionResult; /** * Provides the vault interface, so that the economy adapter in vault does not need to be changed. * * @author jast * */ public class VaultConnector implements Economy { private final String name = "Gringotts"; private final Eco eco = new GringottsEco(); public VaultConnector() { } @Override public boolean isEnabled(){ return Gringotts.G != null && Gringotts.G.isEnabled(); } @Override public String getName() { return name; } @Override public boolean hasBankSupport() { return false; } @Override public int fractionalDigits() { return eco.currency().fractionalDigits(); } @Override public String format(double amount) { return eco.currency().format(amount); } @Override public String currencyNamePlural(){ return eco.currency().namePlural(); } @Override public String currencyNameSingular(){ return eco.currency().name(); } @Override public boolean hasAccount(String playerName) { return eco.account(playerName).exists(); } @Override public double getBalance(String playerName){ return eco.account(playerName).balance(); } @Override public boolean has(String playerName, double amount) { return eco.account(playerName).has(amount); } @Override public EconomyResponse withdrawPlayer(String playerName, double amount) { Account account = eco.account(playerName); TransactionResult removed = account.remove(amount); switch (removed) { case SUCCESS: return new EconomyResponse(amount, account.balance(), ResponseType.SUCCESS, null); case INSUFFICIENT_FUNDS: return new EconomyResponse(0, account.balance(), ResponseType.FAILURE, "Insufficient funds."); case ERROR: default: return new EconomyResponse(0, account.balance(), ResponseType.FAILURE, "Unknown failure."); } } @Override public EconomyResponse depositPlayer(String playerName, double amount){ Account account = eco.account(playerName); TransactionResult added = account.add(amount); switch (added) { case SUCCESS: return new EconomyResponse(amount, account.balance(), ResponseType.SUCCESS, null); case INSUFFICIENT_SPACE: return new EconomyResponse(0, account.balance(), ResponseType.FAILURE, "Insufficient space."); case ERROR: default: return new EconomyResponse(0, account.balance(), ResponseType.FAILURE, "Unknown failure."); } } @Override public EconomyResponse createBank(String name, String player) { return new EconomyResponse(0,0, ResponseType.NOT_IMPLEMENTED, "Gringotts does not support banks"); // BankAccount bank = eco.bank(name).addOwner(player); // if (bank.exists()) // return new EconomyResponse(0, 0, ResponseType.FAILURE, "Unable to create bank!"); // else // return new EconomyResponse(0, 0, ResponseType.SUCCESS, "Created bank " + name); } @Override public EconomyResponse deleteBank(String name) { return new EconomyResponse(0,0, ResponseType.NOT_IMPLEMENTED, "Gringotts does not support banks"); // Account deleted = eco.bank(name).delete(); // if (deleted.exists()) // return new EconomyResponse(0, 0, ResponseType.FAILURE, "Unable to delete bank account!"); // else // return new EconomyResponse(0, 0, ResponseType.SUCCESS, "Deleted bank account (or it didn't exist)"); } @Override public EconomyResponse bankBalance(String name) { return new EconomyResponse(0,0, ResponseType.NOT_IMPLEMENTED, "Gringotts does not support banks"); // double balance = eco.bank(name).balance(); // return new EconomyResponse(0, balance, // ResponseType.SUCCESS, "Balance of bank "+ name +": "+ balance); } @Override public EconomyResponse bankHas(String name, double amount) { return new EconomyResponse(0,0, ResponseType.NOT_IMPLEMENTED, "Gringotts does not support banks"); // BankAccount bank = eco.bank(name); // double balance = bank.balance(); // if (bank.has(amount)) // return new EconomyResponse(0, balance, ResponseType.SUCCESS, "Bank " + name + " has at least " + amount ); // else // return new EconomyResponse(0, balance, ResponseType.FAILURE, "Bank " + name + " does not have at least " + amount ); } @Override public EconomyResponse bankWithdraw(String name, double amount) { return new EconomyResponse(0,0, ResponseType.NOT_IMPLEMENTED, "Gringotts does not support banks"); // BankAccount bank = eco.bank(name); // TransactionResult result = bank.remove(amount); // if (result == TransactionResult.SUCCESS) // return new EconomyResponse(amount, bank.balance(), ResponseType.SUCCESS, "Removed " + amount + " from bank " + name); // else // return new EconomyResponse(0, bank.balance(), ResponseType.SUCCESS, "Failed to remove " + amount + " from bank " + name); } @Override public EconomyResponse bankDeposit(String name, double amount) { return new EconomyResponse(0,0, ResponseType.NOT_IMPLEMENTED, "Gringotts does not support banks"); // BankAccount bank = eco.bank(name); // TransactionResult result = bank.add(amount); // if (result == TransactionResult.SUCCESS) // return new EconomyResponse(amount, bank.balance(), ResponseType.SUCCESS, "Added " + amount + " to bank " + name); // else // return new EconomyResponse(0, bank.balance(), ResponseType.SUCCESS, "Failed to add " + amount + " to bank " + name); } @Override public EconomyResponse isBankOwner(String name, String playerName) { return new EconomyResponse(0,0, ResponseType.NOT_IMPLEMENTED, "Gringotts does not support banks"); // return new EconomyResponse(0, 0, eco.bank(name).isOwner(playerName)? ResponseType.SUCCESS : FAILURE, ""); } @Override public EconomyResponse isBankMember(String name, String playerName) { return new EconomyResponse(0,0, ResponseType.NOT_IMPLEMENTED, "Gringotts does not support banks"); // return new EconomyResponse(0, 0, eco.bank(name).isMember(playerName)? ResponseType.SUCCESS : FAILURE, ""); } @Override public List<String> getBanks() { return new ArrayList<String>(); // return new ArrayList<String>(eco.getBanks()); } @Override public boolean createPlayerAccount(String playerName) { return hasAccount(playerName); } }
package org.jenkinsci.plugins.DependencyCheck; import hudson.FilePath; import org.owasp.dependencycheck.reporting.ReportGenerator; import java.io.Serializable; import java.net.URL; import java.util.ArrayList; /** * A container object that holds all of the configurable options to be used by * a DependencyCheck analysis. * * @author Steve Springett (steve.springett@owasp.org) */ @SuppressWarnings("unused") public class Options implements Serializable { private static final long serialVersionUID = 4571161829818421072L; /** * The name of the report to be displayed */ private String name; /** * Specifies the directory[s] to scan. */ private ArrayList<FilePath> scanPath = new ArrayList<FilePath>(); /** * Specifies the destination directory for the generated report. */ private FilePath outputDirectory; /** * Specifies the data directory. */ private FilePath dataDirectory; /** * Boolean value (true/false) whether or not the evidence collected * about a dependency is displayed in the report. Default is false. */ private boolean showEvidence = false; /** * The report format to be generated. Default is XML. */ private ReportGenerator.Format format = ReportGenerator.Format.XML; /** * Sets whether auto-updating of the NVD CVE/CPE data is enabled. It is not * recommended that this be turned to false. Default is true. */ private boolean autoUpdate = true; /** * Specifies the verbose logging file to use */ private FilePath verboseLoggingFile; /** * Specifies the data mirroring type (scheme) to use */ private int dataMirroringType; /** * Specifies the CVE 1.2 modified URL */ private URL cveUrl12Modified; /** * Specifies the CVE 2.0 modified URL */ private URL cveUrl20Modified; /** * Specifies the CVE 1.2 base URL */ private URL cveUrl12Base; /** * Specifies the CVE 2.0 base URL */ private URL cveUrl20Base; /** * Returns the name of the report to be displayed */ public String getName() { return name; } /** * Sets the name of the report to be displayed */ public void setName(String name) { this.name = name; } /** * Returns the files and/or directory[s] to scan. */ public ArrayList<FilePath> getScanPath() { return scanPath; } /** * Sets the file[s] and/or directory[s] to scan */ public void setScanPath(ArrayList<FilePath> scanPath) { this.scanPath = scanPath; } /** * Add a file and/or directory to scan */ public void addScanPath(FilePath scanPath) { if (this.scanPath == null) { this.scanPath = new ArrayList<FilePath>(); } this.scanPath.add(scanPath); } /** * Returns the destination directory for the generated report. */ public FilePath getOutputDirectory() { return outputDirectory; } /** * Sets the destination directory for the generated report. */ public void setOutputDirectory(FilePath outputDirectory) { this.outputDirectory = outputDirectory; } /** * Returns the data directory. */ public FilePath getDataDirectory() { return dataDirectory; } /** * Sets the data directory. */ public void setDataDirectory(FilePath dataDirectory) { this.dataDirectory = dataDirectory; } /** * Returns a boolean value (true/false) whether or not the evidence collected * about a dependency is displayed in the report. Default is false. */ public boolean isShowEvidence() { return showEvidence; } /** * Sets a boolean value (true/false) whether or not the evidence collected * about a dependency is displayed in the report. */ public void setShowEvidence(boolean showEvidence) { this.showEvidence = showEvidence; } /** * Returns the report format to be generated. Default is XML. */ public ReportGenerator.Format getFormat() { return format; } /** * Sets the report format to be generated. */ public void setFormat(ReportGenerator.Format format) { this.format = format; } /** * Returns whether auto-updating of the NVD CVE/CPE data is enabled. It is not * recommended that this be turned to false. Default is true. */ public boolean isAutoUpdate() { return autoUpdate; } /** * Sets whether auto-updating of the NVD CVE/CPE data is enabled. It is not * recommended that this be turned to false. */ public void setAutoUpdate(boolean autoUpdate) { this.autoUpdate = autoUpdate; } /** * Returns the verbose logging file */ public FilePath getVerboseLoggingFile() { return verboseLoggingFile; } /** * Sets whether verbose logging of the Dependency-Check engine and analyzers * is enabled. */ public void setVerboseLoggingFile(FilePath file) { this.verboseLoggingFile = file; } /** * Returns the data mirroring type (scheme) to use where 0 = none and 1 = NIST CPE/CVE */ public int getDataMirroringType() { return dataMirroringType; } /** * Sets the data mirroring type */ public void setDataMirroringType(int dataMirroringType) { this.dataMirroringType = dataMirroringType; } /** * Returns the CVE 1.2 modified URL */ public URL getCveUrl12Modified() { return cveUrl12Modified; } /** * Sets the CVE 1.2 modified URL */ public void setCveUrl12Modified(URL url) { this.cveUrl12Modified = url; } /** * Returns the CVE 2.0 modified URL */ public URL getCveUrl20Modified() { return cveUrl20Modified; } /** * Sets the CVE 2.0 modified URL */ public void setCveUrl20Modified(URL url) { this.cveUrl20Modified = url; } /** * Returns the CVE 1.2 base URL */ public URL getCveUrl12Base() { return cveUrl12Base; } /** * Sets the CVE 1.2 base URL */ public void setCveUrl12Base(URL url) { this.cveUrl12Base = url; } /** * Returns the CVE 2.0 base URL */ public URL getCveUrl20Base() { return cveUrl20Base; } /** * Sets the CVE 2.0 base URL */ public void setCveUrl20Base(URL url) { this.cveUrl20Base = url; } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (name == null) { sb.append(" -name = ").append("ERROR - NAME NOT SPECIFIED OR INVALID.\n"); } else { sb.append(" -name = ").append(name).append("\n"); } if (scanPath == null || scanPath.size() == 0) { sb.append(" -scanPath = ").append("ERROR - PATH NOT SPECIFIED OR INVALID.\n"); } else { for (FilePath filePath: scanPath) { sb.append(" -scanPath = ").append(filePath.getRemote()).append("\n"); } } if (outputDirectory == null) { sb.append(" -outputDirectory = ").append("ERROR - OUTPUT DIRECTORY NOT SPECIFIED OR INVALID.\n"); } else { sb.append(" -outputDirectory = ").append(outputDirectory.getRemote()).append("\n"); } if (dataDirectory == null) { sb.append(" -dataDirectory = ").append("ERROR - DATA DIRECTORY NOT SPECIFIED OR INVALID.\n"); } else { sb.append(" -dataDirectory = ").append(dataDirectory.getRemote()).append("\n"); } if (verboseLoggingFile != null) { sb.append(" -verboseLogFile = ").append(verboseLoggingFile.getRemote()).append("\n"); } sb.append(" -dataMirroringType = ").append(dataMirroringType==0 ? "none" : "NIST CPE/CVE").append("\n"); if (dataMirroringType != 0) { if (cveUrl12Modified == null) { sb.append(" -cveUrl12Modified = ").append("ERROR - CVE 1.2 MODIFIED URL NOT SPECIFIED OR INVALID.\n"); } else { sb.append(" -cveUrl12Modified = ").append(cveUrl12Modified.toExternalForm()).append("\n"); } if (cveUrl20Modified == null) { sb.append(" -cveUrl20Modified = ").append("ERROR - CVE 2.0 MODIFIED URL NOT SPECIFIED OR INVALID.\n"); } else { sb.append(" -cveUrl20Modified = ").append(cveUrl20Modified.toExternalForm()).append("\n"); } if (cveUrl12Base == null) { sb.append(" -cveUrl12Base = ").append("ERROR - CVE 1.2 BASE URL NOT SPECIFIED OR INVALID.\n"); } else { sb.append(" -cveUrl12Base = ").append(cveUrl12Base.toExternalForm()).append("\n"); } if (cveUrl20Base == null) { sb.append(" -cveUrl20Base = ").append("ERROR - CVE 2.0 BASE URL NOT SPECIFIED OR INVALID.\n"); } else { sb.append(" -cveUrl20Base = ").append(cveUrl20Base.toExternalForm()).append("\n"); } } sb.append(" -showEvidence = ").append(showEvidence).append("\n"); sb.append(" -format = ").append(format.name()).append("\n"); sb.append(" -autoUpdate = ").append(autoUpdate); return sb.toString(); } }
package org.lightmare.deploy.management; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.io.Writer; import java.util.List; import javax.servlet.Servlet; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.lightmare.deploy.fs.Watcher; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.StringUtils; /** * {@link Servlet} to manage deployed applications * * @author levan * */ @WebServlet("/DeployManager") public class DeployManager extends HttpServlet { private static final long serialVersionUID = 1L; public static final String DEPLOY_MANAGER_DEFAULT_NAME = "/DeployManager"; // html tags private static final String BEGIN_TAGS = "<tr><td><a name = \""; private static final String NAME_OF_TAGS = "\" href=\" private static final String END_NAME_TAGS = "</a></td>\n"; private static final String END_TAGS = "</td><td><a href = \"DeployManager\">reload</a></td></tr>"; private static final String REDEPLOY_START_TAG = "<td><a name = \""; private static final String REDEPLOY_TYPE_TAG = "\" href=\"#\" onClick=\"sendRequest(this.name, '"; private static final String REDEPLOY_FILE_TYPE_TAG = "', '"; private static final String REDEPLOY_NAME_TAG = "')\">"; private static final String REDEPLOY_END_TAG = "</a></td>"; private static final String BEGIN_PAGE = StringUtils .concat("<html>\n", "\t<head><script type=\"text/javascript\">\n", "/* <![CDATA[ */\n", "\t\tfunction sendRequest(redeploy, type, fileType){\n ", "\t\t\tvar xmlhttp = new XMLHttpRequest();\n ", "\t\t\tvar reqUrl = \"DeployManager?file=\" + redeploy + \"&type=\" + type + \"&fileType=\" + fileType;\n", "\t\t\txmlhttp.open(\"GET\", reqUrl, true);\n", "\t\t\txmlhttp.send();\n", "}\n", "\n", "</script>\n", "\t<title>Deployment management</title>", "</head>\n", "\t<body>\n", "\t<table>\n"); private static final String TYPE_TAG = "\t\t<tr><td><br><b>"; private static final String END_TYPE_TAG = "</b></br></td></tr>\n"; private static final String END_PAGE = "</body></table>\n </html>"; private static final String LOGIN_PAGE = StringUtils .concat("<html>\n", "\t\t<head>\n", "\t\t\t<title>Login</title>\n", "\t\t</head>\n", "\t\t<body>\n", "\t\t\t\t\t\t<br><form name = \"ManagementLogin\" method=\"post\">", "\t\t\t\t\t\t\t<br><input type=\"user\" name=\"user\"></br>", "\t\t\t\t\t\t\t<br><input type=\"password\" name=\"password\"></br>", "\t\t\t\t\t\t\t<br><input type=\"submit\" value=\"Submit\"></br>", "\t\t\t\t\t\t</form></br>\n"); private static final String INCORRECT_MESSAGE = "<br><b>invalid user name / passowd</b></br>"; private static final String END_LOGIN_PAGE = "</html>"; private static final String DEPLOYMENTS = "deployments"; private static final String DATA_SOURCES = "datasources"; // HTTP parameters private static final String REDEPLOY_PARAM_NAME = "file"; private static final String TYPE_PARAM_NAME = "type"; private static final String REDEPLOY_TYPE = "redeploy"; private static final String UNDEPLOY_TYPE = "undeploy"; protected static final String FILE_TYPE_PARAMETER_NAME = "fileType"; private static final String APP_DEPLOYMENT_TYPE = "application"; private static final String DTS_DEPLOYMENT_TYPE = "datasource"; private static final String USER_PARAMETER_NAME = "user"; private static final String PASS_PARAMETER_NAME = "password"; private static final String DEPLOY_PASS_KEY = "deploy_manager_pass"; private Security security; /** * Class to cache authenticated users for {@link DeployManager} servlet page * * @author levan * */ private static class DeployPass implements Serializable { private static final long serialVersionUID = 1L; private String userName; } private String getApplications() { List<File> apps = Watcher.listDeployments(); List<File> dss = Watcher.listDataSources(); StringBuilder builder = new StringBuilder(); builder.append(BEGIN_PAGE); builder.append(TYPE_TAG); builder.append(DEPLOYMENTS); builder.append(END_TYPE_TAG); String tag; if (ObjectUtils.available(apps)) { for (File app : apps) { tag = getTag(app.getPath(), APP_DEPLOYMENT_TYPE); builder.append(tag); } } builder.append(BEGIN_PAGE); builder.append(TYPE_TAG); builder.append(DATA_SOURCES); builder.append(END_TYPE_TAG); if (ObjectUtils.available(dss)) { for (File ds : dss) { tag = getTag(ds.getPath(), DTS_DEPLOYMENT_TYPE); builder.append(tag); } } builder.append(END_PAGE); return builder.toString(); } private void fillDeployType(StringBuilder builder, String app, String type, String fileType) { builder.append(REDEPLOY_START_TAG); builder.append(app); builder.append(REDEPLOY_TYPE_TAG); builder.append(type); builder.append(REDEPLOY_FILE_TYPE_TAG); builder.append(fileType); builder.append(REDEPLOY_NAME_TAG); builder.append(type); builder.append(REDEPLOY_END_TAG); } private String getTag(String app, String fileType) { StringBuilder builder = new StringBuilder(); builder.append(BEGIN_TAGS); builder.append(app); builder.append(NAME_OF_TAGS); builder.append(app); builder.append(END_NAME_TAGS); fillDeployType(builder, app, UNDEPLOY_TYPE, fileType); fillDeployType(builder, app, REDEPLOY_TYPE, fileType); builder.append(END_TAGS); return builder.toString(); } private String toLoginPage(boolean incorrect) { StringBuilder builder = new StringBuilder(); builder.append(LOGIN_PAGE); if (incorrect) { builder.append(INCORRECT_MESSAGE); } builder.append(END_LOGIN_PAGE); return builder.toString(); } private boolean authenticate(String userName, String password, HttpSession session) { boolean valid = security.authenticate(userName, password); if (valid) { DeployPass pass = new DeployPass(); pass.userName = userName; session.setAttribute(DEPLOY_PASS_KEY, pass); } return valid; } private boolean check(HttpSession session) { boolean valid = ObjectUtils.notNull(session); if (valid) { Object pass = session.getAttribute(DEPLOY_PASS_KEY); valid = ObjectUtils.notNull(pass); if (valid) { valid = (pass instanceof DeployPass) && (ObjectUtils.available(((DeployPass) pass).userName)); } else { valid = security.check(); } } return valid; } @Override public void init() throws ServletException { try { security = new Security(); } catch (IOException ex) { } super.init(); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean check = check(request.getSession(Boolean.FALSE)); String html; if (check) { String fileName = request.getParameter(REDEPLOY_PARAM_NAME); String type = request.getParameter(TYPE_PARAM_NAME); if (ObjectUtils.available(fileName)) { if (type == null || REDEPLOY_TYPE.equals(type)) { Watcher.redeployFile(fileName); } else if (UNDEPLOY_TYPE.equals(type)) { Watcher.undeployFile(fileName); } } html = getApplications(); } else { html = toLoginPage(Boolean.FALSE); } Writer writer = response.getWriter(); try { writer.write(html); } finally { writer.close(); } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userName = request.getParameter(USER_PARAMETER_NAME); String password = request.getParameter(PASS_PARAMETER_NAME); boolean valid = ObjectUtils.available(userName) && ObjectUtils.available(password); if (valid) { valid = authenticate(userName, password, request.getSession(Boolean.TRUE)); } if (valid) { response.sendRedirect("DeployManager"); } else { String html = toLoginPage(Boolean.TRUE); Writer writer = response.getWriter(); try { writer.write(html); } finally { writer.close(); } } } }
package org.lightmare.ejb.embeddable; import java.io.IOException; import java.util.Map; import javax.ejb.embeddable.EJBContainer; import javax.naming.Context; import org.apache.log4j.Logger; import org.lightmare.deploy.MetaCreator; import org.lightmare.jndi.JndiManager; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.ObjectUtils; /** * Implementation for {@link javax.ejb.embeddable.EJBContainer} class for given * EJB container (runs only for java 7 and upper) * * @author levan * @since 0.0.48-SNAPSHOT */ public class EJBContainerImpl extends EJBContainer { // Initializes EJB container private MetaCreator creator; private static final Logger LOG = Logger.getLogger(EJBContainerImpl.class); protected EJBContainerImpl() { try { this.creator = new MetaCreator.Builder().build(); this.creator.scanForBeans(); } catch (IOException ex) { LOG.error("Could not initialize EJBContainer", ex); } } protected EJBContainerImpl(Map<?, ?> properties) { try { MetaCreator.Builder builder; if (CollectionUtils.valid(properties)) { Map<Object, Object> configuration = ObjectUtils .cast(properties); builder = new MetaCreator.Builder(configuration); } else { builder = new MetaCreator.Builder(); } this.creator = builder.build(); this.creator.scanForBeans(); } catch (IOException ex) { LOG.error("Could not initialize EJBContainer", ex); } } @Override public Context getContext() { Context context; try { JndiManager utils = new JndiManager(); context = utils.getContext(); } catch (IOException ex) { context = null; LOG.error("Could not initialize Context", ex); } return context; } @Override public void close() { try { if (ObjectUtils.notNull(creator)) { creator.clear(); } MetaCreator.close(); } catch (IOException ex) { LOG.fatal(ex.getMessage(), ex); } } }
package org.musicbrainz.search.solrwriter; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.math.BigInteger; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import org.apache.lucene.document.Document; import org.apache.solr.common.util.NamedList; import org.apache.solr.request.SolrQueryRequest; import org.apache.solr.response.*; import org.apache.solr.search.DocIterator; import org.musicbrainz.mmd2.*; public class MBXMLWriter implements QueryResponseWriter { /** * The context used to (un-)serialize XML */ private JAXBContext context = null; private Unmarshaller unmarshaller = null; protected Marshaller marshaller = null; private ObjectFactory objectfactory = null; /** * The entity type of this MBXMLWriter */ private entityTypes entityType = null; private enum entityTypes { artist, area, cdstub, label, place, recording, release, release_group, tag, work; public static entityTypes getType(String entityType) { for (entityTypes et : entityTypes.values()) { if (et.name().equalsIgnoreCase(entityType)) { return et; } } throw new IllegalArgumentException(entityType + "is not a valid entity type"); } } /** * MetadataListWrapper wraps common functionality in dealing with * {@link Metadata}. This includes generating the appropriate list object * for different entity types, as well as calling the appropriate method to * set the list on the {@link Metadata} object. */ class MetadataListWrapper { private List objList = null; private Object MMDList = null; private Metadata metadata = null; private Method setCountMethod = null; private Method setOffsetMethod = null; public MetadataListWrapper() { switch (entityType) { case area: MMDList = objectfactory.createAreaList(); objList = ((AreaList) MMDList).getArea(); break; case artist: MMDList = objectfactory.createArtistList(); objList = ((ArtistList) MMDList).getArtist(); break; case cdstub: MMDList = objectfactory.createCdstubList(); objList = ((CdstubList) MMDList).getCdstub(); break; case label: MMDList = objectfactory.createLabelList(); objList = ((LabelList) MMDList).getLabel(); break; case place: MMDList = objectfactory.createPlaceList(); objList = ((PlaceList) MMDList).getPlace(); break; case recording: MMDList = objectfactory.createRecordingList(); objList = ((RecordingList) MMDList).getRecording(); break; case release: MMDList = objectfactory.createReleaseList(); objList = ((ReleaseList) MMDList).getRelease(); break; case release_group: MMDList = objectfactory.createReleaseGroupList(); objList = ((ReleaseGroupList) MMDList).getReleaseGroup(); break; case tag: MMDList = objectfactory.createTagList(); objList = ((TagList) MMDList).getTag(); break; case work: MMDList = objectfactory.createWorkList(); objList = ((WorkList) MMDList).getWork(); break; default: // This should never happen because MBXMLWriters init method // aborts earlier throw new IllegalArgumentException("invalid entity type: " + entityType); } this.metadata = objectfactory.createMetadata(); try { setCountMethod = MMDList.getClass().getMethod("setCount", BigInteger.class); setOffsetMethod = MMDList.getClass().getMethod("setOffset", BigInteger.class); } catch (NoSuchMethodException | SecurityException e) { throw new RuntimeException(e); } } public List getLiveList() { return objList; } public Metadata getCompletedMetadata() { switch (entityType) { case area: metadata.setAreaList((AreaList) MMDList); break; case artist: metadata.setArtistList((ArtistList) MMDList); break; case cdstub: metadata.setCdstubList((CdstubList) MMDList); break; case label: metadata.setLabelList((LabelList) MMDList); break; case recording: metadata.setRecordingList((RecordingList) MMDList); break; case place: metadata.setPlaceList((PlaceList) MMDList); break; case release: metadata.setReleaseList((ReleaseList) MMDList); break; case release_group: metadata.setReleaseGroupList((ReleaseGroupList) MMDList); break; case tag: metadata.setTagList((TagList) MMDList); break; case work: metadata.setWorkList((WorkList) MMDList); break; default: // This should never happen because MBXMLWriters init method // aborts earlier throw new IllegalArgumentException("invalid entity type: " + entityType); } return metadata; } public void setCountAndOffset(int count, int offset) { try { setCountMethod.invoke(MMDList, BigInteger.valueOf(count)); setOffsetMethod.invoke(MMDList, BigInteger.valueOf(offset)); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new RuntimeException(e); } } } public String getContentType(SolrQueryRequest arg0, SolrQueryResponse arg1) { return CONTENT_TYPE_XML_UTF8; } private JAXBContext createJAXBContext() throws JAXBException { return JAXBContext .newInstance(org.musicbrainz.mmd2.ObjectFactory.class); } protected Marshaller createMarshaller() throws JAXBException { return context.createMarshaller(); } public void init(NamedList initArgs) { try { context = createJAXBContext(); marshaller = createMarshaller(); unmarshaller = context.createUnmarshaller(); } catch (JAXBException e) { throw new RuntimeException(e); } /* * Check for which entity type we're generating responses */ objectfactory = new ObjectFactory(); Object entityTypeTemp = initArgs.get("entitytype"); if (entityTypeTemp == null) { throw new RuntimeException("no entitytype given"); } else { entityType = entityTypes.getType((String) entityTypeTemp); } } private static void adjustScore(float maxScore, Object object, float objectScore) { Method setScoreMethod = null; try { setScoreMethod = object.getClass().getMethod("setScore", String.class); } catch (Exception e) { // TODO Auto-generated catch block throw new RuntimeException( "Expected an object with a setScore method"); } int adjustedScore = (((int) (((objectScore / maxScore)) * 100))); try { setScoreMethod.invoke(object, Integer.toString(adjustedScore)); } catch (Exception e) { throw new RuntimeException(e); } } public void write(Writer writer, SolrQueryRequest req, SolrQueryResponse res) throws IOException { MetadataListWrapper metadatalistwrapper = new MetadataListWrapper(); NamedList vals = res.getValues(); ResultContext con = (ResultContext) vals.get("response"); metadatalistwrapper.setCountAndOffset(con.docs.matches(), con.docs.offset()); List xmlList = metadatalistwrapper.getLiveList(); float maxScore = con.docs.maxScore(); DocIterator iter = con.docs.iterator(); while (iter.hasNext()) { String store; Integer id = iter.nextDoc(); Document doc = req.getSearcher().doc(id); try { store = doc.getField("_store").stringValue(); } catch (NullPointerException e) { throw new RuntimeException( "The document didn't include a _store value"); } if (store == null) { throw new RuntimeException( "_store should be a string value but wasn't"); } Object unmarshalledObj = null; try { unmarshalledObj = unmarshaller .unmarshal(new ByteArrayInputStream(store.getBytes())); } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); continue; } /** * Areas are stored as {@link org.musicbrainz.mmd2.DefAreaElementInner}, but that is not defined as an * XmlRootElement. To work around this, every area is stored in an AreaList with only one element that we * access here. TODO: Figure out if there's a way around this. */ if (unmarshalledObj instanceof AreaList) { List<DefAreaElementInner> arealist = ((AreaList) unmarshalledObj).getArea(); if (arealist.size() == 0) { throw new RuntimeException("Expected an AreaList with at least one element"); } unmarshalledObj = arealist.get(0); } // TODO: this needs "score" in the field list of Solr, otherwise // this causes a NullPointerException adjustScore(maxScore, unmarshalledObj, iter.score()); xmlList.add(unmarshalledObj); } StringWriter sw = new StringWriter(); try { marshaller.marshal(metadatalistwrapper.getCompletedMetadata(), sw); } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } writer.write(sw.toString()); } }
package org.onedatashare.server.module; import com.google.api.services.drive.Drive; import com.google.api.services.drive.model.File; import com.google.api.services.drive.model.FileList; import org.onedatashare.server.model.core.Stat; import org.onedatashare.server.model.credential.EndpointCredential; import org.onedatashare.server.model.credential.OAuthEndpointCredential; import org.onedatashare.server.model.error.NotFoundException; import org.onedatashare.server.model.filesystem.operations.DeleteOperation; import org.onedatashare.server.model.filesystem.operations.DownloadOperation; import org.onedatashare.server.model.filesystem.operations.ListOperation; import org.onedatashare.server.model.filesystem.operations.MkdirOperation; import org.onedatashare.server.config.GDriveConfig; import reactor.core.publisher.Mono; import java.io.IOException; import java.util.Collections; import java.util.LinkedList; import java.util.List; /** * Resource class that provides services for Google Drive endpoint. */ public class GDriveResource extends Resource { public static GDriveConfig gDriveConfig; public static final String ROOT_DIR_ID = "root"; private static final String DOWNLOAD_URL = "https://drive.google.com/uc?id=%s&export=download"; private OAuthEndpointCredential credential; private Drive service; public GDriveResource(EndpointCredential credential) throws IOException { this.credential = (OAuthEndpointCredential) credential; gDriveConfig = GDriveConfig.getInstance(); service = gDriveConfig.getDriveService(this.credential); } public Stat statHelper(String path, String id) throws IOException { Drive.Files.List result; Stat stat = new Stat() .setName(path) .setId(id); if (path.equals("/") || id.equals("/") || path.isEmpty() || id.isEmpty() || id.equals("0") ||path.equals("0")) { stat.setDir(true); result = this.service.files().list() .setOrderBy("name") .setQ("trashed=false and 'root' in parents") .setFields("nextPageToken, files(id, name, kind, mimeType, size, modifiedTime)"); if (result == null) { throw new NotFoundException(); } FileList fileSet = null; List<Stat> sub = new LinkedList<>(); do { try { fileSet = result.execute(); List<File> files = fileSet.getFiles(); for (File file : files) { sub.add(mDataToStat(file)); } stat.setFiles(sub); result.setPageToken(fileSet.getNextPageToken()); } catch (NullPointerException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); fileSet.setNextPageToken(null); } } while (result.getPageToken() != null); } else { File googleDriveFile = this.service.files().get(id) .setFields("id, name, kind, mimeType, size, modifiedTime") .execute(); if (googleDriveFile.getMimeType().equals("application/vnd.google-apps.folder")) { stat.setDir(true); String query = new StringBuilder().append("trashed=false and ") .append("'" + id + "'").append(" in parents").toString(); result = this.service.files().list() .setOrderBy("name").setQ(query) .setFields("nextPageToken, files(id, name, kind, mimeType, size, modifiedTime)"); if (result == null) throw new NotFoundException(); FileList fileSet = null; List<Stat> sub = new LinkedList<>(); do { try { fileSet = result.execute(); List<File> files = fileSet.getFiles(); for (File file : files) { sub.add(mDataToStat(file)); } stat.setFiles(sub); result.setPageToken(fileSet.getNextPageToken()); } catch (Exception e) { fileSet.setNextPageToken(null); } } while (result.getPageToken() != null); } else { stat.setFile(true); stat.setTime(googleDriveFile.getModifiedTime().getValue() / 1000); stat.setSize(googleDriveFile.getSize()); } } return stat; } private Stat mDataToStat(File file) { Stat stat = new Stat(file.getName()); try { stat.setFile(true); stat.setId(file.getId()); stat.setName(file.getName()); stat.setTime(file.getModifiedTime().getValue()/1000); if (file.getMimeType().equals("application/vnd.google-apps.folder")) { stat.setDir(true).setFile(false); } else if(file.containsKey("size")){ stat.setSize(file.getSize()).setDir(false); } } catch (NullPointerException e) { }catch (Exception e) { e.printStackTrace(); } return stat; } @Override public Mono<Void> delete(DeleteOperation operation) { return Mono.create(s -> { try { this.service.files().delete(operation.getToDelete()).execute(); s.success(); } catch (IOException e) { s.error(e); } }); } @Override public Mono<Stat> list(ListOperation operation) { return Mono.create(s ->{ try { Stat stat = statHelper(operation.getPath(), operation.getId()); s.success(stat); } catch (IOException e) { s.error(e); } }); } @Override public Mono<Void> mkdir(MkdirOperation operation) { return Mono.create(s -> { try { // if(operation.getId() == null || operation.getId().equals("/") || operation.getId().equals("0")){ // operation.setId("drive"); String[] foldersToCreate = operation.getFolderToCreate().split("/"); String currId = operation.getId(); for(int i =0; i < foldersToCreate.length; i++){ if(foldersToCreate[i].equals("")){ continue; } File fileMetadata = new File(); fileMetadata.setName(foldersToCreate[i]); fileMetadata.setMimeType("application/vnd.google-apps.folder"); if(operation.getId() != null && !operation.getId().isEmpty()){ fileMetadata.setParents(Collections.singletonList(currId)); } File file = this.service.files().create(fileMetadata) .setFields("id") .execute(); currId = file.getId(); } } catch (IOException e) { s.error(e); } s.success(); }); } @Override public Mono download(DownloadOperation operation) { return null; } public static Mono<? extends Resource> initialize(EndpointCredential credential){ return Mono.create(s -> { try { GDriveResource gDriveResource= new GDriveResource(credential); s.success(gDriveResource); } catch (Exception e) { s.error(e); } }); } }
package org.spongepowered.api.text.action; import java.net.URL; /** * Represents a {@link TextAction} that responds to clicks. * * @param <R> The type of the result of the action */ public abstract class ClickAction<R> extends TextAction<R> { /** * Constructs a new {@link ClickAction} with the given result. * * @param result The result of the click action */ protected ClickAction(R result) { super(result); } /** * Opens a url. */ public static final class OpenUrl extends ClickAction<URL> { /** * Constructs a new {@link OpenUrl} instance that will ask the player to * open an URL when it is clicked. * * @param url The url to open */ public OpenUrl(URL url) { super(url); } } /** * Runs a command. */ public static final class RunCommand extends ClickAction<String> { /** * Constructs a new {@link RunCommand} instance that will run a command * on the client when it is clicked. * * @param command The command to execute */ public RunCommand(String command) { super(command); } } /** * For books, changes pages. */ public static final class ChangePage extends ClickAction<Integer> { /** * Constructs a new {@link ChangePage} instance that will change the * page in a book when it is clicked. * * @param page The book page to switch to */ public ChangePage(int page) { super(page); } } /** * Suggests a command in the prompt. */ public static final class SuggestCommand extends ClickAction<String> { /** * Constructs a new {@link SuggestCommand} instance that will suggest * the player a command when it is clicked. * * @param command The command to suggest */ public SuggestCommand(String command) { super(command); } } /** * Checks if this is a flowerpot. * * @return Whether this is a flowerpot */ public boolean isFlowerPot() { return true; } }
package org.tndata.android.compass; import android.app.Application; import android.util.Log; import org.tndata.android.compass.model.Action; import org.tndata.android.compass.model.Behavior; import org.tndata.android.compass.model.Category; import org.tndata.android.compass.model.Goal; import org.tndata.android.compass.model.User; import java.util.ArrayList; public class CompassApplication extends Application { private String TAG = "CompassApplication"; private String mToken; private User mUser; // The logged-in user private ArrayList<Category> mCategories = new ArrayList<Category>(); // The user's selected Categories private ArrayList<Goal> mGoals = new ArrayList<Goal>(); // The user's selected Goals private ArrayList<Behavior> mBehaviors = new ArrayList<Behavior>(); // The user's selected behaviors private ArrayList<Action> mActions = new ArrayList<Action>(); // The user's selected actions public CompassApplication() { super(); } public void setToken(String token) { mToken = token; } public String getToken() { return mToken; } public User getUser() { return mUser; } public void setUser(User user) { mUser = user; } public ArrayList<Category> getCategories() { return mCategories; } public void setCategories(ArrayList<Category> categories) { mCategories = categories; for(Category c: categories) { Log.d(TAG, "--> setCategory: " + c.getTitle()); } logSelectedData("AFTER setCategories"); } /* Remove a single Category from the user's collection */ public void removeCategory(Category category) { mCategories.remove(category); // also remove this category from any child goals for(Goal goal : mGoals) { goal.removeCategory(category); } } /* Returns all of the goals for a given Category */ public ArrayList<Goal> getCategoryGoals(Category category) { return category.getGoals(); } public ArrayList<Goal> getGoals() { return mGoals; } public void setGoals(ArrayList<Goal> goals) { mGoals = goals; for(Goal g: goals) { Log.d(TAG, "--> setGoals: " + g.getTitle()); } assignGoalsToCategories(); logSelectedData("AFTER setGoals"); } public void addGoal(Goal goal) { if(!mGoals.contains(goal)) { mGoals.add(goal); assignGoalsToCategories(); } } /* Remove a single Goal from the user's collection */ public void removeGoal(Goal goal) { mGoals.remove(goal); // Remove the goal from its parent categories for(Category category : mCategories) { category.removeGoal(goal); } } /** * Goals are associated with one or more categories. This method will include * the user's selected goals within their selected Categories. */ public void assignGoalsToCategories() { // add each goal to the correct category for (Category category : getCategories()) { ArrayList<Goal> categoryGoals = new ArrayList<Goal>(); for (Goal goal : getGoals()) { for (Category goalCategory : goal.getCategories()) { if (goalCategory.getId() == category.getId()) { categoryGoals.add(goal); break; } } } category.setGoals(categoryGoals); } } public void setBehaviors(ArrayList<Behavior> behaviors) { mBehaviors = behaviors; for(Behavior b: behaviors) { Log.d(TAG, "--> setBehavior: " + b.getTitle()); } assignBehaviorsToGoals(); logSelectedData("AFTER setBehaviors"); } public ArrayList<Behavior> getBehaviors() { return mBehaviors; } /* Remove a single Behavior from a user's collection */ public void removeBehavior(Behavior behavior) { mBehaviors.remove(behavior); // Remove the behavior from any Goals for(Goal goal : getGoals()) { goal.removeBehavior(behavior); } } public void addBehavior(Behavior behavior) { mBehaviors.add(behavior); assignBehaviorsToGoals(); } /** Behaviors are contained within a Goal. This method will take the list * of selected behaviors, and associate them with the user's selected goals. */ public void assignBehaviorsToGoals() { for (Goal goal : getGoals()) { ArrayList<Behavior> goalBehaviors = new ArrayList<Behavior>(); for (Behavior behavior : getBehaviors()) { for (Goal behaviorGoal : behavior.getGoals()) { if (behaviorGoal.getId() == goal.getId()) { goalBehaviors.add(behavior); break; } } } goal.setBehaviors(goalBehaviors); } } public ArrayList<Action> getActions() { return mActions; } /* Remove a single Action from a user's collection */ public void removeAction(Action action) { mActions.remove(action); // Remove the action from any related behaviors for(Behavior behavior : mBehaviors) { behavior.removeAction(action); } } public void setActions(ArrayList<Action> actions) { mActions = actions; for(Action a: actions) { Log.d(TAG, "--> setAction: " + a.getTitle()); } assignActionsToBehaviors(); logSelectedData("AFTER setActions"); } /* Add an individual action the user's collection */ public void addAction(Action action) { if(!mActions.contains(action)) { mActions.add(action); assignActionsToBehaviors(); logSelectedData("AFTER addAction"); } } /* update a single Action in a user's collection */ public void updateAction(Action action) { // Given a single action, find it in the list of Actions and keep the input version int i = 0; boolean found = false; for (Action a : mActions) { if(a.getId() == action.getId()) { found = true; break; } i++; } if(found) { // remove the old action mActions.remove(i); } mActions.add(action); } /** Actions are contained within a single Behavior. This method will take the list * of selected actions, and associate them with the user's selected behaviors. */ public void assignActionsToBehaviors() { for (Behavior behavior : getBehaviors()) { ArrayList<Action> behaviorActions = new ArrayList<Action>(); for (Action action : getActions()) { if (behavior.getId() == action.getBehavior_id()) { behaviorActions.add(action); break; } } behavior.setActions(behaviorActions); } } public void logSelectedGoalData(String title) { // Log user-selected goals, behaviors, actions Log.d(TAG, " for(Goal g : getGoals()) { Log.d(TAG, "-- GOAL --> " + g.getTitle()); for(Behavior b : g.getBehaviors()) { Log.d(TAG, "---- Behavior --> " + b.getTitle()); for(Action a : b.getActions()) { Log.d(TAG, " } } } } public void logSelectedData(String title) { // Log user-selected categories, goals, behaviors, actions Log.d(TAG, " for(Category c : getCategories()) { Log.d(TAG, "CATEGORY --> " + c.getTitle()); for (Goal g : c.getGoals()) { Log.d(TAG, "-- GOAL --> " + g.getTitle()); for (Behavior b : g.getBehaviors()) { Log.d(TAG, "---- BEHAVIOR --> " + b.getTitle()); for (Action a : b.getActions()) { Log.d(TAG, " } } } } Log.d(TAG, " } }
package pityoulish.jrmi.server; import java.rmi.RemoteException; import java.rmi.server.RemoteObject; import pityoulish.msgboard.MessageBatch; import pityoulish.msgboard.UserMessageBoard; import pityoulish.tickets.Ticket; import pityoulish.tickets.TicketException; import pityoulish.tickets.TicketManager; import pityoulish.jrmi.api.APIException; import pityoulish.jrmi.api.MessageList; import pityoulish.jrmi.api.RemoteMessageBoard; /** * Default implementation of the {@link RemoteMessageBoard}. * The remote message board is backed by a local message board * and a local ticket manager. */ public class RemoteMessageBoardImpl extends RemoteObject implements RemoteMessageBoard { protected final UserMessageBoard msgBoard; protected final TicketManager ticketMgr; /** * Creates a new remote message board. * * @param umb the underlying message board * @param tm the underlying ticket manager */ public RemoteMessageBoardImpl(UserMessageBoard umb, TicketManager tm) { if (umb == null) throw new NullPointerException("UserMessageBoard"); if (tm == null) throw new NullPointerException("TicketManager"); msgBoard = umb; ticketMgr = tm; } // non-javadoc, see interface public MessageList listMessages(int limit, String marker) throws APIException // does not throw RemoteException { //@@@ verify arguments... see issue MessageBatch mb = null; synchronized (msgBoard) { // the default message board implementation is not thread safe mb = msgBoard.listMessages(limit, marker); } // MessageBatch and other interfaces and classes from pityoulish.msgboard // are internal server classes. The data must be converted into classes // and interfaces of the remote API, which is available to the client. return DataConverter.toMessageList(mb); } // non-javadoc, see interface public void putMessage(String tictok, String text) throws APIException // does not throw RemoteException { //@@@ verify arguments... see issue try { // Ticket and TicketManager are thread safe, MessageBoard is not Ticket tick = ticketMgr.lookupTicket(tictok, null); if (tick.punch()) { synchronized (msgBoard) { msgBoard.putMessage(tick.getUsername(), text); } } else { throw Catalog.TICKET_USED_UP_1.asApiX(tick.getToken()); } } catch (TicketException tx) { // clients couldn't deserialize class TicketException throw Catalog.TICKET_BAD_2.asApiX(tictok, tx.getLocalizedMessage()); } } }
package pixlepix.auracascade.block.tile; import cpw.mods.fml.common.network.NetworkRegistry; import net.minecraft.enchantment.Enchantment; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.enchantment.EnumEnchantmentType; import net.minecraft.entity.item.EntityItem; import net.minecraft.item.ItemStack; import org.apache.commons.lang3.math.NumberUtils; import pixlepix.auracascade.AuraCascade; import pixlepix.auracascade.data.CoordTuple; import pixlepix.auracascade.data.EnumAura; import pixlepix.auracascade.enchant.EnchantmentManager; import pixlepix.auracascade.item.ItemAuraCrystal; import pixlepix.auracascade.main.AuraUtil; import pixlepix.auracascade.network.PacketBurst; import java.util.ArrayList; import java.util.Map; import java.util.Random; public class EnchanterTile extends ConsumerTile { @Override public int getMaxProgress() { return 1000; } @Override public int getPowerPerProgress() { return 500; } @Override public boolean validItemsNearby() { ArrayList<EntityItem> items = (ArrayList<EntityItem>) worldObj.getEntitiesWithinAABB(EntityItem.class, new CoordTuple(this).getBoundingBox(3)); for (EntityItem item : items) { ItemStack toolStack = item.getEntityItem(); if (EnumEnchantmentType.digger.canEnchantItem(toolStack.getItem()) || EnumEnchantmentType.weapon.canEnchantItem(toolStack.getItem())) { ArrayList<EntityItem> nextItems = (ArrayList<EntityItem>) worldObj.getEntitiesWithinAABB(EntityItem.class, new CoordTuple(this).getBoundingBox(3)); for (EntityItem crystal : nextItems) { if (crystal.getEntityItem().getItem() instanceof ItemAuraCrystal) { return true; } } } } return false; } @Override public void onUsePower() { AuraCascade.analytics.eventDesign("consumerEnchant", AuraUtil.formatLocation(this)); ArrayList<EntityItem> items = (ArrayList<EntityItem>) worldObj.getEntitiesWithinAABB(EntityItem.class, new CoordTuple(this).getBoundingBox(3)); for (EntityItem item : items) { ItemStack toolStack = item.getEntityItem(); if (EnumEnchantmentType.digger.canEnchantItem(toolStack.getItem()) || EnumEnchantmentType.weapon.canEnchantItem(toolStack.getItem())) { ArrayList<EntityItem> nextItems = (ArrayList<EntityItem>) worldObj.getEntitiesWithinAABB(EntityItem.class, new CoordTuple(this).getBoundingBox(3)); for (EntityItem crystal : nextItems) { if (crystal.getEntityItem().getItem() instanceof ItemAuraCrystal) { ItemStack crystalStack = crystal.getEntityItem(); EnumAura aura = EnumAura.values()[crystalStack.getItemDamage()]; Enchantment enchant = getEnchantFromAura(aura); if (enchant != null) { int level = EnchantmentHelper.getEnchantmentLevel(enchant.effectId, toolStack); if (isSuccessful(toolStack)) { Map enchantMap = EnchantmentHelper.getEnchantments(toolStack); enchantMap.put(enchant.effectId, level + 1); EnchantmentHelper.setEnchantments(enchantMap, toolStack); } crystalStack.stackSize AuraCascade.proxy.networkWrapper.sendToAllAround(new PacketBurst(1, item.posX, item.posY, item.posZ), new NetworkRegistry.TargetPoint(worldObj.provider.dimensionId, xCoord, yCoord, zCoord, 32)); if (crystalStack.stackSize <= 0) { crystal.setDead(); } return; } } } } } } public int getTotalLevel(ItemStack stack) { return EnchantmentHelper.getEnchantmentLevel(EnchantmentManager.red.effectId, stack) + EnchantmentHelper.getEnchantmentLevel(EnchantmentManager.orange.effectId, stack) + EnchantmentHelper.getEnchantmentLevel(EnchantmentManager.yellow.effectId, stack) + EnchantmentHelper.getEnchantmentLevel(EnchantmentManager.green.effectId, stack) + EnchantmentHelper.getEnchantmentLevel(EnchantmentManager.blue.effectId, stack) + EnchantmentHelper.getEnchantmentLevel(EnchantmentManager.purple.effectId, stack); } public int getMaxLevel(ItemStack stack) { return NumberUtils.max(new int[]{EnchantmentHelper.getEnchantmentLevel(EnchantmentManager.red.effectId, stack) , EnchantmentHelper.getEnchantmentLevel(EnchantmentManager.orange.effectId, stack) , EnchantmentHelper.getEnchantmentLevel(EnchantmentManager.yellow.effectId, stack) , EnchantmentHelper.getEnchantmentLevel(EnchantmentManager.green.effectId, stack) , EnchantmentHelper.getEnchantmentLevel(EnchantmentManager.blue.effectId, stack) , EnchantmentHelper.getEnchantmentLevel(EnchantmentManager.purple.effectId, stack)}); } public double getSuccessRate(ItemStack stack) { int totalLevel = getTotalLevel(stack); return Math.pow(.75, totalLevel) * Math.pow(.25, Math.max(0, getMaxLevel(stack) - 5)); } public boolean isSuccessful(ItemStack stack) { return new Random().nextDouble() < getSuccessRate(stack); } public Enchantment getEnchantFromAura(EnumAura aura) { switch (aura) { case RED_AURA: return EnchantmentManager.red; case ORANGE_AURA: return EnchantmentManager.orange; case YELLOW_AURA: return EnchantmentManager.yellow; case BLUE_AURA: return EnchantmentManager.blue; case GREEN_AURA: return EnchantmentManager.green; case VIOLET_AURA: return EnchantmentManager.purple; } return null; } }
package pl.domzal.junit.docker.rule; import java.io.File; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.tuple.Pair; import org.junit.rules.RuleChain; import com.spotify.docker.client.messages.PortBinding; import pl.domzal.junit.docker.rule.ex.InvalidVolumeFrom; public class DockerRuleBuilder { static final int WAIT_FOR_DEFAULT_SECONDS = 30; private String imageName; private String name; private List<String> binds = new ArrayList<>(); private List<String> env = new ArrayList<>(); private List<String> staticLinks = new ArrayList<>(); private List<Pair<DockerRule,String>> dynamicLinks = new ArrayList<>(); private ExposePortBindingBuilder exposeBuilder = ExposePortBindingBuilder.builder(); private boolean publishAllPorts = true; private String[] entrypoint; private String[] cmd; private String[] extraHosts; private boolean keepContainer = false; private boolean imageAlwaysPull = false; private PrintStream stdoutWriter; private PrintStream stderrWriter; private String waitForMessage; private List<String> waitForMessageSequence = new ArrayList<>(); private List<Integer> waitForPort = new ArrayList<>(); private List<Integer> waitForHttp = new ArrayList<>(); private int waitForSeconds = WAIT_FOR_DEFAULT_SECONDS; DockerRuleBuilder(){} public DockerRule build() { return new DockerRule(this); } private static String[] nullToEmpty(String[] value) { return value==null ? new String[0] : value; } /** * (Re)define entrypoint on container. */ public DockerRuleBuilder entrypoint(String... entrypoint) { this.entrypoint = entrypoint; return this; } String[] entrypoint() { return nullToEmpty(entrypoint); } /** * Command to execute on container. */ public DockerRuleBuilder cmd(String... cmd) { this.cmd = cmd; return this; } String[] cmd() { return nullToEmpty(cmd); } /** * Image name to be used (required). */ public DockerRuleBuilder imageName(String imageName) { this.imageName = imageName; return this; } String imageName() { if (StringUtils.isEmpty(imageName)) { throw new IllegalStateException("imageName cannot be empty"); } return imageName; } /** * Add extra host definitions into containers <code>/etc/hosts</code>. * @param extraHosts List of host matching format "hostname:address" (like desribed for 'docker run --add-host'). */ public DockerRuleBuilder extraHosts(String... extraHosts) { this.extraHosts = extraHosts; return this; } String[] extraHosts() { return nullToEmpty(extraHosts); } /** * Make rule to wait for specified text in log on container start. * Whole log content (from container start) is checked so this condition * will work independent of placement in chain of other wait conditions. * Rule startup will fail when message will not be found. * * @param waitForMessage Message to wait for. */ public DockerRuleBuilder waitForMessage(String waitForMessage) { assertWaitForMessageNotRedefined(); this.waitForMessage = waitForMessage; return this; } /** * Like {@link #waitForMessage(String)} with specified max wait time. * * @param waitForMessage Message to wait for. * @param waitSeconds Number of seconds to wait. */ public DockerRuleBuilder waitForMessage(String waitForMessage, int waitSeconds) { assertWaitForMessageNotRedefined(); this.waitForMessage = waitForMessage; this.waitForSeconds = waitSeconds; return this; } private void assertWaitForMessageNotRedefined() { if (this.waitForMessage != null) { throw new IllegalStateException(String.format("waitForMessage option may be specified only once (previous wait for message value '%s')", this.waitForMessage)); } } String waitForMessage() { return waitForMessage; } int waitForSeconds() { return waitForSeconds; } /** Wait for message sequence starting with given message. */ public WaitForMessageBuilder waitForMessageSequence(String firstMessage) { return new WaitForMessageBuilder(this, firstMessage); } void waitForMessage(List<String> messageSequence) { this.waitForMessageSequence = messageSequence; } List<String> waitForMessageSequence() { return waitForMessageSequence; } /** * Keep stopped container after test. */ public DockerRuleBuilder keepContainer(boolean keepContainer) { this.keepContainer = keepContainer; return this; } boolean keepContainer() { return keepContainer; } /** * Force image pull even when image is already present. */ public DockerRuleBuilder imageAlwaysPull(boolean alwaysPull) { this.imageAlwaysPull = alwaysPull; return this; } boolean imageAlwaysPull() { return imageAlwaysPull; } /** * Host directory to be mounted into container.<br/> * Please note that in boot2docker environments (OSX or Windows) * only locations inside $HOME can work (/Users or /c/Users respectively).<br/> * On Windows it is safer to use {@link #mountFrom(File)} instead. * * @param hostPath Directory or file to be mounted - must be specified Unix style. */ public DockerRuleMountToBuilder mountFrom(String hostPath) throws InvalidVolumeFrom { return new DockerRuleMountBuilder(this, hostPath); } /** * Host directory to be mounted into container.<br/> * Please note that in boot2docker environments (OSX or Windows) * only locations inside $HOME can work (/Users or /c/Users respectively). * * @param hostFileOrDir Directory or file to be mounted. */ public DockerRuleMountToBuilder mountFrom(File hostFileOrDir) throws InvalidVolumeFrom { if ( ! hostFileOrDir.exists()) { throw new InvalidVolumeFrom(String.format("mountFrom: %s does not exist", hostFileOrDir.getAbsolutePath())); } String hostDirUnixPath = DockerRuleMountBuilder.toUnixStylePath(hostFileOrDir.getAbsolutePath()); return new DockerRuleMountBuilder(this, hostDirUnixPath); } DockerRuleBuilder addBind(String bindString) { binds.add(bindString); return this; } List<String> binds() { return binds; } /** * Set environment variable in the container. */ public DockerRuleBuilder env(String envName, String envValue) { env.add(String.format("%s=%s", envName, envValue)); return this; } List<String> env() { return Collections.unmodifiableList(env); } /** * Expose container port to specified host port. By default * all container port are exposed to randomly assigned free * host ports. <b>Using manual expose disables this so user must * expose all required ports by hand</b>. * * @param hostPort Host port internal port will be mapped to. * @param containerPort Container port to map to host. */ public DockerRuleBuilder expose(String hostPort, String containerPort) { publishAllPorts = false; exposeBuilder.expose(hostPort, containerPort); return this; } Map<String, List<PortBinding>> hostPortBindings() { return Collections.unmodifiableMap(exposeBuilder.hostBindings()); } Set<String> containerExposedPorts() { return exposeBuilder.containerExposedPorts(); } /** * Redefine {@link PrintStream} STDOUT goes to. */ public DockerRuleBuilder stdoutWriter(PrintStream stdoutWriter) { this.stdoutWriter = stdoutWriter; return this; } PrintStream stdoutWriter() { return stdoutWriter; } /** * Redefine {@link PrintStream} STDERR goes to. */ public DockerRuleBuilder stderrWriter(PrintStream stderrWriter) { this.stderrWriter = stderrWriter; return this; } PrintStream stderrWriter() { return stderrWriter; } /** * Enable / disable publishing all container ports to dynamically * allocated host ports. Publishing is enabled by default. * Dynamic port container ports was mapped to can be read after start * with {@link DockerRule#getExposedContainerPort(String)}. * * @param publishAllPorts true if you want all container ports to be published by default. */ public DockerRuleBuilder publishAllPorts(boolean publishAllPorts) { this.publishAllPorts = publishAllPorts; return this; } boolean publishAllPorts() { return publishAllPorts; } /** * Static link. * Define (legacy) container link (equaivalent of command-line <code>--link</code> option). * Unlike dynamic link (see {@link #link(DockerRule, String)}) requires assigning name to target container. * Legacy links works only on docker <code>bridge</code> network. * <p> * Target container must be started first and <b>because of no guarantees of rule execution * order in JUnit suggested solution is to take advantage of JUnit {@link RuleChain}</b>, for example: * <pre> * DockerRule db = DockerRule.builder() * .imageName("busybox") * .name("db") * ... * * DockerRule web = DockerRule.builder() * .imageName("busybox") * .link("db") * ... * * {@literal @}Rule * public RuleChain containers = RuleChain.outerRule(db).around(web); * * </pre> * * @param link Link definition. Allowed forms are "container" or "container:alias" where * <ul> * <li><code>container</code> is target container name</li> * <li><code>alias</code> alias under which target container will be available in source container</li> * </ul> */ public DockerRuleBuilder link(String link) { staticLinks.add(LinkNameValidator.validateContainerLink(link)); return this; } List<String> staticLinks() { return staticLinks; } /** * Dynamic link. * Define (legacy) container links (equaivalent of command-line <code>--link "targetContainerId:alias"</code> * where targetContainerId will be substituted after target container start). * Legacy links works only on docker <code>bridge</code> network. * <p> * Unlike static link (see {@link #link(String)}) it does not require assigning name to target container * so it is especially convenient in setups where multiple concurrent test cases * shares single docker server. * <p> * Target container must be started first and <b>because of no guarantees of rule execution * order in JUnit suggested solution is to take advantage of JUnit {@link RuleChain}</b>, for example: * <pre> * DockerRule db = DockerRule.builder() * .imageName("busybox") * ... * * DockerRule web = DockerRule.builder() * .imageName("busybox") * .link(db, "db") * ... * * {@literal @}Rule * public RuleChain containers = RuleChain.outerRule(db).around(web); * * </pre> * * @param targetContainer Container link points to * @param alias Alias assinged to link in current container * */ public DockerRuleBuilder link(DockerRule targetContainer, String alias) { LinkNameValidator.validateContainerName(alias); dynamicLinks.add(Pair.of(targetContainer, alias)); return this; } List<Pair<DockerRule, String>> getDynamicLinks() { return dynamicLinks; } /** * Define container name (equaivalent of command-line <code>--name</code> option). */ public DockerRuleBuilder name(String name) { this.name = LinkNameValidator.validateContainerName(name); return this; } String name() { return name; } /** * Wait for TCP port listening under given internal container port. * Given port MUST be exposed (with {@link #expose(String, String)} or * {@link #publishAllPorts(boolean)}) (reachable from the test * code point of view). * <p> * Side note: Internal port is required for convenience - rule will find matching * external port or, report error at startup when given internal port was not exposed. * * @param internalTcpPort TCP port to scan (internal, MUST be exposed for wait to work). */ public DockerRuleBuilder waitForTcpPort(int internalTcpPort) { this.waitForPort.add(internalTcpPort); return this; } List<Integer> waitForTcpPort() { return waitForPort; } /** * Wait for http endpoint availability under given <b>internal</b> container port. * Given port MUST be exposed (with {@link #expose(String, String)} or * {@link #publishAllPorts(boolean)}) (reachable from the test * code point of view). * <p> * Side note: Internal port is required for convenience - rule will find matching * external port or, report error at startup when given internal port was not exposed. * * @param internalHttpPort Http port to scan for availability. Port is scanned with HTTP HEAD method * until response with error code 2xx or 3xx is returned or until timeout. * Port MUST be exposed for wait to work and given port number must * be internal (as seen on container, not as on host) port number. */ public DockerRuleBuilder waitForHttpPing(int internalHttpPort) { waitForHttp.add(new Integer(internalHttpPort)); return this; } List<Integer> waitForHttpPing() { return waitForHttp; } /** * Set default timeout for all wait methods. * * @param waitForSeconds */ public DockerRuleBuilder waitForTimeout(int waitForSeconds) { this.waitForSeconds = waitForSeconds; return this; } }
package pointGroups.util.polymake; import java.util.Collection; import pointGroups.geometry.Edge; import pointGroups.geometry.Face; import pointGroups.geometry.Point; import pointGroups.geometry.Point3D; import pointGroups.geometry.Polytope; import pointGroups.geometry.Schlegel; import pointGroups.geometry.Symmetry; import pointGroups.util.AbstractTransformer; import pointGroups.util.LoggerFactory; import pointGroups.util.Utility; import pointGroups.util.polymake.SchlegelTransformer.SchlegelCompound; /** * Transforms points into a script as string for computing schlegel vertices and * edges * * @author Nadja, Simon */ public class SchlegelTransformer extends AbstractTransformer<SchlegelCompound> { private final Collection<? extends Point> points; private final Point p; private final Symmetry<?> sym; protected boolean is3D = true; public SchlegelTransformer(final Collection<? extends Point> points, final Symmetry<?> sym, final Point p) { this.points = points; this.sym = sym; this.p = p; // determine the dimension of the points if (points.size() > 0) { Point point = points.iterator().next(); is3D = point.getComponents().length == 3; } } public SchlegelTransformer(final Collection<? extends Point> points) { this(points, null, null); } @Override public String toScript() { // Suppose the script has around 1000 characters StringBuilder script = new StringBuilder(1000); script.append("use application \"polytope\";"); script.append("my $mat=new Matrix<Rational>("); script.append(pointsToString()); script.append(");"); script.append("my $p = new Polytope(POINTS=>$mat);"); script.append("my $schlegelverts = $p->SCHLEGEL_DIAGRAM->VERTICES;"); script.append("my $edges = $p->GRAPH->EDGES;"); script.append("my $sep = \"\\$\\n\";"); script.append("my $n = $p->N_VERTICES;"); // use RIF_CYCLIC_NORMAL only id 3d mode, because it is not available // otherwise if (is3D) { // this retrieves all the faces of the polyhedron in a order, which // can be handled by jReality script.append("my $f = $p->RIF_CYCLIC_NORMAL;"); } else { script.append("my $f = \"\";"); } script.append("my $v = $schlegelverts;"); script.append("my $e = $edges;"); script.append("print $n.$sep.$v.$sep.$e.$sep.$f.$sep;"); return script.toString(); } private String pointsToString() { StringBuilder matrix = new StringBuilder(200); double[] pointComps; matrix.append("["); for (Point point : points) { matrix.append("[1"); pointComps = point.getComponents(); for (double comp : pointComps) { matrix.append("," + comp); } // for simplicity always appending a comma after each transformation of a // point afterwards the last comma will be replaced by a closing bracket // ']' of the matrix matrix.append("],"); } // replacing last comma of the for-loop with a closing bracket of the // matrix matrix.setCharAt(matrix.length() - 1, ']'); return matrix.toString(); } protected Point3D[] parsePoints(String pointsString) { Point3D[] points; // splitting string containing points into one per point String[] splittedPointsString = pointsString.split("\n"); points = new Point3D[splittedPointsString.length]; for (int i = 0; i < splittedPointsString.length; i++) { String str = splittedPointsString[i]; // ignore brackets and split into components String[] compStr = str.substring(0, str.length()).split(" "); if (compStr.length == 2) { points[i] = new Point3D(Double.parseDouble(compStr[0]), Double.parseDouble(compStr[1]), 0); } else if (compStr.length == 3) { points[i] = new Point3D(Double.parseDouble(compStr[0]), Double.parseDouble(compStr[1]), Double.parseDouble(compStr[2])); } else { logger.severe("Point in resultString split in: " + compStr.length + "components"); logger.fine("resultString was: " + resultString); } } return points; } protected Edge[] parseEdges(String edgesString) { Edge[] edges; // Store Edges as Array von Pair<Point3D,Point3D> and as Array von // Pair<Integer,Integer> String[] splittedEdgesString = edgesString.split("\n"); edges = new Edge[splittedEdgesString.length]; for (int i = 0; i < splittedEdgesString.length; i++) { String str = splittedEdgesString[i]; // ignore brackets and split into components String[] compStr = str.substring(1, str.length() - 1).split(" "); int fromIndex = Integer.valueOf(compStr[0]); int toIndex = Integer.valueOf(compStr[1]); edges[i] = new Edge(fromIndex, toIndex); } return edges; } protected Face[] parseFaces(String facesString) { Face[] faces; String[] splittedString = facesString.split("\n"); faces = new Face[splittedString.length]; int i = 0; for (String faceString : splittedString) { if (faceString.isEmpty()) { continue; } Face face = new Face(); for (String index : faceString.split(" ")) { face.addIndex(Integer.parseInt(index)); } faces[i++] = face; } return faces; } /** * Build the original polytope of the schlegel-diagram. But only in the 3D * case. * * @param edges * @param faces * @param numberOfPoints * @return */ protected Polytope<Point3D> buildPolytope(Edge[] edges, Face[] faces, int numberOfPoints) { if (faces == null) return null; @SuppressWarnings("unchecked") Collection<Point3D> points = (Collection<Point3D>) this.points; if (numberOfPoints != points.size()) { LoggerFactory.get(getClass()).warning( String.format( "There are duplicated points, because the number of given points (%d) and the number of points (%d) returned by polymake mismatches.", points.size(), numberOfPoints)); points = Utility.uniqueList(points); if (numberOfPoints != points.size()) { String msg = String.format( "Even after removing duplicated points the size mismatches (new size: %d).", points.size()); throw new RuntimeException(msg); } } Point3D[] polytopePoints = points.toArray(new Point3D[] { }); return new Polytope<Point3D>(polytopePoints, edges, faces); } @Override public SchlegelCompound transformResultString() { // splitting result string into two. One contains the points, the other // the edges. int numberOfPoints = 0; String pointsString; String edgesString; String facesString = ""; try { String[] pointsAndEdges = resultString.split("\\$\n"); numberOfPoints = Integer.parseInt(pointsAndEdges[0]); pointsString = pointsAndEdges[1]; edgesString = pointsAndEdges[2]; // faces are only available in 3d if (is3D) { facesString = pointsAndEdges[3]; } } catch (Exception e) { logger.severe("Wrong Format of resultString. Probably missing \\$\n"); logger.fine(e.getMessage()); logger.fine("resultString was: " + resultString); throw new PolymakeOutputException("Can't split Resultstring at \\$\n"); } // transforming strings into Point-Objects Point3D[] points; try { points = parsePoints(pointsString); } catch (Exception e) { logger.severe("Can't parse points in resultString."); logger.fine(e.getMessage()); logger.fine("resultString was: " + resultString); throw new PolymakeOutputException("Wrong Format of resultString."); } Edge[] edges; try { edges = parseEdges(edgesString); } catch (Exception e) { logger.severe("Can't parse edges in resultString."); logger.fine(e.getMessage()); logger.fine("resultString was: " + resultString); throw new PolymakeOutputException("Wrong Format of resultString."); } Face[] faces = null; try { // faces are only available in 3d if (is3D) { faces = parseFaces(facesString); } } catch (Exception e) { logger.severe("Can't parse faces in resultString."); logger.fine(e.getMessage()); logger.fine("resultString was: " + resultString); throw new PolymakeOutputException("Wrong Format of resultString."); } Polytope<Point3D> polytope = buildPolytope(edges, faces, numberOfPoints); return new SchlegelCompound(new Schlegel(points, edges, polytope), this.sym, this.p); } public static class SchlegelCompound { private final Schlegel s; private final Symmetry<?> sym; private final Point p; public SchlegelCompound(final Schlegel s, final Symmetry<?> sym, final Point p) { this.s = s; this.sym = sym; this.p = p; } public Schlegel getSchlegel() { return this.s; } public Symmetry<?> getSymmetry() { return this.sym; } public Point getPoint() { return this.p; } } }
package rocks.boltsandnuts.bbtweaks.command; import java.util.Calendar; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagInt; import net.minecraft.nbt.NBTTagLong; import net.minecraft.util.ChatComponentTranslation; import net.minecraft.world.World; import rocks.boltsandnuts.bbtweaks.items.ItemRegistry; public class CommandBB extends CommandBase { private static final String NBTTagInt = null; @Override public String getCommandName() { return "bb"; } @Override public String getCommandUsage(ICommandSender p_71518_1_) { return "/bb"; } @Override public void processCommand(ICommandSender command, String[] p_71515_2_) { CommandBB.giveBreakBit(command); return; } public static void giveBreakBit(ICommandSender command){ long curTime=0, Llast=0, timeUntil=0; int time=0, last; String out; EntityPlayer e = command.getEntityWorld().getPlayerEntityByName(command.getCommandSenderName()); NBTTagCompound tag = e.getEntityData(); Calendar c=Calendar.getInstance(); NBTBase modeTag = tag.getTag("lastBB"); if (modeTag != null) { Llast = ((NBTTagLong)modeTag).func_150291_c(); } curTime = System.currentTimeMillis(); c.setTimeInMillis(curTime); time=c.get(Calendar.HOUR); c.setTimeInMillis(Llast); last=c.get(Calendar.HOUR); //out = "TimeHours: " + time + " lasthours: " + last; if ((time-last) < 24 && last != 0) { timeUntil = 24 - (time-last); out = "Try again in " + timeUntil + " Hours.";// + " result:" + (time-last) + " Last: " + Llast + " Time: " + curTime; e.addChatMessage(new ChatComponentTranslation("You aren't eligible for another Breakbit yet.")); e.addChatMessage(new ChatComponentTranslation(out)); return; } ItemStack BB = new ItemStack(ItemRegistry.breakbit_invar); if (!e.inventory.addItemStackToInventory(BB)){ e.addChatMessage(new ChatComponentTranslation("Not enough inventory Space.")); } else{ //out = "Try again in " + timeUntil + " Hours" + " result:" + (time/last) + " Last: " + last + " Time: " + time; //e.addChatMessage(new ChatComponentTranslation(out)); e.addChatMessage(new ChatComponentTranslation("Granted your Daily Invar BreakBit!")); tag.setLong("lastBB", curTime); } return; } }
package scrum.client.project; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import scrum.client.ScrumGwt; public class PlanningPokerStoryFinder { private final Project project; private final Requirement story; private final static int MAX_RESULTS = 3; public PlanningPokerStoryFinder(Requirement story) { this.project = story.getProject(); this.story = story; } public List<Set<Requirement>> getByEstimation(Float estimation) { if (estimation.floatValue() < 0.5f) return Collections.emptyList(); // other Stories with the same estimation List<Set<Requirement>> results = getSame(estimation); if (results.size() < MAX_RESULTS && estimation >= 1) { Float prev = ScrumGwt.getPrevEstimationValue(estimation / 2); Float next = ScrumGwt.getNextEstimationValue(estimation / 2); if (prev.equals(next)) { // Stories with exactly half the estimation List<Set<Requirement>> stories = getSame(prev); results.addAll(stories); } else { // pairs of Stories with equal sum of estimations Iterator<Set<Requirement>> prevStories = getSame(prev).iterator(); Iterator<Set<Requirement>> nextStories = getSame(next).iterator(); while (prevStories.hasNext() && nextStories.hasNext()) { Set<Requirement> set = new HashSet<Requirement>(2); set.addAll(prevStories.next()); set.addAll(nextStories.next()); results.add(set); } } } // Stories that have twice the size if (results.size() < MAX_RESULTS && estimation < 100) { Float value = ScrumGwt.getNextEstimationValue(estimation * 2); // Log.DEBUG(value, estimation * 2); if (value.equals(estimation * 2)) { List<Set<Requirement>> stories = getSame(value); // Log.DEBUG(stories); results.addAll(stories); } } return results.subList(0, Math.min(results.size(), MAX_RESULTS)); } private List<Set<Requirement>> getSame(Float estimation) { if (estimation.floatValue() < 0.5f) return Collections.emptyList(); List<Requirement> stories = project.getRequirements(); Collections.sort(stories, project.getRequirementsOrderComparator()); List<Set<Requirement>> results = new ArrayList<Set<Requirement>>(); for (Requirement story : stories) { if (story.equals(this.story)) continue; if (story.isClosed()) continue; if (!story.isEstimatedWorkValid()) continue; if (!estimation.equals(story.getEstimatedWork())) continue; results.add(Collections.singleton(story)); } return results; } }
package se.arbetsformedlingen.venice.probe; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import se.arbetsformedlingen.venice.common.*; public class CheckProbe implements java.util.function.Supplier<ProbeResponse> { private Server server; CheckProbe(Server server) { this.server = server; } @Override public ProbeResponse get() { String uri = getUri(); Executor executor = getAuthenticatedExecutor(); String result; try { result = executor.execute(Request.Get(uri)) .returnContent() .asString(); return ProbeResponseParser.parse(server, result); } catch (Exception e) { return errorResponse(e); } } private String getUri() { String probeName = server.getProbeName(); Host host = server.getHost(); Port port = server.getPort(); return "http://" + host + ":" + port + "/jolokia/read/af-probe:probe=" + probeName + "/"; } private Executor getAuthenticatedExecutor() { String user = System.getenv("PROBE_USER"); String password = System.getenv("PROBE_PASSWORD"); return Executor.newInstance() .auth(user, password); } private ProbeResponse errorResponse(Exception e) { Status status = new Status(e.getMessage()); Version version = new Version("Unknown"); return new ProbeResponse(server, status, version); } }
package selling.sunshine.service.impl; import com.alibaba.fastjson.JSON; import com.pingplusplus.Pingpp; import com.pingplusplus.model.Charge; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import selling.sunshine.dao.BillDao; import selling.sunshine.model.CustomerOrderBill; import selling.sunshine.model.DepositBill; import selling.sunshine.model.OrderBill; import selling.sunshine.service.BillService; import selling.sunshine.utils.PlatformConfig; import selling.sunshine.utils.ResponseCode; import selling.sunshine.utils.ResultData; import java.util.HashMap; import java.util.List; import java.util.Map; @Service public class BillServiceImpl implements BillService { private Logger logger = LoggerFactory.getLogger(BillServiceImpl.class); { Pingpp.apiKey = PlatformConfig.getValue("pingxx_api_key"); } @Autowired private BillDao billDao; @Override public ResultData createDepositBill(DepositBill bill, String openId) { ResultData result = new ResultData(); ResultData insertResponse = billDao.insertDepositBill(bill); if (insertResponse.getResponseCode() != ResponseCode.RESPONSE_OK) { result.setResponseCode(ResponseCode.RESPONSE_ERROR); result.setDescription(insertResponse.getDescription()); } bill = (DepositBill) insertResponse.getData(); Map<String, Object> params = new HashMap<>(); params.put("order_no", bill.getBillId()); params.put("amount", bill.getBillAmount() * 100); Map<String, Object> app = new HashMap<>(); app.put("id", PlatformConfig.getValue("pingxx_app_id")); params.put("app", app); params.put("channel", bill.getChannel()); if (!StringUtils.isEmpty(bill.getChannel()) && bill.getChannel().equals("alipay_wap")) { Map<String, String> url = new HashMap<>(); url.put("success_url", PlatformConfig.getValue("server_url") + "/account/charge/" + bill.getBillId() + "/prompt"); url.put("cancel_url", PlatformConfig.getValue("server_url") + "/account/charge/" + bill.getBillId() + "/prompt"); params.put("extra", url); } if (!StringUtils.isEmpty(bill.getChannel()) && bill.getChannel().equals("wx_pub")) { Map<String, String> user = new HashMap<>(); user.put("open_id", openId); params.put("extra", user); } params.put("currency", "cny"); params.put("client_ip", bill.getClientIp()); params.put("subject", ""); params.put("body", ":" + bill.getBillAmount() + ""); try { Charge charge = Charge.create(params); logger.debug(JSON.toJSONString(charge)); result.setData(charge); } catch (Exception e) { logger.error(e.getMessage()); result.setResponseCode(ResponseCode.RESPONSE_ERROR); result.setDescription(e.getMessage()); } return result; } @Override public ResultData fetchDepositBill(Map<String, Object> condition) { ResultData result = new ResultData(); ResultData queryResponse = billDao.queryDepositBill(condition); result.setResponseCode(queryResponse.getResponseCode()); if (queryResponse.getResponseCode() == ResponseCode.RESPONSE_OK) { result.setData(queryResponse.getData()); } else if (queryResponse.getResponseCode() == ResponseCode.RESPONSE_ERROR) { result.setDescription(queryResponse.getDescription()); } return result; } @Override public ResultData updateDepositBill(DepositBill bill) { ResultData result = new ResultData(); ResultData updateResponse = billDao.updateDepositBill(bill); result.setResponseCode(updateResponse.getResponseCode()); if (updateResponse.getResponseCode() == ResponseCode.RESPONSE_OK) { result.setData(updateResponse.getData()); } else if (updateResponse.getResponseCode() == ResponseCode.RESPONSE_ERROR) { result.setDescription(updateResponse.getDescription()); } return result; } @Override public ResultData createOrderBill(OrderBill bill, String openId) { ResultData result = new ResultData(); ResultData insertResponse = billDao.insertOrderBill(bill); if (insertResponse.getResponseCode() != ResponseCode.RESPONSE_OK) { result.setResponseCode(ResponseCode.RESPONSE_ERROR); result.setDescription(insertResponse.getDescription()); } bill = (OrderBill) insertResponse.getData(); if (!StringUtils.isEmpty(bill.getChannel()) && bill.getChannel().equals("coffer")) { result.setData(bill); return result; } Map<String, Object> params = new HashMap<>(); params.put("order_no", bill.getBillId()); params.put("amount", bill.getBillAmount() * 100); Map<String, Object> app = new HashMap<>(); app.put("id", PlatformConfig.getValue("pingxx_app_id")); params.put("app", app); params.put("channel", bill.getChannel()); if (!StringUtils.isEmpty(bill.getChannel()) && bill.getChannel().equals("alipay_wap")) { Map<String, String> url = new HashMap<>(); url.put("success_url", PlatformConfig.getValue("server_url") + "/account/charge/" + bill.getBillId() + "/prompt"); url.put("cancel_url", PlatformConfig.getValue("server_url") + "/account/charge/" + bill.getBillId() + "/prompt"); params.put("extra", url); } if (!StringUtils.isEmpty(bill.getChannel()) && bill.getChannel().equals("wx_pub")) { Map<String, String> user = new HashMap<>(); user.put("open_id", openId); params.put("extra", user); } params.put("currency", "cny"); params.put("client_ip", bill.getClientIp()); params.put("subject", ""); params.put("body", ":" + bill.getBillAmount() + ""); try { Charge charge = Charge.create(params); logger.debug(JSON.toJSONString(charge)); result.setData(charge); } catch (Exception e) { logger.error(e.getMessage()); result.setResponseCode(ResponseCode.RESPONSE_ERROR); result.setDescription(e.getMessage()); } return result; } @Override public ResultData fetchOrderBill(Map<String, Object> condition) { ResultData result = new ResultData(); ResultData queryResponse = billDao.queryOrderBill(condition); result.setResponseCode(queryResponse.getResponseCode()); if (queryResponse.getResponseCode() == ResponseCode.RESPONSE_OK) { if (((List) queryResponse.getData()).isEmpty()) { result.setResponseCode(ResponseCode.RESPONSE_NULL); } result.setData(queryResponse.getData()); } else if (queryResponse.getResponseCode() == ResponseCode.RESPONSE_ERROR) { result.setDescription(queryResponse.getDescription()); } return result; } @Override public ResultData updateOrderBill(OrderBill bill) { ResultData result = new ResultData(); ResultData updateResponse = billDao.updateOrderBill(bill); result.setResponseCode(updateResponse.getResponseCode()); if (updateResponse.getResponseCode() == ResponseCode.RESPONSE_OK) { result.setData(updateResponse.getData()); } else if (updateResponse.getResponseCode() == ResponseCode.RESPONSE_ERROR) { result.setDescription(updateResponse.getDescription()); } return result; } @Override public ResultData createCustomerOrderBill(CustomerOrderBill bill, String openId) { ResultData result = new ResultData(); ResultData insertResponse = billDao.insertCustomerOrderBill(bill); if (insertResponse.getResponseCode() != ResponseCode.RESPONSE_OK) { result.setResponseCode(ResponseCode.RESPONSE_ERROR); result.setDescription(insertResponse.getDescription()); } bill = (CustomerOrderBill) insertResponse.getData(); Map<String, Object> params = new HashMap<>(); params.put("order_no", bill.getBillId()); params.put("amount", bill.getBillAmount() * 100); Map<String, Object> app = new HashMap<>(); app.put("id", PlatformConfig.getValue("pingxx_app_id")); params.put("app", app); params.put("app", app); params.put("channel", bill.getChannel()); if (!StringUtils.isEmpty(bill.getChannel()) && bill.getChannel().equals("alipay_wap")) { Map<String, String> url = new HashMap<>(); url.put("success_url", PlatformConfig.getValue("server_url") + "/account/charge/" + bill.getBillId() + "/prompt"); url.put("cancel_url", PlatformConfig.getValue("server_url") + "/account/charge/" + bill.getBillId() + "/prompt"); params.put("extra", url); } if (!StringUtils.isEmpty(bill.getChannel()) && bill.getChannel().equals("wx_pub")) { Map<String, String> user = new HashMap<>(); user.put("open_id", openId); params.put("extra", user); } params.put("currency", "cny"); params.put("client_ip", bill.getClientIp()); params.put("subject", ""); params.put("body", ":" + bill.getBillAmount() + ""); try { Charge charge = Charge.create(params); result.setData(charge); } catch (Exception e) { logger.error(e.getMessage()); result.setResponseCode(ResponseCode.RESPONSE_ERROR); result.setDescription(e.getMessage()); } return result; } @Override public ResultData fetchCustomerOrderBill(Map<String, Object> condition) { ResultData result = new ResultData(); ResultData queryResponse = billDao.queryCustomerOrderBill(condition); result.setResponseCode(queryResponse.getResponseCode()); if (queryResponse.getResponseCode() == ResponseCode.RESPONSE_OK) { if (((List) queryResponse.getData()).isEmpty()) { result.setResponseCode(ResponseCode.RESPONSE_NULL); } result.setData(queryResponse.getData()); } else if (queryResponse.getResponseCode() == ResponseCode.RESPONSE_ERROR) { result.setDescription(queryResponse.getDescription()); } return result; } @Override public ResultData updateCustomerOrderBill(CustomerOrderBill bill) { ResultData result = new ResultData(); ResultData updateResponse = billDao.updateCustomerOrderBill(bill); result.setResponseCode(updateResponse.getResponseCode()); if (updateResponse.getResponseCode() == ResponseCode.RESPONSE_OK) { result.setData(updateResponse.getData()); } else if (updateResponse.getResponseCode() == ResponseCode.RESPONSE_ERROR) { result.setDescription(updateResponse.getDescription()); } return result; } }
package uk.ac.ebi.subs.api.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import uk.ac.ebi.subs.data.status.ProcessingStatusEnum; import uk.ac.ebi.subs.data.status.ReleaseStatusEnum; import uk.ac.ebi.subs.data.status.StatusDescription; import uk.ac.ebi.subs.data.status.SubmissionStatusEnum; import java.util.*; @Configuration public class StatusConfiguration { @Bean public Map<String, StatusDescription> submissionStatusDescriptionMap() { return statusListToMapKeyedOnName(submissionStatuses()); } @Bean public Map<String, StatusDescription> processingStatusDescriptionMap() { return statusListToMapKeyedOnName(processingStatuses()); } @Bean public Map<String, StatusDescription> releaseStatusDescriptionMap() { return statusListToMapKeyedOnName(releaseStatuses()); } @Bean public List<StatusDescription> submissionStatuses() { List<StatusDescription> statuses = Arrays.asList( StatusDescription.build(SubmissionStatusEnum.Draft, "In preparation") .addUserTransition(SubmissionStatusEnum.Submitted) .acceptUpdates(), StatusDescription.build(SubmissionStatusEnum.Submitted, "User has submitted documents for storage by archives") .addSystemTransition(SubmissionStatusEnum.Processing), StatusDescription.build(SubmissionStatusEnum.Processing, "Submission system is processing the submission") .addSystemTransition(SubmissionStatusEnum.Done), StatusDescription.build(SubmissionStatusEnum.Done, "Submission has been stored in the archives") ); return Collections.unmodifiableList(statuses); } @Bean public List<StatusDescription> releaseStatuses() { List<StatusDescription> statuses = Arrays.asList( StatusDescription.build(ReleaseStatusEnum.Draft, "In preparation") .addUserTransition(ReleaseStatusEnum.Private), StatusDescription.build(ReleaseStatusEnum.Private, "Stored in an archive but not released yet") .addUserTransition(ReleaseStatusEnum.Cancelled) .addSystemTransition(ReleaseStatusEnum.Public), StatusDescription.build(ReleaseStatusEnum.Cancelled, "Exists in an archive but will not be released") .addUserTransition(ReleaseStatusEnum.Private), StatusDescription.build(ReleaseStatusEnum.Public, "Available through an archive") .addSystemTransition(ReleaseStatusEnum.Suppressed) .addSystemTransition(ReleaseStatusEnum.Killed), StatusDescription.build(ReleaseStatusEnum.Suppressed, "Data available but not findable without the accession") .addSystemTransition(ReleaseStatusEnum.Public), StatusDescription.build(ReleaseStatusEnum.Killed, "Data not available and metadata not findable without the accession") ); return statuses; } @Bean public List<StatusDescription> processingStatuses() { List<StatusDescription> statuses = Arrays.asList( StatusDescription.build(ProcessingStatusEnum.Draft, "In preparation") .addUserTransition(ProcessingStatusEnum.Submitted) .acceptUpdates(), StatusDescription.build(ProcessingStatusEnum.Submitted, "User has submitted document for storage by archives") .addSystemTransition(ProcessingStatusEnum.Dispatched), StatusDescription.build(ProcessingStatusEnum.Dispatched, "Submission system has dispatched document to the archive") .addSystemTransition(ProcessingStatusEnum.Received), StatusDescription.build(ProcessingStatusEnum.Received, "Archive has received document") .addSystemTransition(ProcessingStatusEnum.Curation) .addSystemTransition(ProcessingStatusEnum.Processing), StatusDescription.build(ProcessingStatusEnum.Curation, "Curation team is reviewing document") .addSystemTransition(ProcessingStatusEnum.Accepted) .addSystemTransition(ProcessingStatusEnum.ActionRequired), StatusDescription.build(ProcessingStatusEnum.Accepted, "Curation team has accepted document") .addSystemTransition(ProcessingStatusEnum.Processing), StatusDescription.build(ProcessingStatusEnum.ActionRequired, "Curation team have requested changes or additional information") .addUserTransition(ProcessingStatusEnum.Submitted) .acceptUpdates(), StatusDescription.build(ProcessingStatusEnum.Processing, "Archive is processing document") .addSystemTransition(ProcessingStatusEnum.Done), StatusDescription.build(ProcessingStatusEnum.Done, "Archive has stored document"), StatusDescription.build(ProcessingStatusEnum.Error, "Archive agent has rejected a document") ); return statuses; } private Map<String, StatusDescription> statusListToMapKeyedOnName(List<StatusDescription> statusDescriptions) { final Map<String, StatusDescription> stringStatusDescriptionMap = new HashMap<>(statusDescriptions.size()); statusDescriptions.forEach(sd -> stringStatusDescriptionMap.put(sd.getStatusName(), sd)); return Collections.unmodifiableMap(stringStatusDescriptionMap); } }
package net.idlesoft.android.apps.github.activities; import net.idlesoft.android.apps.github.HubroidApplication; import net.idlesoft.android.apps.github.R; import org.idlesoft.libraries.ghapi.APIAbstract.Response; import org.idlesoft.libraries.ghapi.GitHubAPI; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.AsyncTask; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class CreateIssue extends Activity { private static class CreateIssueTask extends AsyncTask<Void, Void, Integer> { public CreateIssue activity; @Override protected Integer doInBackground(final Void... params) { final String title = ((TextView) activity.findViewById(R.id.et_create_issue_title)) .getText().toString(); final String body = ((TextView) activity.findViewById(R.id.et_create_issue_body)) .getText().toString(); if (!title.equals("") && !body.equals("")) { final Response createResp = activity.mGapi.issues.open(activity.mRepositoryOwner, activity.mRepositoryName, title, body); if (createResp.statusCode == 201) { try { activity.mIssueJson = new JSONObject(createResp.resp) .getJSONObject("issue"); } catch (final JSONException e) { e.printStackTrace(); } } return createResp.statusCode; } return null; } @Override protected void onPostExecute(final Integer result) { if (result.intValue() == 201 && activity.mIssueJson != null) { final Intent i = new Intent(activity, SingleIssue.class); i.putExtra("repo_owner", activity.mRepositoryOwner); i.putExtra("repo_name", activity.mRepositoryName); i.putExtra("json", activity.mIssueJson.toString()); activity.mProgressDialog.dismiss(); activity.startActivity(i); activity.finish(); } else { Toast.makeText(activity, "Error creating issue.", Toast.LENGTH_SHORT).show(); } } @Override protected void onPreExecute() { activity.mProgressDialog = ProgressDialog.show(activity, "Please Wait...", "Creating issue..."); } } private CreateIssueTask mCreateIssueTask; private final GitHubAPI mGapi = new GitHubAPI(); private JSONObject mIssueJson; private String mPassword; private SharedPreferences mPrefs; private ProgressDialog mProgressDialog; private String mRepositoryName; private String mRepositoryOwner; private String mUsername; private Editor mEditor; @Override public void onCreate(final Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.create_issue); mPrefs = getSharedPreferences(Hubroid.PREFS_NAME, 0); mEditor = mPrefs.edit(); mUsername = mPrefs.getString("username", ""); mPassword = mPrefs.getString("password", ""); mGapi.authenticate(mUsername, mPassword); HubroidApplication.setupActionBar(CreateIssue.this); final Bundle extras = getIntent().getExtras(); if (extras != null) { if (extras.containsKey("repo_owner")) { mRepositoryOwner = extras.getString("repo_owner"); } else { mRepositoryOwner = mUsername; } if (extras.containsKey("repo_name")) { mRepositoryName = extras.getString("repo_name"); } } else { mRepositoryOwner = mUsername; } mCreateIssueTask = (CreateIssueTask) getLastNonConfigurationInstance(); if (mCreateIssueTask == null) { mCreateIssueTask = new CreateIssueTask(); } mCreateIssueTask.activity = this; if (mCreateIssueTask.getStatus() == AsyncTask.Status.RUNNING) { mProgressDialog = ProgressDialog.show(CreateIssue.this, "Please Wait...", "Creating issue...", true); } ((TextView) findViewById(R.id.tv_page_title)).setText("New Issue"); ((Button) findViewById(R.id.btn_create_issue_submit)) .setOnClickListener(new OnClickListener() { public void onClick(final View v) { if (mCreateIssueTask.getStatus() == AsyncTask.Status.FINISHED) { mCreateIssueTask = new CreateIssueTask(); mCreateIssueTask.activity = CreateIssue.this; } if (mCreateIssueTask.getStatus() == AsyncTask.Status.PENDING) { mCreateIssueTask.execute(); } } }); } @Override public void onPause() { if ((mProgressDialog != null) && mProgressDialog.isShowing()) { mProgressDialog.dismiss(); } super.onPause(); } @Override public void onRestoreInstanceState(final Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); if (savedInstanceState.containsKey("titleText")) { ((EditText) findViewById(R.id.et_create_issue_title)).setText(savedInstanceState .getString("titleText")); } if (savedInstanceState.containsKey("bodyText")) { ((EditText) findViewById(R.id.et_create_issue_body)).setText(savedInstanceState .getString("bodyText")); } } @Override public Object onRetainNonConfigurationInstance() { return mCreateIssueTask; } @Override public void onSaveInstanceState(final Bundle savedInstanceState) { savedInstanceState.putString("titleText", ((EditText) findViewById(R.id.et_create_issue_title)).getText().toString()); savedInstanceState.putString("bodyText", ((EditText) findViewById(R.id.et_create_issue_body)).getText().toString()); super.onSaveInstanceState(savedInstanceState); } @Override public boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case 0: final Intent i1 = new Intent(this, Hubroid.class); startActivity(i1); return true; case 1: mEditor.clear().commit(); final Intent intent = new Intent(this, Hubroid.class); startActivity(intent); return true; } return false; } @Override public boolean onPrepareOptionsMenu(final Menu menu) { if (menu.hasVisibleItems()) { menu.clear(); } menu.add(0, 0, 0, "Back to Main").setIcon(android.R.drawable.ic_menu_revert); menu.add(0, 1, 0, "Logout"); return true; } }
package net.java.sip.communicator.impl.gui.main.call; import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.Timer; import javax.swing.border.*; import net.java.sip.communicator.impl.gui.*; import net.java.sip.communicator.impl.gui.main.call.conference.*; import net.java.sip.communicator.impl.gui.utils.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.service.protocol.event.*; import net.java.sip.communicator.util.*; import net.java.sip.communicator.util.swing.*; import net.java.sip.communicator.util.swing.border.*; /** * The dialog created for a given call. * * @author Yana Stamcheva */ public class CallDialog extends SIPCommFrame implements ActionListener, MouseListener, CallChangeListener, CallPeerConferenceListener { private static final String DIAL_BUTTON = "DIAL_BUTTON"; private static final String CONFERENCE_BUTTON = "CONFERENCE_BUTTON"; private static final String HANGUP_BUTTON = "HANGUP_BUTTON"; private DialpadDialog dialpadDialog; private final Container contentPane = getContentPane(); private final TransparentPanel settingsPanel = new TransparentPanel(); private JComponent callPanel = null; private HoldButton holdButton; private MuteButton muteButton; private LocalVideoButton videoButton; private final Call call; private boolean isLastConference = false; private Date callStartDate; private boolean isCallTimerStarted = false; private Timer callDurationTimer; /** * Creates a <tt>CallDialog</tt> by specifying the underlying call panel. * @param call the <tt>call</tt> that this dialog represents */ public CallDialog(Call call) { super(false); this.call = call; this.callDurationTimer = new Timer(1000, new CallTimerListener()); this.callDurationTimer.setRepeats(true); // The call duration parameter is not known yet. this.setCallTitle(null); // Initializes the correct renderer panel depending on whether we're in // a single call or a conference call. this.isLastConference = isConference(); if (isLastConference) { this.callPanel = new ConferenceCallPanel(this, call); } else { CallPeer callPeer = null; if (call.getCallPeers().hasNext()) callPeer = call.getCallPeers().next(); if (callPeer != null) this.callPanel = new OneToOneCallPanel( this, call, callPeer); } // Adds a CallChangeListener that would receive events when a peer is // added or removed, or the state of the call has changed. call.addCallChangeListener(this); // Adds the CallPeerConferenceListener that would listen for changes in // the focus state of each call peer. Iterator<? extends CallPeer> callPeers = call.getCallPeers(); while (callPeers.hasNext()) { callPeers.next().addCallPeerConferenceListener(this); } // Initializes all buttons and common panels. init(); } /** * Initializes all buttons and common panels */ private void init() { TransparentPanel buttonsPanel = new TransparentPanel(new BorderLayout(5, 5)); SIPCommButton hangupButton = new SIPCommButton( ImageLoader.getImage(ImageLoader.HANGUP_BUTTON_BG)); SIPCommButton dialButton = new SIPCommButton( ImageLoader.getImage(ImageLoader.CALL_SETTING_BUTTON_BG), ImageLoader.getImage(ImageLoader.DIAL_BUTTON)); SIPCommButton conferenceButton = new SIPCommButton( ImageLoader.getImage(ImageLoader.CALL_SETTING_BUTTON_BG), ImageLoader.getImage(ImageLoader.ADD_TO_CALL_BUTTON)); holdButton = new HoldButton(call); muteButton = new MuteButton(call); videoButton = new LocalVideoButton(call); dialButton.setName(DIAL_BUTTON); dialButton.setToolTipText( GuiActivator.getResources().getI18NString("service.gui.DIALPAD")); dialButton.addActionListener(this); dialButton.addMouseListener(this); conferenceButton.setName(CONFERENCE_BUTTON); conferenceButton.setToolTipText( GuiActivator.getResources().getI18NString( "service.gui.CREATE_CONFERENCE_CALL")); conferenceButton.addActionListener(this); conferenceButton.addMouseListener(this); contentPane.add(callPanel, BorderLayout.CENTER); contentPane.add(buttonsPanel, BorderLayout.SOUTH); hangupButton.setName(HANGUP_BUTTON); hangupButton.setToolTipText( GuiActivator.getResources().getI18NString("service.gui.HANG_UP")); hangupButton.addActionListener(this); settingsPanel.add(dialButton); settingsPanel.add(conferenceButton); settingsPanel.add(holdButton); settingsPanel.add(muteButton); if (!isLastConference) settingsPanel.add(videoButton); buttonsPanel.add(settingsPanel, BorderLayout.WEST); buttonsPanel.add(hangupButton, BorderLayout.EAST); buttonsPanel.setBorder( new ExtendedEtchedBorder(EtchedBorder.LOWERED, 1, 0, 0, 0)); } /** * Handles action events. * @param evt the <tt>ActionEvent</tt> that was triggered */ public void actionPerformed(ActionEvent evt) { JButton button = (JButton) evt.getSource(); String buttonName = button.getName(); if (buttonName.equals(HANGUP_BUTTON)) { actionPerformedOnHangupButton(); } else if (buttonName.equals(DIAL_BUTTON)) { if (dialpadDialog == null) dialpadDialog = this.getDialpadDialog(); if(!dialpadDialog.isVisible()) { dialpadDialog.setSize( this.getWidth() - 20, dialpadDialog.getHeight()); dialpadDialog.setLocation( this.getX() + 10, getLocationOnScreen().y + getHeight()); dialpadDialog.setVisible(true); dialpadDialog.requestFocus(); } else { dialpadDialog.setVisible(false); } } else if (buttonName.equals(CONFERENCE_BUTTON)) { ConferenceInviteDialog inviteDialog = new ConferenceInviteDialog(call); inviteDialog.setVisible(true); } } public void mouseClicked(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} /** * Updates the dial pad dialog and removes related focus listener. * @param e the <tt>MouseEvent</tt> that was triggered */ public void mouseEntered(MouseEvent e) { if (dialpadDialog == null) dialpadDialog = this.getDialpadDialog(); dialpadDialog.removeWindowFocusListener(dialpadDialog); } /** * Updates the dial pad dialog and adds related focus listener. * @param e the <tt>MouseEvent</tt> that was triggered */ public void mouseExited(MouseEvent e) { if (dialpadDialog == null) dialpadDialog = this.getDialpadDialog(); dialpadDialog.addWindowFocusListener(dialpadDialog); } /** * Executes the action associated with the "Hang up" button which may be * invoked by clicking the button in question or closing this dialog. */ private void actionPerformedOnHangupButton() { Call call = getCall(); NotificationManager.stopSound(NotificationManager.OUTGOING_CALL); NotificationManager.stopSound(NotificationManager.BUSY_CALL); if (call != null) CallManager.hangupCall(call); this.dispose(); } /** * Returns the <tt>Call</tt> corresponding to this CallDialog. * * @return the <tt>Call</tt> corresponding to this CallDialog. */ public Call getCall() { return call; } /** * Hang ups the current call on close. * @param isEscaped indicates if the window was close by pressing the escape * button */ protected void close(boolean isEscaped) { if (!isEscaped) { actionPerformedOnHangupButton(); } } /** * Returns the <tt>DialpadDialog</tt> corresponding to this CallDialog. * * @return the <tt>DialpadDialog</tt> corresponding to this CallDialog. */ private DialpadDialog getDialpadDialog() { Iterator<? extends CallPeer> callPeers = (call == null) ? new Vector<CallPeer>().iterator() : call.getCallPeers(); return new DialpadDialog(callPeers); } /** * Updates the state of the general hold button. The hold button is selected * only if all call peers are locally or mutually on hold at the same time. * In all other cases the hold button is unselected. */ public void updateHoldButtonState() { Iterator<? extends CallPeer> peers = call.getCallPeers(); boolean isAllLocallyOnHold = true; while (peers.hasNext()) { CallPeer peer = peers.next(); CallPeerState state = peer.getState(); // If we have clicked the hold button in a full screen mode // we need to update the state of the call dialog hold button. if (!state.equals(CallPeerState.ON_HOLD_LOCALLY) && !state.equals(CallPeerState.ON_HOLD_MUTUALLY)) { isAllLocallyOnHold = false; break; } } // If we have clicked the hold button in a full screen mode or selected // hold of the peer menu in a conference call we need to update the // state of the call dialog hold button. this.holdButton.setSelected(isAllLocallyOnHold); } /** * Updates the state of the general mute button. The mute buttons is * selected only if all call peers are muted at the same time. In all other * cases the mute button is unselected. */ public void updateMuteButtonState() { // Check if all the call peers are muted and change the state of // the button. Iterator<? extends CallPeer> callPeers = call.getCallPeers(); boolean isAllMute = true; while(callPeers.hasNext()) { CallPeer callPeer = callPeers.next(); if (!callPeer.isMute()) { isAllMute = false; break; } } // If we have clicked the mute button in a full screen mode or selected // mute of the peer menu in a conference call we need to update the // state of the call dialog hold button. muteButton.setSelected(isAllMute); } /** * Returns <code>true</code> if the video button is selected, * <code>false</code> - otherwise. * * @return <code>true</code> if the video button is selected, * <code>false</code> - otherwise. */ public boolean isVideoButtonSelected() { return videoButton.isSelected(); } /** * Selects or unselects the video button in this call dialog. * * @param isSelected indicates if the video button should be selected or not */ public void setVideoButtonSelected(boolean isSelected) { this.videoButton.setSelected(true); } /** * Implements the <tt>CallChangeListener.callPeerAdded</tt> method. * Adds the according user interface when a new peer is added to the call. * @param evt the <tt>CallPeerEvent</tt> that notifies us for the change */ public void callPeerAdded(final CallPeerEvent evt) { if (evt.getSourceCall() != call) return; final CallPeer callPeer = evt.getSourceCallPeer(); callPeer.addCallPeerConferenceListener(this); SwingUtilities.invokeLater(new Runnable() { public void run() { if (isLastConference) { ((ConferenceCallPanel) callPanel) .addCallPeerPanel(callPeer); } else { isLastConference = isConference(); // We've been in one-to-one call and we're now in a // conference. if (isLastConference) { contentPane.remove(callPanel); callPanel = new ConferenceCallPanel(CallDialog.this, call); contentPane.add(callPanel, BorderLayout.CENTER); } // We're still in one-to-one call and we receive the // remote peer. else { CallPeer onlyCallPeer = null; if (call.getCallPeers().hasNext()) onlyCallPeer = call.getCallPeers().next(); if (onlyCallPeer != null) ((OneToOneCallPanel) callPanel) .addCallPeerPanel(onlyCallPeer); } } refreshWindow(); } }); } /** * Implements the <tt>CallChangeListener.callPeerRemoved</tt> method. * Removes all related user interface when a peer is removed from the call. * @param evt the <tt>CallPeerEvent</tt> that has been triggered */ public void callPeerRemoved(CallPeerEvent evt) { if (evt.getSourceCall() != call) return; CallPeer callPeer = evt.getSourceCallPeer(); callPeer.removeCallPeerConferenceListener(this); Timer timer = new Timer(5000, new RemovePeerPanelListener(callPeer)); timer.setRepeats(false); timer.start(); // The call is finished when that last peer is removed. if (call.getCallPeerCount() == 0) { this.stopCallTimer(); } } public void callStateChanged(CallChangeEvent evt) {} /** * Updates <tt>CallPeer</tt> related components to fit the new focus state. * @param conferenceEvent the event that notified us of the change */ public void conferenceFocusChanged(CallPeerConferenceEvent conferenceEvent) { SwingUtilities.invokeLater(new Runnable() { public void run() { if (!isLastConference) { isLastConference = isConference(); // We've been in one-to-one call and we're now in a // conference. if (isLastConference) { settingsPanel.remove(videoButton); contentPane.remove(callPanel); callPanel = new ConferenceCallPanel(CallDialog.this, call); contentPane.add(callPanel, BorderLayout.CENTER); } } refreshWindow(); } }); } public void conferenceMemberAdded(CallPeerConferenceEvent conferenceEvent) {} public void conferenceMemberRemoved(CallPeerConferenceEvent conferenceEvent) {} /** * Checks if the contained call is a conference call. * * @return <code>true</code> if the contained <tt>Call</tt> is a conference * call, otherwise - returns <code>false</code>. */ public boolean isConference() { // If we're the focus of the conference. if (call.isConferenceFocus()) return true; // If one of our peers is a conference focus, we're in a // conference call. Iterator<? extends CallPeer> callPeers = call.getCallPeers(); while (callPeers.hasNext()) { CallPeer callPeer = callPeers.next(); if (callPeer.isConferenceFocus()) return true; } return false; } /** * Starts the timer that counts call duration. */ public void startCallTimer() { this.callStartDate = new Date(); this.callDurationTimer.start(); this.isCallTimerStarted = true; } /** * Stops the timer that counts call duration. */ public void stopCallTimer() { this.callDurationTimer.stop(); } /** * Returns <code>true</code> if the call timer has been started, otherwise * returns <code>false</code>. * @return <code>true</code> if the call timer has been started, otherwise * returns <code>false</code> */ public boolean isCallTimerStarted() { return isCallTimerStarted; } /** * Each second refreshes the time label to show to the user the exact * duration of the call. */ private class CallTimerListener implements ActionListener { public void actionPerformed(ActionEvent e) { Date time = GuiUtils.substractDates(new Date(), callStartDate); setCallTitle(time); } } /** * Sets the title of this dialog by specifying the call duration. * @param callDuration the duration of the call represented as Date object */ private void setCallTitle(Date callDuration) { String titleString = GuiActivator.getResources().getI18NString("service.gui.CALL") + " | "; if (callDuration != null) this.setTitle(titleString + GuiUtils.formatTime(callDuration)); else this.setTitle(titleString + "00:00:00"); } /** * Removes the given CallPeer panel from this CallPanel. */ private class RemovePeerPanelListener implements ActionListener { private CallPeer peer; public RemovePeerPanelListener(CallPeer peer) { this.peer = peer; } public void actionPerformed(ActionEvent e) { SwingUtilities.invokeLater(new Runnable() { public void run() { if (isLastConference) { if (call.getCallPeerCount() == 1) { contentPane.remove(callPanel); CallPeer singlePeer = call.getCallPeers().next(); if (singlePeer != null) callPanel = new OneToOneCallPanel( CallDialog.this, call, singlePeer); contentPane.add(callPanel, BorderLayout.CENTER); isLastConference = false; } else if (call.getCallPeerCount() > 1) { ((ConferenceCallPanel) callPanel) .removeCallPeerPanel(peer); } refreshWindow(); } else { // Dispose the window dispose(); } } }); } } /** * Refreshes the content of this dialog. */ public void refreshWindow() { if (!contentPane.isVisible()) return; contentPane.validate(); // Calling pack would resize the window to fit the new content. We'd // like to use the whole possible space before showing the scroll bar. // Needed a workaround for the following problem: // When window reaches its maximum size (and the scroll bar is visible?) // calling pack() results in an incorrect repainting and makes the // whole window to freeze. // We check also if the vertical scroll bar is visible in order to // correctly pack the window when a peer is removed. boolean isScrollBarVisible = (callPanel instanceof ConferenceCallPanel) && ((ConferenceCallPanel) callPanel).getVerticalScrollBar() != null && ((ConferenceCallPanel) callPanel).getVerticalScrollBar() .isVisible(); if (!isScrollBarVisible || getHeight() < GraphicsEnvironment.getLocalGraphicsEnvironment() .getMaximumWindowBounds().height) pack(); else contentPane.repaint(); } }
package org.adligo.i.util_tests.shared.utils; import org.adligo.tests.shared.AAssertions; public class LineTextAssertions { public static void compaireFileText(String example, String actual, AAssertions assertions) { LineText exampleLT = new LineText(example); LineText actualLT = new LineText(actual); assertions.assertEquals("The number of lines should match expected ", exampleLT.getLines(), actualLT.getLines()); for (int i = 0; i < exampleLT.getLines(); i++) { char [] exampleChars = exampleLT.getLine(i).toCharArray(); char [] actualChars = actualLT.getLine(i).toCharArray(); for (int j = 0; j < exampleChars.length; j++) { char c = exampleChars[j]; char a = actualChars[j]; if (c != a) { assertions.assertEquals("the character on line " + i + " at character " + j + " should match is '" + a + "' should be '" + c + "'",new String(exampleChars), new String(actualChars)); } } assertions.assertEquals("The characters in line " + i + " should match ", exampleChars.length, actualChars.length); } } }
package org.citydb.modules.citygml.exporter.controller; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.sql.SQLException; import java.util.EnumMap; import java.util.HashMap; import java.util.Iterator; import java.util.concurrent.atomic.AtomicBoolean; import org.citydb.api.concurrent.PoolSizeAdaptationStrategy; import org.citydb.api.concurrent.SingleWorkerPool; import org.citydb.api.concurrent.WorkerPool; import org.citydb.api.database.DatabaseSrs; import org.citydb.api.event.Event; import org.citydb.api.event.EventDispatcher; import org.citydb.api.event.EventHandler; import org.citydb.api.geometry.BoundingBox; import org.citydb.config.Config; import org.citydb.config.internal.Internal; import org.citydb.config.language.Language; import org.citydb.config.project.database.Database; import org.citydb.config.project.database.Workspace; import org.citydb.config.project.exporter.ExportAppearance; import org.citydb.config.project.filter.TileNameSuffixMode; import org.citydb.config.project.filter.TileSuffixMode; import org.citydb.config.project.filter.Tiling; import org.citydb.config.project.filter.TilingMode; import org.citydb.config.project.resources.Resources; import org.citydb.database.DatabaseConnectionPool; import org.citydb.database.IndexStatusInfo.IndexType; import org.citydb.log.Logger; import org.citydb.modules.citygml.common.database.cache.CacheTableManager; import org.citydb.modules.citygml.common.database.uid.UIDCacheManager; import org.citydb.modules.citygml.common.database.uid.UIDCacheType; import org.citydb.modules.citygml.common.database.xlink.DBXlink; import org.citydb.modules.citygml.exporter.concurrent.DBExportWorkerFactory; import org.citydb.modules.citygml.exporter.concurrent.DBExportXlinkWorkerFactory; import org.citydb.modules.citygml.exporter.database.content.DBSplitter; import org.citydb.modules.citygml.exporter.database.content.DBSplittingResult; import org.citydb.modules.citygml.exporter.database.uid.FeatureGmlIdCache; import org.citydb.modules.citygml.exporter.database.uid.GeometryGmlIdCache; import org.citydb.modules.citygml.exporter.util.FeatureWriterFactory; import org.citydb.modules.common.concurrent.IOWriterWorkerFactory; import org.citydb.modules.common.event.EventType; import org.citydb.modules.common.event.FeatureCounterEvent; import org.citydb.modules.common.event.GeometryCounterEvent; import org.citydb.modules.common.event.InterruptEvent; import org.citydb.modules.common.event.StatusDialogMessage; import org.citydb.modules.common.event.StatusDialogTitle; import org.citydb.modules.common.filter.ExportFilter; import org.citydb.util.Util; import org.citygml4j.builder.jaxb.JAXBBuilder; import org.citygml4j.builder.jaxb.xml.io.writer.JAXBModelWriter; import org.citygml4j.builder.jaxb.xml.io.writer.JAXBOutputFactory; import org.citygml4j.model.citygml.CityGMLClass; import org.citygml4j.model.gml.GMLClass; import org.citygml4j.model.module.Module; import org.citygml4j.model.module.ModuleContext; import org.citygml4j.model.module.citygml.AppearanceModule; import org.citygml4j.model.module.citygml.CityGMLModule; import org.citygml4j.model.module.citygml.CityGMLModuleType; import org.citygml4j.model.module.citygml.CityGMLVersion; import org.citygml4j.model.module.citygml.CoreModule; import org.citygml4j.util.xml.SAXEventBuffer; import org.citygml4j.util.xml.SAXWriter; import org.citygml4j.xml.io.writer.CityGMLWriteException; import org.citygml4j.xml.io.writer.CityModelInfo; import org.xml.sax.SAXException; public class Exporter implements EventHandler { private final Logger LOG = Logger.getInstance(); private final JAXBBuilder jaxbBuilder; private final DatabaseConnectionPool dbPool; private final Config config; private final EventDispatcher eventDispatcher; private DBSplitter dbSplitter; private volatile boolean shouldRun = true; private AtomicBoolean isInterrupted = new AtomicBoolean(false); private WorkerPool<DBSplittingResult> dbWorkerPool; private SingleWorkerPool<SAXEventBuffer> ioWriterPool; private WorkerPool<DBXlink> xlinkExporterPool; private CacheTableManager cacheTableManager; private UIDCacheManager uidCacheManager; private ExportFilter exportFilter; private boolean useTiling; private EnumMap<CityGMLClass, Long> totalFeatureCounterMap; private EnumMap<GMLClass, Long> totalGeometryCounterMap; private EnumMap<CityGMLClass, Long> featureCounterMap; private EnumMap<GMLClass, Long> geometryCounterMap; public Exporter(JAXBBuilder jaxbBuilder, DatabaseConnectionPool dbPool, Config config, EventDispatcher eventDispatcher) { this.jaxbBuilder = jaxbBuilder; this.dbPool = dbPool; this.config = config; this.eventDispatcher = eventDispatcher; featureCounterMap = new EnumMap<CityGMLClass, Long>(CityGMLClass.class); geometryCounterMap = new EnumMap<GMLClass, Long>(GMLClass.class); totalFeatureCounterMap = new EnumMap<CityGMLClass, Long>(CityGMLClass.class); totalGeometryCounterMap = new EnumMap<GMLClass, Long>(GMLClass.class); } public void cleanup() { eventDispatcher.removeEventHandler(this); } public boolean doProcess() { // get config shortcuts Resources resources = config.getProject().getExporter().getResources(); Database database = config.getProject().getDatabase(); // worker pool settings int minThreads = resources.getThreadPool().getDefaultPool().getMinThreads(); int maxThreads = resources.getThreadPool().getDefaultPool().getMaxThreads(); // gml:id lookup cache update int lookupCacheBatchSize = database.getUpdateBatching().getGmlIdCacheBatchValue(); // adding listeners eventDispatcher.addEventHandler(EventType.FEATURE_COUNTER, this); eventDispatcher.addEventHandler(EventType.GEOMETRY_COUNTER, this); eventDispatcher.addEventHandler(EventType.INTERRUPT, this); // checking workspace Workspace workspace = database.getWorkspaces().getExportWorkspace(); if (shouldRun && dbPool.getActiveDatabaseAdapter().hasVersioningSupport() && !dbPool.getActiveDatabaseAdapter().getWorkspaceManager().equalsDefaultWorkspaceName(workspace.getName()) && !dbPool.getActiveDatabaseAdapter().getWorkspaceManager().existsWorkspace(workspace, true)) return false; // set module context according to CityGML version and create SAX writer CityGMLVersion version = Util.toCityGMLVersion(config.getProject().getExporter().getCityGMLVersion()); ModuleContext moduleContext = new ModuleContext(version); CityModelInfo cityModel = new CityModelInfo(); SAXWriter saxWriter = new SAXWriter(); saxWriter.setWriteEncoding(true); saxWriter.setIndentString(" "); saxWriter.setHeaderComment("Written by " + this.getClass().getPackage().getImplementationTitle() + ", version \"" + this.getClass().getPackage().getImplementationVersion() + '"', this.getClass().getPackage().getImplementationVendor()); saxWriter.setDefaultNamespace(moduleContext.getModule(CityGMLModuleType.CORE).getNamespaceURI()); for (Module module : moduleContext.getModules()) { if (module instanceof CoreModule) continue; if (!config.getProject().getExporter().getAppearances().isSetExportAppearance() && module instanceof AppearanceModule) continue; saxWriter.setPrefix(module.getNamespacePrefix(), module.getNamespaceURI()); if (module instanceof CityGMLModule) saxWriter.setSchemaLocation(module.getNamespaceURI(), module.getSchemaLocation()); } // checking file Internal internalConfig = config.getInternal(); File exportFile = new File(internalConfig.getExportFileName()); String fileName = exportFile.getName(); String folderName = new File(exportFile.getAbsolutePath()).getParent(); String fileExtension = Util.getFileExtension(fileName); if (fileExtension == null) fileExtension = "gml"; else fileName = Util.stripFileExtension(fileName); // create export folder File folder = new File(folderName); if (!folder.exists() && !folder.mkdirs()) { LOG.error("Failed to create folder '" + folderName + "'."); return false; } // set target reference system for export DatabaseSrs targetSRS = config.getProject().getExporter().getTargetSRS(); if (!targetSRS.isSupported()) targetSRS = dbPool.getActiveDatabaseAdapter().getConnectionMetaData().getReferenceSystem(); internalConfig.setExportTargetSRS(targetSRS); internalConfig.setTransformCoordinates(targetSRS.isSupported() && targetSRS.getSrid() != dbPool.getActiveDatabaseAdapter().getConnectionMetaData().getReferenceSystem().getSrid()); if (internalConfig.isTransformCoordinates()) { if (targetSRS.is3D() == dbPool.getActiveDatabaseAdapter().getConnectionMetaData().getReferenceSystem().is3D()) { LOG.info("Transforming geometry representation to reference system '" + targetSRS.getDescription() + "' (SRID: " + targetSRS.getSrid() + ")."); LOG.warn("Transformation is NOT applied to height reference system."); } else { LOG.error("Dimensionality of reference system for geometry transformation does not match."); return false; } } // log index status try { for (IndexType type : IndexType.values()) dbPool.getActiveDatabaseAdapter().getUtil().getIndexStatus(type).printStatusToConsole(); } catch (SQLException e) { LOG.error("Database error while querying index status: " + e.getMessage()); return false; } // check whether database contains global appearances and set internal flag try { internalConfig.setExportGlobalAppearances(config.getProject().getExporter().getAppearances().isSetExportAppearance() && dbPool.getActiveDatabaseAdapter().getUtil().getNumGlobalAppearances(workspace) > 0); } catch (SQLException e) { LOG.error("Database error while querying the number of global appearances: " + e.getMessage()); return false; } // getting export filter exportFilter = new ExportFilter(config); // cache gml:ids of city objects in case we have to export groups internalConfig.setRegisterGmlIdInCache((!exportFilter.getFeatureClassFilter().isActive() || !exportFilter.getFeatureClassFilter().filter(CityGMLClass.CITY_OBJECT_GROUP)) && !config.getProject().getExporter().getCityObjectGroup().isExportMemberAsXLinks()); // bounding box config Tiling tiling = config.getProject().getExporter().getFilter().getComplexFilter().getTiledBoundingBox().getTiling(); useTiling = exportFilter.getBoundingBoxFilter().isActive() && tiling.getMode() != TilingMode.NO_TILING; int rows = useTiling ? tiling.getRows() : 1; int columns = useTiling ? tiling.getColumns() : 1; long start = System.currentTimeMillis(); for (int i = 0; shouldRun && i < rows; i++) { for (int j = 0; shouldRun && j < columns; j++) { try { File file = null; if (useTiling) { exportFilter.getBoundingBoxFilter().setActiveTile(i, j); // create suffix for folderName and fileName TileSuffixMode suffixMode = tiling.getTilePathSuffix(); String suffix = ""; BoundingBox bbox = exportFilter.getBoundingBoxFilter().getFilterState(); double minX = bbox.getLowerLeftCorner().getX(); double minY = bbox.getLowerLeftCorner().getY(); double maxX = bbox.getUpperRightCorner().getX(); double maxY = bbox.getUpperRightCorner().getY(); switch (suffixMode) { case XMIN_YMIN: suffix = String.valueOf(minX) + '_' + String.valueOf(minY); break; case XMAX_YMIN: suffix = String.valueOf(maxX) + '_' + String.valueOf(minY); break; case XMIN_YMAX: suffix = String.valueOf(minX) + '_' + String.valueOf(maxY); break; case XMAX_YMAX: suffix = String.valueOf(maxX) + '_' + String.valueOf(maxY); break; case XMIN_YMIN_XMAX_YMAX: suffix = String.valueOf(minX) + '_' + String.valueOf(minY) + '_' + String.valueOf(maxX) + '_' + String.valueOf(maxY); break; default: suffix = String.valueOf(i) + '_' + String.valueOf(j); } String subfolderName = folderName + File.separator + tiling.getTilePath() + '_' + suffix; File subfolder = new File(subfolderName); if (!subfolder.exists() && !subfolder.mkdirs()) { LOG.error("Failed to create tiling subfolder '" + subfolderName + "'."); return false; } if (tiling.getTileNameSuffix() == TileNameSuffixMode.SAME_AS_PATH) file = new File(subfolderName + File.separator + fileName + '_' + suffix + '.' + fileExtension); else // no suffix for filename file = new File(subfolderName + File.separator + fileName + '.' + fileExtension); } else // no tiling file = new File(folderName + File.separator + fileName + '.' + fileExtension); config.getInternal().setExportFileName(file.getAbsolutePath()); File path = new File(file.getAbsolutePath()); internalConfig.setExportPath(path.getParent()); eventDispatcher.triggerEvent(new StatusDialogMessage(Language.I18N.getString("export.dialog.cityObj.msg"), this)); eventDispatcher.triggerEvent(new StatusDialogTitle(file.getName(), this)); // checking export path for texture images ExportAppearance appearances = config.getProject().getExporter().getAppearances(); if (appearances.isSetExportAppearance()) { // read user input String textureExportPath = null; boolean isRelative = appearances.getTexturePath().isRelative(); if (isRelative) textureExportPath = appearances.getTexturePath().getRelativePath(); else textureExportPath = appearances.getTexturePath().getAbsolutePath(); if (textureExportPath != null && textureExportPath.length() > 0) { // convert into system readable path name File tmp = new File(textureExportPath); textureExportPath = tmp.getPath(); if (isRelative) { File exportPath = new File(path.getParent() + File.separator + textureExportPath); if (exportPath.isFile() || (exportPath.isDirectory() && !exportPath.canWrite())) { LOG.error("Failed to open texture files subfolder '" + exportPath.toString() + "' for writing."); return false; } else if (!exportPath.isDirectory()) { boolean success = exportPath.mkdirs(); if (!success) { LOG.error("Failed to create texture files subfolder '" + exportPath.toString() + "'."); return false; } else LOG.info("Created texture files subfolder '" + textureExportPath + "'."); } internalConfig.setExportTextureFilePath(textureExportPath); } else { File exportPath = new File(tmp.getAbsolutePath()); if (!exportPath.exists() || !exportPath.isDirectory() || !exportPath.canWrite()) { LOG.error("Failed to open texture files folder '" + exportPath.toString() + "' for writing."); return false; } internalConfig.setExportTextureFilePath(exportPath.toString()); } } } // open file for writing try { OutputStreamWriter fileWriter = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); saxWriter.setOutput(fileWriter); } catch (IOException ioE) { LOG.error("Failed to open file '" + fileName + "' for writing: " + ioE.getMessage()); return false; } // create instance of temp table manager try { cacheTableManager = new CacheTableManager(dbPool, maxThreads, config); } catch (SQLException e) { LOG.error("SQL error while initializing cache manager: " + e.getMessage()); return false; } catch (IOException e) { LOG.error("I/O error while initializing cache manager: " + e.getMessage()); return false; } // create instance of gml:id lookup server manager... uidCacheManager = new UIDCacheManager(); // ...and start servers try { uidCacheManager.initCache( UIDCacheType.GEOMETRY, new GeometryGmlIdCache(cacheTableManager, resources.getGmlIdCache().getGeometry().getPartitions(), lookupCacheBatchSize), resources.getGmlIdCache().getGeometry().getCacheSize(), resources.getGmlIdCache().getGeometry().getPageFactor(), maxThreads); uidCacheManager.initCache( UIDCacheType.FEATURE, new FeatureGmlIdCache(cacheTableManager, resources.getGmlIdCache().getFeature().getPartitions(), lookupCacheBatchSize), resources.getGmlIdCache().getFeature().getCacheSize(), resources.getGmlIdCache().getFeature().getPageFactor(), maxThreads); } catch (SQLException sqlEx) { LOG.error("SQL error while initializing database export: " + sqlEx.getMessage()); return false; } // create worker pools // here we have an open issue: queue sizes are fix... xlinkExporterPool = new WorkerPool<DBXlink>( "xlink_exporter_pool", 1, Math.max(1, maxThreads / 2), PoolSizeAdaptationStrategy.AGGRESSIVE, new DBExportXlinkWorkerFactory(dbPool, config, eventDispatcher), 300, false); ioWriterPool = new SingleWorkerPool<SAXEventBuffer>( "citygml_writer_pool", new IOWriterWorkerFactory(saxWriter), 100, false); dbWorkerPool = new WorkerPool<DBSplittingResult>( "db_exporter_pool", minThreads, maxThreads, PoolSizeAdaptationStrategy.AGGRESSIVE, new DBExportWorkerFactory( dbPool, jaxbBuilder, new FeatureWriterFactory(ioWriterPool, jaxbBuilder, config), xlinkExporterPool, uidCacheManager, cacheTableManager, exportFilter, config, eventDispatcher), 300, false); // prestart pool workers xlinkExporterPool.prestartCoreWorkers(); ioWriterPool.prestartCoreWorkers(); dbWorkerPool.prestartCoreWorkers(); // fail if we could not start a single import worker if (dbWorkerPool.getPoolSize() == 0) { LOG.error("Failed to start database export worker pool. Check the database connection pool settings."); return false; } // ok, preparations done. inform user... LOG.info("Exporting to file: " + file.getAbsolutePath()); // write CityModel header element JAXBModelWriter writer = null; try { writer = new JAXBModelWriter( saxWriter, (JAXBOutputFactory)jaxbBuilder.createCityGMLOutputFactory(moduleContext), moduleContext, cityModel); writer.writeStartDocument(); } catch (CityGMLWriteException e) { LOG.error("I/O error: " + e.getCause().getMessage()); return false; } // flush writer to make sure header has been written try { saxWriter.flush(); } catch (SAXException e) { LOG.error("I/O error: " + e.getMessage()); return false; } // get database splitter and start query dbSplitter = null; try { dbSplitter = new DBSplitter( dbPool, dbWorkerPool, exportFilter, uidCacheManager.getCache(CityGMLClass.ABSTRACT_CITY_OBJECT), cacheTableManager, eventDispatcher, config); if (shouldRun) dbSplitter.startQuery(); } catch (SQLException sqlE) { LOG.error("SQL error: " + sqlE.getMessage()); LOG.error("Failed to query the database. Check the database connection pool settings."); return false; } try { dbWorkerPool.shutdownAndWait(); if (shouldRun) xlinkExporterPool.shutdownAndWait(); ioWriterPool.shutdownAndWait(); } catch (InterruptedException e) { LOG.error("Internal error: " + e.getMessage()); } // write footer element try { writer.writeEndDocument(); } catch (CityGMLWriteException e) { LOG.error("I/O error: " + e.getCause().getMessage()); return false; } // flush sax writer try { saxWriter.flush(); saxWriter.getOutputWriter().close(); } catch (SAXException e) { LOG.error("I/O error: " + e.getMessage()); return false; } catch (IOException e) { LOG.error("I/O error: " + e.getMessage()); return false; } eventDispatcher.triggerEvent(new StatusDialogMessage(Language.I18N.getString("export.dialog.finish.msg"), this)); // cleaning up... try { uidCacheManager.shutdownAll(); } catch (SQLException e) { LOG.error("SQL error: " + e.getMessage()); } try { LOG.info("Cleaning temporary cache."); cacheTableManager.dropAll(); cacheTableManager = null; } catch (SQLException sqlE) { LOG.error("SQL error: " + sqlE.getMessage()); return false; } // finally join eventDispatcher try { eventDispatcher.flushEvents(); } catch (InterruptedException iE) { LOG.error("Internal error: " + iE.getMessage()); return false; } // show exported features if (!featureCounterMap.isEmpty()) { LOG.info("Exported CityGML features:"); for (CityGMLClass type : featureCounterMap.keySet()) LOG.info(type + ": " + featureCounterMap.get(type)); } long geometryObjects = 0; for (GMLClass type : geometryCounterMap.keySet()) geometryObjects += geometryCounterMap.get(type); if (geometryObjects != 0) LOG.info("Processed geometry objects: " + geometryObjects); featureCounterMap.clear(); geometryCounterMap.clear(); } finally { // clean up if (xlinkExporterPool != null && !xlinkExporterPool.isTerminated()) xlinkExporterPool.shutdownNow(); if (dbWorkerPool != null && !dbWorkerPool.isTerminated()) dbWorkerPool.shutdownNow(); if (ioWriterPool != null && !ioWriterPool.isTerminated()) ioWriterPool.shutdownNow(); if (cacheTableManager != null) { try { LOG.info("Cleaning temporary cache."); cacheTableManager.dropAll(); cacheTableManager = null; } catch (SQLException sqlEx) { LOG.error("SQL error while finishing database export: " + sqlEx.getMessage()); } } // set null uidCacheManager = null; xlinkExporterPool = null; ioWriterPool = null; dbWorkerPool = null; dbSplitter = null; } } } // show totally exported features if (useTiling && (rows > 1 || columns > 1)) { if (!totalFeatureCounterMap.isEmpty()) { LOG.info("Totally exported CityGML features:"); for (CityGMLClass type : totalFeatureCounterMap.keySet()) LOG.info(type + ": " + totalFeatureCounterMap.get(type)); } long geometryObjects = 0; for (GMLClass type : totalGeometryCounterMap.keySet()) geometryObjects += totalGeometryCounterMap.get(type); if (geometryObjects != 0) LOG.info("Total processed geometry objects: " + geometryObjects); } if (shouldRun) LOG.info("Total export time: " + Util.formatElapsedTime(System.currentTimeMillis() - start) + "."); return shouldRun; } @Override public void handleEvent(Event e) throws Exception { if (e.getEventType() == EventType.FEATURE_COUNTER) { HashMap<CityGMLClass, Long> counterMap = ((FeatureCounterEvent)e).getCounter(); for (CityGMLClass type : counterMap.keySet()) { Long counter = featureCounterMap.get(type); Long update = counterMap.get(type); if (counter == null) featureCounterMap.put(type, update); else featureCounterMap.put(type, counter + update); if (useTiling) { counter = totalFeatureCounterMap.get(type); if (counter == null) totalFeatureCounterMap.put(type, update); else totalFeatureCounterMap.put(type, counter + update); } } } else if (e.getEventType() == EventType.GEOMETRY_COUNTER) { HashMap<GMLClass, Long> counterMap = ((GeometryCounterEvent)e).getCounter(); for (GMLClass type : counterMap.keySet()) { Long counter = geometryCounterMap.get(type); Long update = counterMap.get(type); if (counter == null) geometryCounterMap.put(type, update); else geometryCounterMap.put(type, counter + update); if (useTiling) { counter = totalGeometryCounterMap.get(type); if (counter == null) totalGeometryCounterMap.put(type, update); else totalGeometryCounterMap.put(type, counter + update); } } } else if (e.getEventType() == EventType.INTERRUPT) { if (isInterrupted.compareAndSet(false, true)) { shouldRun = false; InterruptEvent interruptEvent = (InterruptEvent)e; if (interruptEvent.getCause() != null) { Throwable cause = interruptEvent.getCause(); if (cause instanceof SQLException) { Iterator<Throwable> iter = ((SQLException)cause).iterator(); LOG.error("A SQL error occured: " + iter.next().getMessage().trim()); while (iter.hasNext()) LOG.error("Cause: " + iter.next().getMessage().trim()); } else { LOG.error("An error occured: " + cause.getMessage().trim()); while ((cause = cause.getCause()) != null) LOG.error("Cause: " + cause.getMessage().trim()); } } String log = interruptEvent.getLogMessage(); if (log != null) LOG.log(interruptEvent.getLogLevelType(), log); if (dbSplitter != null) dbSplitter.shutdown(); if (dbWorkerPool != null) dbWorkerPool.drainWorkQueue(); if (xlinkExporterPool != null) xlinkExporterPool.shutdownNow(); } } } }
package org.ensembl.healthcheck.testcase.generic; import java.sql.Connection; import org.ensembl.healthcheck.DatabaseRegistryEntry; import org.ensembl.healthcheck.DatabaseType; import org.ensembl.healthcheck.ReportManager; import org.ensembl.healthcheck.Species; import org.ensembl.healthcheck.util.DBUtils; import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase; /** * Check various things about ID mapping-related tables. */ public class MappingSession extends SingleDatabaseTestCase { // historical names to ignore when doing format checking private String[] ignoredNames = {"homo_sapiens_core_120"}; /** * Create a new MappingSession healthcheck. */ public MappingSession() { addToGroup("id_mapping"); addToGroup("release"); setDescription("Checks the mapping session and stable ID tables."); } /** * This only really applies to core databases */ public void types() { removeAppliesToType(DatabaseType.OTHERFEATURES); removeAppliesToType(DatabaseType.ESTGENE); removeAppliesToType(DatabaseType.VEGA); removeAppliesToType(DatabaseType.CDNA); } /** * Run the test - check the ID mapping-related tables. * @param dbre The database to check. * @return true if the test passes. */ public boolean run(final DatabaseRegistryEntry dbre) { boolean result = true; // there are several species where ID mapping is not done Species s = dbre.getSpecies(); if (s != Species.CAENORHABDITIS_ELEGANS && s != Species.DROSOPHILA_MELANOGASTER && s != Species.TAKIFUGU_RUBRIPES) { Connection con = dbre.getConnection(); logger.info("Checking tables exist and are populated"); result = checkTablesExistAndPopulated(dbre) && result; logger.info("Checking for null strings"); result = checkNoNullStrings(con) && result; logger.info("Checking DB name format in mapping_session"); result = checkDBNameFormat(con) && result; logger.info("Checking mapping_session chaining"); result = checkMappingSessionChaining(con) && result; logger.info("Checking mapping_session/stable_id_event keys"); result = checkMappingSessionStableIDKeys(con) && result; } return result; } // run /** * Check format of old/new DB names in mapping_session. */ private boolean checkDBNameFormat(final Connection con) { boolean result = true; String dbNameRegexp = "[A-Za-z]+_[A-Za-z]+_(core|est|estgene|vega)_\\d+_\\d+[A-Za-z]?.*"; String[] sql = {"SELECT old_db_name from mapping_session WHERE old_db_name <> 'ALL'", "SELECT new_db_name from mapping_session WHERE new_db_name <> 'LATEST'"}; for (int i = 0; i < sql.length; i++) { String[] names = getColumnValues(con, sql[i]); for (int j = 0; j < names.length; j++) { if (!(names[j].matches(dbNameRegexp)) && !ignoreName(names[j])) { ReportManager.problem(this, con, "Database name " + names[j] + " in mapping_session does not appear to be in the correct format"); result = false; } } } if (result) { ReportManager .correct(this, con, "All database names in mapping_session appear to be in the correct format"); } return result; } /** * Checks tables exist and have >0 rows. Doesn't check population for first-build databases. * * @param con * @return True when all ID mapping-related tables exist and have > 0 rows. * */ private boolean checkTablesExistAndPopulated(final DatabaseRegistryEntry dbre) { String[] tables = new String[] {"stable_id_event", "mapping_session", "gene_archive", "peptide_archive"}; boolean result = true; Connection con = dbre.getConnection(); String dbName = DBUtils.getShortDatabaseName(con); if (!dbName.matches(".*_1[a-zA-Z]?$")) { for (int i = 0; i < tables.length; i++) { String table = tables[i]; boolean exists = checkTableExists(con, table); if (exists) { if (countRowsInTable(con, table) == 0) { ReportManager.problem(this, con, "Empty table:" + table); result = false; } } else { ReportManager.problem(this, con, "Missing table:" + table); result = false; } } } else { logger.info(dbName + " seems to be a new genebuild, skipping table checks"); } return result; } /** * Check no "NULL" or "null" strings in stable_id_event.new_stable_id or * stable_id_event.oldable_id. * * @param con * @return */ private boolean checkNoNullStrings(final Connection con) { boolean result = true; int rows = getRowCount(con, "select count(*) from stable_id_event sie where new_stable_id='NULL'"); if (rows > 0) { ReportManager.problem(this, con, rows + " rows in stable_id_event.new_stable_id contains \"NULL\" string instead of NULL value."); result = false; } rows = getRowCount(con, "select count(*) from stable_id_event sie where new_stable_id='null'"); if (rows > 0) { ReportManager.problem(this, con, rows + " rows in stable_id_event.new_stable_id contains \"null\" string instead of NULL value."); result = false; } rows = getRowCount(con, "select count(*) from stable_id_event sie where old_stable_id='NULL'"); if (rows > 0) { ReportManager.problem(this, con, rows + " rows in stable_id_event.old_stable_id contains \"NULL\" string instead of NULL value."); result = false; } rows = getRowCount(con, "select count(*) from stable_id_event sie where old_stable_id='null'"); if (rows > 0) { ReportManager.problem(this, con, rows + " rows in stable_id_event.old_stable_id contains \"null\" string instead of NULL value."); result = false; } return result; } /** * Check that the old_db_name and new_db_name columns "chain" together. */ private boolean checkMappingSessionChaining(final Connection con) { boolean result = true; String[] oldNames = getColumnValues(con, "SELECT old_db_name FROM mapping_session WHERE old_db_name <> 'ALL' ORDER BY created"); String[] newNames = getColumnValues(con, "SELECT new_db_name FROM mapping_session WHERE new_db_name <> 'LATEST' ORDER BY created"); for (int i = 1; i < oldNames.length; i++) { if (!(oldNames[i].equalsIgnoreCase(newNames[i - 1]))) { ReportManager.problem(this, con, "Old/new names " + oldNames[i] + " " + newNames[i - 1] + " do not chain properly"); result = false; } } if (result) { ReportManager.correct(this, con, "Old/new db name chaining in mapping_session seems OK"); } return result; } /** * Check that all mapping_sessions have entries in stable_id_event and * vice-versa. */ private boolean checkMappingSessionStableIDKeys(final Connection con) { boolean result = true; int orphans = countOrphans(con, "mapping_session", "mapping_session_id", "stable_id_event", "mapping_session_id", false); if (orphans > 0) { ReportManager.problem(this, con, orphans + " dangling references between mapping_session and stable_id_event tables"); result = false; } else { ReportManager.correct(this, con, "All mapping_session/stable_id_event keys are OK"); } return result; } /** * Certain historical names don't match the new format and should be * ignored to prevent constant failures. */ private boolean ignoreName(String name) { for (int i = 0; i < ignoredNames.length; i++) { if (name.equals(ignoredNames[i])) { return true; } } return false; } } // MappingSession
package org.objectweb.proactive.examples.c3d; import org.objectweb.proactive.examples.c3d.geom.Ray; import org.objectweb.proactive.examples.c3d.geom.Vec; import org.objectweb.proactive.examples.c3d.prim.Isect; import org.objectweb.proactive.examples.c3d.prim.Light; import org.objectweb.proactive.examples.c3d.prim.Primitive; import org.objectweb.proactive.examples.c3d.prim.Surface; import java.awt.image.ColorModel; public class C3DRenderingEngine implements java.io.Serializable { /** * Lights for the rendering scene */ private Light lights[]; /** * Objects (spheres) for the rendering scene */ private Primitive prim[]; /** * Default RGB ColorModel for the newPixels(...) */ private transient ColorModel model; /** * The view for the rendering scene */ private View view; /** * Interval c3ddispatcher */ private C3DDispatcher c3ddispatcher; /** * Alpha channel */ private static final int alpha = 255 << 24; /** * Null vector (for speedup, instead of <code>new Vec(0,0,0)</code> */ private static final Vec voidVec = new Vec(); /** * Current intersection instance (only one is needed!) */ private Isect inter = new Isect(); /** * Temporary ray */ private Ray tRay = new Ray(); /** * Temporary vect */ private Vec L = new Vec(); /** * Feature the migration property */ public void migrateTo(String nodeTarget) { try { org.objectweb.proactive.ProActive.migrateTo(nodeTarget); } catch (Exception e) { e.printStackTrace(); } } /** * Default constructor */ public C3DRenderingEngine() { } /** * Constructor refernecing the current dispatcher */ public C3DRenderingEngine(C3DDispatcher c3ddispatcher) { model = ColorModel.getRGBdefault(); this.c3ddispatcher = c3ddispatcher; //System.out.println("Rendering id "+org.objectweb.proactive.ProActive.getBodyOnThis().getID()); } /** * Find closest Ray, return initialized Isect * with intersection information. */ boolean intersect(Ray r, double maxt) { Isect tp; int i, nhits; nhits = 0; inter.t = 1e9; for (i = 0; i < prim.length; i++) { // uses global temporary Prim (tp) as temp.object for speedup tp = prim[i].intersect(r); if (tp != null && tp.t < inter.t) { inter.t = tp.t; inter.prim = tp.prim; inter.surf = tp.surf; inter.enter = tp.enter; nhits++; } } return nhits > 0 ? true : false; } /** * Checks if there is a shadow */ int Shadow(Ray r, double tmax) { if (intersect(r, tmax)) return 0; return 1; } /** * Return the Vector's reflection direction */ Vec SpecularDirection(Vec I, Vec N) { Vec r; r = Vec.comb(1.0 / Math.abs(Vec.dot(I, N)), I, 2.0, N); r.normalize(); return r; } /** * Return the Vector's transmission direction */ Vec TransDir(Surface m1, Surface m2, Vec I, Vec N) { double n1, n2, eta, c1, cs2; Vec r; n1 = m1 == null ? 1.0 : m1.ior; n2 = m2 == null ? 1.0 : m2.ior; eta = n1 / n2; c1 = -Vec.dot(I, N); cs2 = 1.0 - eta * eta * (1.0 - c1 * c1); if (cs2 < 0.0) return null; r = Vec.comb(eta, I, eta * c1 - Math.sqrt(cs2), N); r.normalize(); return r; } /** * Returns the shaded color */ Vec shade(int level, double weight, Vec P, Vec N, Vec I, Isect hit) { Vec tcol; Vec R; double t, diff, spec; Surface surf; Vec col; int l; col = new Vec(); surf = hit.surf; R = new Vec(); if (surf.shine > 1e-6) { R = SpecularDirection(I, N); } // Computes the effectof each light for (l = 0; l < lights.length; l++) { L.sub2(lights[l].pos, P); if (Vec.dot(N, L) >= 0.0) { t = L.normalize(); tRay.P = P; tRay.D = L; // Checks if there is a shadow if (Shadow(tRay, t) > 0) { diff = Vec.dot(N, L) * surf.kd * lights[l].brightness; col.adds(diff, surf.color); if (surf.shine > 1e-6) { spec = Vec.dot(R, L); if (spec > 1e-6) { spec = Math.pow(spec, surf.shine); col.x += spec; col.y += spec; col.z += spec; } } } } } // for tRay.P = P; if (surf.ks * weight > 1e-3) { tRay.D = SpecularDirection(I, N); tcol = trace(level + 1, surf.ks * weight, tRay); col.adds(surf.ks, tcol); } if (surf.kt * weight > 1e-3) { if (hit.enter > 0) tRay.D = TransDir(null, surf, I, N); else tRay.D = TransDir(surf, null, I, N); tcol = trace(level + 1, surf.kt * weight, tRay); col.adds(surf.kt, tcol); } // garbaging... tcol = null; surf = null; return col; } /** * Launches a ray */ Vec trace(int level, double weight, Ray r) { Vec P, N; boolean hit; // Checks the recursion level if (level > 6) { return new Vec(); } hit = intersect(r, 1e6); if (hit) { P = r.point(inter.t); N = inter.prim.normal(P); if (Vec.dot(r.D, N) >= 0.0) { N.negate(); } return shade(level, weight, P, N, r.D, inter); } // no intersection --> col = 0,0,0 return voidVec; } /** * Scan all pixels in the image intervals, have them traced * and set the result with newPixels(...) on the MemoryImagesource * <i>heavily optimized!!!</i> */ public void render(int engine_number, Interval interval) { // Screen variables int row[] = new int[interval.width * (interval.yto - interval.yfrom)]; int pixCounter = 0; //iterator // Renderding variables int x, y, red, green, blue; double xlen, ylen; Vec viewVec = Vec.sub(view.at, view.from); viewVec.normalize(); Vec tmpVec = new Vec(viewVec); tmpVec.scale(Vec.dot(view.up, viewVec)); Vec upVec = Vec.sub(view.up, tmpVec); upVec.normalize(); Vec leftVec = Vec.cross(view.up, viewVec); leftVec.normalize(); double frustrumwidth = view.dist * Math.tan(view.angle); upVec.scale(-frustrumwidth); leftVec.scale(view.aspect * frustrumwidth); Ray r = new Ray(view.from, voidVec); Vec col = new Vec(); // All loops are reversed for 'speedup' (cf. thinking in java p331) // For each line for (y = interval.yfrom; y < interval.yto; y++) { ylen = (double)(2.0 * y) / (double)interval.width - 1.0; // For each pixel of the line for (x = 0; x < interval.width; x++) { xlen = (double)(2.0 * x) / (double)interval.width - 1.0; r.D = Vec.comb(xlen, leftVec, ylen, upVec); r.D.add(viewVec); r.D.normalize(); col = trace(0, 1.0, r); // computes the color of the ray red = (int)(col.x * 255.0); if (red > 255) red = 255; green = (int)(col.y * 255.0); if (green > 255) green = 255; blue = (int)(col.z * 255.0); if (blue > 255) blue = 255; // Sets the pixels row[pixCounter++] = alpha | (red << 16) | (green << 8) | (blue); } // end for (x) } // end for (y) // sends the results to the dispatcher c3ddispatcher.setPixels(row, interval, engine_number); } /** * Creates the local objects used in the rendering */ public void setScene(Scene scene) { int nLights = scene.getLights(); int nObjects = scene.getObjects(); lights = new Light[nLights]; prim = new Primitive[nObjects]; for (int l = 0; l < nLights; l++) { lights[l] = scene.getLight(l); } for (int o = 0; o < nObjects; o++) { prim[o] = scene.getObject(o); } this.view = scene.getView(); } /** * Destructor * @exception Throwable exception requested by RMI */ protected void finalize() throws Throwable { //System.out.println("Engine halted and released"); super.finalize(); } /** * The pinging function called by <code>C3DDispatcher</code> * to get the avg. pinging time */ public int ping() { return 0; } }
package com.alibaba.easyexcel.test.core.sort; import com.alibaba.excel.annotation.ExcelProperty; import lombok.Data; /** * @author Jiaju Zhuang */ @Data public class SortData { private String column5; private String column6; @ExcelProperty(order = 100) private String column4; @ExcelProperty(order = 99) private String column3; @ExcelProperty(value = "column2", index = 1) private String column2; @ExcelProperty(value = "column1", index = 0) private String column1; }
package com.github.bot.curiosone.core.nlp; // SUPPRESS CHECKSTYLE AvoidStarImport import static org.junit.Assert.*; import org.junit.Test; public class MeaningTest { @Test public void testInstantiation() { Meaning m = new Meaning(POS.AP, LEX.OBJECT); assertTrue(m instanceof Meaning); assertTrue(m instanceof Comparable); } @Test public void testGetPos() { Meaning m = new Meaning(POS.AP, LEX.OBJECT); assertEquals(POS.AP, m.getPOS()); m = new Meaning(POS.VPP, LEX.PHENOMENON); assertEquals(POS.VPP, m.getPOS()); m = new Meaning(POS.ADJ, LEX.QUANTITY); assertEquals(POS.ADJ, m.getPOS()); } @Test public void testGetLex() { Meaning m = new Meaning(POS.AP, LEX.OBJECT); assertEquals(LEX.OBJECT, m.getLEX()); m = new Meaning(POS.VPP, LEX.PHENOMENON); assertEquals(LEX.PHENOMENON, m.getLEX()); m = new Meaning(POS.ADJ, LEX.QUANTITY); assertEquals(LEX.QUANTITY, m.getLEX()); } @Test(expected = IllegalArgumentException.class) public void testSetFrequencyException() { Meaning m = new Meaning(POS.AP, LEX.PHENOMENON); m.setFrequency(-1); m = new Meaning(POS.VPP, LEX.OBJECT); m.setFrequency(-2); m = new Meaning(POS.VP, LEX.QUANTITY); m.setFrequency(-42); } @Test public void testSetFrequency() { Meaning m = new Meaning(POS.AP, LEX.PHENOMENON); m.setFrequency(1); assertEquals(1, m.getFrequency()); m = new Meaning(POS.VPP, LEX.OBJECT); m.setFrequency(2); assertEquals(2, m.getFrequency()); m = new Meaning(POS.VP, LEX.QUANTITY); m.setFrequency(42); assertEquals(42, m.getFrequency()); } @Test public void testEqualsReflexive() { Meaning m = new Meaning(POS.DET, LEX.TIME); assertTrue(m.equals(m)); m = new Meaning(POS.NEG, LEX.SOCIAL); assertTrue(m.equals(m)); m = new Meaning(POS.INTERJ, LEX.PERSONAL_OBJECTIVE); assertTrue(m.equals(m)); } @Test public void testEqualsSymmetric() { Meaning m = new Meaning(POS.PREP, LEX.RELATIVE); Meaning mm = new Meaning(POS.PREP, LEX.RELATIVE); assertTrue(m.equals(mm) && mm.equals(m)); m = new Meaning(POS.UNKN, LEX.COORDINATOR); mm = new Meaning(POS.UNKN, LEX.COORDINATOR); assertTrue(m.equals(mm) && mm.equals(m)); m = new Meaning(POS.CONJ, LEX.SURPRISE); mm = new Meaning(POS.CONJ, LEX.SURPRISE); assertTrue(m.equals(mm) && mm.equals(m)); } @Test public void testEqualsTransitive() { Meaning m = new Meaning(POS.DET, LEX.REGARDS); Meaning mm = new Meaning(POS.DET, LEX.REGARDS); Meaning mmm = new Meaning(POS.DET, LEX.REGARDS); assertTrue(m.equals(mm) && mm.equals(mmm) && mmm.equals(m)); m = new Meaning(POS.N, LEX.SUBSTANCE); mm = new Meaning(POS.N, LEX.SUBSTANCE); mmm = new Meaning(POS.N, LEX.SUBSTANCE); assertTrue(m.equals(mm) && mm.equals(mmm) && mmm.equals(m)); m = new Meaning(POS.APP, LEX.TIME); mm = new Meaning(POS.APP, LEX.TIME); mmm = new Meaning(POS.APP, LEX.TIME); assertTrue(m.equals(mm) && mm.equals(mmm) && mmm.equals(m)); } @Test public void testEqualsConsistent() { Meaning m = new Meaning(POS.CONJ, LEX.CHANGE); Meaning mm = new Meaning(POS.CONJ, LEX.CHANGE); assertTrue(m.equals(mm)); m.setFrequency(42); m.setFrequency(424242); assertTrue(m.equals(mm)); } @Test public void testEqualsNullComparison() { Meaning m = new Meaning(POS.NPP, LEX.CONSUMPTION); assertFalse(m.equals(null)); m = new Meaning(POS.NUMB, LEX.CONTACT); assertFalse(m.equals(null)); m = new Meaning(POS.S, LEX.CREATION); assertFalse(m.equals(null)); } @Test public void testEqualsOtherObj() { Meaning m = new Meaning(POS.CONJ, LEX.PAIN); assertFalse(m.equals(new Integer(42))); } @Test public void testEqualsHashCodeContract() { Meaning m = new Meaning(POS.VP, LEX.DISGUST); Meaning mm = new Meaning(POS.VP, LEX.DISGUST); assertEquals(m, mm); assertEquals(m.hashCode(), mm.hashCode()); m = new Meaning(POS.PRON, LEX.APOLOGIZE); mm = new Meaning(POS.PRON, LEX.APOLOGIZE); assertTrue(m.equals(mm)); assertEquals(m.hashCode(), mm.hashCode()); m = new Meaning(POS.AP, LEX.GRATITUDE); mm = new Meaning(POS.AP, LEX.GRATITUDE); assertTrue(m.equals(mm)); assertEquals(m.hashCode(), mm.hashCode()); } @Test public void testHashCodeReflexive() { Meaning m = new Meaning(POS.ADV, LEX.SURPRISE); Meaning mm = new Meaning(POS.ADV, LEX.SURPRISE); assertEquals(m.hashCode(), mm.hashCode()); m = new Meaning(POS.PREP, LEX.MAIL); mm = new Meaning(POS.PREP, LEX.MAIL); assertEquals(m.hashCode(), mm.hashCode()); m = new Meaning(POS.V, LEX.GENERIC); mm = new Meaning(POS.V, LEX.GENERIC); assertEquals(m.hashCode(), mm.hashCode()); } @Test public void testHashCodeTransitive() { Meaning m = new Meaning(POS.ADV, LEX.SURPRISE); Meaning mm = new Meaning(POS.ADV, LEX.SURPRISE); Meaning mmm = new Meaning(POS.ADV, LEX.SURPRISE); assertTrue(m.hashCode() == mm.hashCode() && mm.hashCode() == mmm.hashCode() && mmm.hashCode() == m.hashCode()); m = new Meaning(POS.PREP, LEX.MAIL); mm = new Meaning(POS.PREP, LEX.MAIL); mmm = new Meaning(POS.PREP, LEX.MAIL); assertTrue(m.hashCode() == mm.hashCode() && mm.hashCode() == mmm.hashCode() && mmm.hashCode() == m.hashCode()); m = new Meaning(POS.V, LEX.GENERIC); mm = new Meaning(POS.V, LEX.GENERIC); mmm = new Meaning(POS.V, LEX.GENERIC); assertTrue(m.hashCode() == mm.hashCode() && mm.hashCode() == mmm.hashCode() && mmm.hashCode() == m.hashCode()); } @Test public void testHashCodeConsistent() { Meaning m = new Meaning(POS.S, LEX.INTERROGATIVE); Meaning mm = new Meaning(POS.S, LEX.INTERROGATIVE); assertEquals(m.hashCode(), mm.hashCode()); m.setFrequency(130); mm.setFrequency(31); assertEquals(m.hashCode(), mm.hashCode()); m = new Meaning(POS.INTERJ, LEX.REGARDS); mm = new Meaning(POS.INTERJ, LEX.REGARDS); assertEquals(m.hashCode(), mm.hashCode()); m.setFrequency(130); mm.setFrequency(130); assertEquals(m.hashCode(), mm.hashCode()); m = new Meaning(POS.NUMB, LEX.INDEFINITE_ARTICLE); mm = new Meaning(POS.NUMB, LEX.INDEFINITE_ARTICLE); assertEquals(m.hashCode(), mm.hashCode()); m.setFrequency(90); mm.setFrequency(45); assertEquals(m.hashCode(), mm.hashCode()); } @Test public void testCompareTo() { Meaning m = new Meaning(POS.NPP, LEX.INTERROGATIVE); Meaning mm = new Meaning(POS.S, LEX.DISGUST); assertEquals(0, m.compareTo(mm)); m.setFrequency(1); mm.setFrequency(2); assertTrue(m.compareTo(mm) < 0); m.setFrequency(3); assertTrue(m.compareTo(mm) > 0); } }
package crawler.service.impl; import static org.mockito.Mockito.*; import org.junit.Test; import crawler.domain.Novel; import crawler.domain.source.NovelSource; public class NovelInfoManagerImplTest { @Test public void testSaveNovelInfo() throws Exception { String filePath = this.getClass().getClassLoader().getResource("novel/testInfo.html").getPath(); NovelSource novelSource = mock(NovelSource.class); when(novelSource.getNovelInfoLink()).thenReturn("file://" + filePath); when(novelSource.getNovel()).thenReturn(new Novel()); NovelInfoManagerImpl novelInfoManager = new NovelInfoManagerImpl(); novelInfoManager.saveNovelInfo(novelSource); } }
package cz.linkedlist.http; import cz.linkedlist.TileSet; import cz.linkedlist.UTMCode; import cz.linkedlist.cache.Cache; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.springframework.web.client.RestTemplate; import java.time.LocalDate; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.Set; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.mockito.Matchers.anyObject; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.when; public class HttpTileListingServiceTest { private HttpTileListingService service; @Before public void init() { Cache cache = Mockito.mock(Cache.class); when(cache.exists(anyObject())).thenReturn(Optional.empty()); when(cache.insert(anyObject(), eq(true))).thenReturn(true); when(cache.insert(anyObject(), eq(false))).thenReturn(false); service = new HttpTileListingService(new RestTemplate(), cache); } @Test public void testExists() throws Exception { TileSet tileSet = new TileSet(UTMCode.of("36MTD"), LocalDate.of(2016, 8, 31)); assertThat(service.exists(tileSet), is(true)); } @Test public void testNotExists() throws Exception { TileSet tileSet = new TileSet(UTMCode.of("36MTD"), LocalDate.of(2016, 8, 31), 3); assertThat(service.exists(tileSet), is(false)); } @Test public void testGetYears() throws Exception { UTMCode code = UTMCode.of("36MTD"); Set<Integer> years = service.getYears(code); assertThat(years, hasSize(3)); assertThat(years, hasItem(2015)); assertThat(years, hasItem(2016)); assertThat(years, hasItem(2017)); } @Test public void testGetMonths() throws Exception { UTMCode code = UTMCode.of("36MTD"); Set<Integer> months = service.getMonths(code, 2015); assertThat(months, hasSize(5)); assertThat(months, hasItem(10)); assertThat(months, hasItem(11)); assertThat(months, hasItem(12)); assertThat(months, hasItem(7)); assertThat(months, hasItem(9)); } @Test public void testGetDays() throws Exception { UTMCode code = UTMCode.of("36MTD"); Set<Integer> days = service.getDays(code, 2015, 10); assertThat(days, hasSize(2)); assertThat(days, hasItem(23)); assertThat(days, hasItem(3)); } @Test public void testGetDatasets() throws Exception { UTMCode code = UTMCode.of("36MTD"); Set<Integer> dataSets = service.getDataSets(code, 2015, 10, 23); assertThat(dataSets, hasSize(1)); assertThat(dataSets, hasItem(0)); } @Test public void testGetFolderContents() throws Exception { TileSet tileSet = new TileSet(UTMCode.of("36MTD"), LocalDate.of(2015, 10, 23)); List<String> folderContents = service.getFolderContents(tileSet); assertAllBands(folderContents); assertThat(folderContents, hasItem("tiles/36/M/TD/2015/10/23/0/metadata.xml")); assertThat(folderContents, hasItem("tiles/36/M/TD/2015/10/23/0/productInfo.json")); assertThat(folderContents, hasItem("tiles/36/M/TD/2015/10/23/0/tileInfo.json")); } @Test public void testAvailableDates() throws Exception { UTMCode code = UTMCode.of("20MMN"); List<LocalDate> localDates = service.availableDates(code); assertThat(localDates, hasSize(1)); assertThat(localDates, hasItem(LocalDate.of(2015, 12, 6))); } @Test public void testAvailableDatesAfter() throws Exception { UTMCode code = UTMCode.of("20MMN"); Collection<LocalDate> localDates = service.availableDatesAfter(code, LocalDate.of(2014, 1, 6)); assertThat(localDates, hasSize(1)); assertThat(localDates, hasItem(LocalDate.of(2015, 12, 6))); } @Test public void testAvailableDatesAfterWithoutAvailableDates() throws Exception { UTMCode code = UTMCode.of("20MMN"); Collection<LocalDate> localDates = service.availableDatesAfter(code, LocalDate.of(2017, 1, 6)); assertThat(localDates, hasSize(0)); } @Test public void testAvailableDatesAfterWithDateInTheSameYearAndMonth() throws Exception { UTMCode code = UTMCode.of("20MMN"); Collection<LocalDate> localDates = service.availableDatesAfter(code, LocalDate.of(2015, 12, 5)); assertThat(localDates, hasSize(1)); assertThat(localDates, hasItem(LocalDate.of(2015, 12, 6))); } private void assertAllBands(List<String> contents) { for(int i = 1; i<=12; i++) { assertThat(contents, hasItem("tiles/36/M/TD/2015/10/23/0/B" + String.format("%02d", i) + ".jp2")); } assertThat(contents, hasItem("tiles/36/M/TD/2015/10/23/0/B8A.jp2")); } }