text
stringlengths
10
2.72M
package com.ggtf.xieyingwu.cloudphoto.instagram.model; /** * Created by xieyingwu on 2017/5/18. */ public class IgAuth { public String code; public String error; public String error_reason; public String error_description; public boolean isAuthSuc; private IgAuth() { } public static IgAuth initIgAuth(String redirectUri) { IgAuth igAuth = new IgAuth(); int beginIndex = redirectUri.indexOf("?"); String value = redirectUri.substring(beginIndex + 1); if (value.contains("&")) { igAuth.isAuthSuc = false; String[] split = value.split("&"); for (String str : split) { if (str.startsWith("error=")) { igAuth.error = str.replace("error=", "").trim(); continue; } if (str.startsWith("error_reason=")) { igAuth.error_reason = str.replace("error_reason=", "").trim(); continue; } if (str.startsWith("error_description=")) { igAuth.error_description = str.replace("error_description=", "").trim(); } } } else { igAuth.isAuthSuc = true; igAuth.code = value.replace("code=", "").trim(); } return igAuth; } }
/** * Copyright (C) 2006 Aelitis, All Rights Reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * AELITIS, SAS au capital de 63.529,40 euros * 8 Allee Lenotre, La Grille Royale, 78600 Le Mesnil le Roi, France. * */ package com.aelitis.azureus.ui.swt.views.skin; import java.io.File; import java.lang.reflect.Method; import java.net.URL; import java.util.Map; import org.gudy.azureus2.core3.disk.DiskManagerFileInfo; import org.gudy.azureus2.core3.download.DownloadManager; import org.gudy.azureus2.core3.download.ForceRecheckListener; import org.gudy.azureus2.core3.internat.MessageText; import org.gudy.azureus2.core3.torrent.TOTorrent; import org.gudy.azureus2.core3.util.*; import org.gudy.azureus2.plugins.PluginInterface; import org.gudy.azureus2.pluginsimpl.local.PluginCoreUtils; import org.gudy.azureus2.ui.swt.TextViewerWindow; import org.gudy.azureus2.ui.swt.Utils; import org.gudy.azureus2.ui.swt.shells.MessageBoxShell; import org.gudy.azureus2.ui.swt.views.utils.ManagerUtils; import com.aelitis.azureus.activities.VuzeActivitiesEntry; import com.aelitis.azureus.core.AzureusCoreFactory; import com.aelitis.azureus.core.download.*; import com.aelitis.azureus.core.torrent.PlatformTorrentUtils; import com.aelitis.azureus.core.util.LaunchManager; import com.aelitis.azureus.core.vuzefile.VuzeFile; import com.aelitis.azureus.core.vuzefile.VuzeFileComponent; import com.aelitis.azureus.core.vuzefile.VuzeFileHandler; import com.aelitis.azureus.ui.UserPrompterResultListener; import com.aelitis.azureus.ui.selectedcontent.DownloadUrlInfo; import com.aelitis.azureus.ui.selectedcontent.ISelectedContent; import com.aelitis.azureus.ui.swt.UIFunctionsManagerSWT; import com.aelitis.azureus.ui.swt.UIFunctionsSWT; import com.aelitis.azureus.ui.swt.feature.FeatureManagerUI; import com.aelitis.azureus.ui.swt.player.PlayerInstallWindow; import com.aelitis.azureus.ui.swt.player.PlayerInstaller; import com.aelitis.azureus.ui.swt.utils.TorrentUIUtilsV3; import com.aelitis.azureus.util.DLReferals; import com.aelitis.azureus.util.DataSourceUtils; import com.aelitis.azureus.util.PlayUtils; /** * @author TuxPaper * @created Oct 12, 2006 * */ public class TorrentListViewsUtils { private static StreamManagerDownload current_stream; private static TextViewerWindow stream_viewer; public static void playOrStreamDataSource(Object ds, boolean launch_already_checked) { String referal = DLReferals.DL_REFERAL_UNKNOWN; if (ds instanceof VuzeActivitiesEntry) { referal = DLReferals.DL_REFERAL_PLAYDASHACTIVITY; } else if (ds instanceof DownloadManager) { referal = DLReferals.DL_REFERAL_PLAYDM; } else if (ds instanceof ISelectedContent) { referal = DLReferals.DL_REFERAL_SELCONTENT; } playOrStreamDataSource(ds, referal, launch_already_checked, true ); } public static void playOrStreamDataSource(Object ds, String referal, boolean launch_already_checked, boolean complete_only) { DiskManagerFileInfo fileInfo = DataSourceUtils.getFileInfo(ds); if (fileInfo != null) { playOrStream(fileInfo.getDownloadManager(), fileInfo.getIndex(), complete_only, launch_already_checked, referal); }else{ DownloadManager dm = DataSourceUtils.getDM(ds); if (dm == null) { downloadDataSource(ds, true, referal); } else { playOrStream(dm, -1, complete_only, launch_already_checked, referal); } } } public static void downloadDataSource(Object ds, boolean playNow, String referal) { TOTorrent torrent = DataSourceUtils.getTorrent(ds); if ( torrent != null ){ // handle encapsulated vuze file try{ Map torrent_map = torrent.serialiseToMap(); torrent_map.remove( "info" ); VuzeFile vf = VuzeFileHandler.getSingleton().loadVuzeFile( torrent_map ); if ( vf != null ){ VuzeFileHandler.getSingleton().handleFiles( new VuzeFile[]{ vf }, VuzeFileComponent.COMP_TYPE_NONE ); return; } }catch( Throwable e ){ } } // we want to re-download the torrent if it's ours, since the existing // one is likely stale if (torrent != null && !DataSourceUtils.isPlatformContent(ds)) { TorrentUIUtilsV3.addTorrentToGM(torrent); } else { DownloadUrlInfo dlInfo = DataSourceUtils.getDownloadInfo(ds); if (dlInfo != null) { TorrentUIUtilsV3.loadTorrent(dlInfo, playNow, false, true); return; } String hash = DataSourceUtils.getHash(ds); if (hash != null) { dlInfo = new DownloadUrlInfo(UrlUtils.parseTextForMagnets(hash)); dlInfo.setReferer(referal); TorrentUIUtilsV3.loadTorrent(dlInfo, playNow, false, true); return; } } } // VuzePlayer (2011) calls this public static void playOrStream(final DownloadManager dm, final int file_index, final boolean complete_only, boolean launch_already_checked) { playOrStream(dm, file_index, complete_only, launch_already_checked, null); } private static void playOrStream(final DownloadManager dm, final int file_index, final boolean complete_only, boolean launch_already_checked, final String referal) { if (dm == null) { return; } if ( launch_already_checked ){ _playOrStream(dm, file_index, complete_only, referal); }else{ LaunchManager launch_manager = LaunchManager.getManager(); LaunchManager.LaunchTarget target = launch_manager.createTarget( dm ); launch_manager.launchRequest( target, new LaunchManager.LaunchAction() { public void actionAllowed() { Utils.execSWTThread( new Runnable() { public void run() { _playOrStream(dm, file_index, complete_only, referal); } }); } public void actionDenied( Throwable reason ) { Debug.out( "Launch request denied", reason ); } }); } } private static void _playOrStream(final DownloadManager dm, final int file_index, boolean complete_only, String referal) { if (dm == null) { return; } // if (!canPlay(dm)) { // return false; // } final TOTorrent torrent = dm.getTorrent(); if (torrent == null) { return; } if (PlayUtils.canUseEMP(torrent, file_index,complete_only)) { debug("Can use EMP"); int open_result = openInEMP(dm,file_index,complete_only,referal); if ( open_result == 0 ){ PlatformTorrentUtils.setHasBeenOpened(dm, true); return; }else if ( open_result == 2 ){ debug( "Open in EMP abandoned" ); return; } else { debug("Open EMP Failed"); } // fallback to normal } else { debug("Can't use EMP."); } // We used to pop up a dialog saying we didn't know how to play the file // But now the play toolbar and play 'default' action aren't even enabled // if we can't use EMP. So there's no point. } /** * @param string * * @since 3.0.3.3 */ private static void debug(String string) { if (org.gudy.azureus2.core3.util.Constants.isCVSVersion()) { System.out.println(string); } } private static boolean emp_installing; /** * * @param dm * @return 0=good, 1 = fail, 2 = abandon */ private static int installEMP( String name, final Runnable target ) { synchronized( TorrentListViewsUtils.class ){ if ( emp_installing ){ Debug.out( "EMP is already being installed, secondary launch for " + name + " ignored" ); return( 2 ); } emp_installing = true; } boolean running = false; try{ final PlayerInstaller installer = new PlayerInstaller(); final PlayerInstallWindow window = new PlayerInstallWindow(installer); window.open(); AEThread2 installerThread = new AEThread2("player installer",true) { public void run() { try{ if (installer.install()){ Utils.execSWTThread(new AERunnable() { public void runSupport() { target.run(); } }); } }finally{ synchronized( TorrentListViewsUtils.class ){ emp_installing = false; } } } }; installerThread.start(); running = true; return( 0 ); }catch( Throwable e ){ Debug.out( e ); return( 1 ); }finally{ if ( !running ){ synchronized( TorrentListViewsUtils.class ){ emp_installing = false; } } } } /** * New version accepts map with ASX parameters. If the params are null then is uses the * old version to start the player. If the * * * @param dm - DownloadManager * @return - int: 0 = ok, 1 = fail, 2 = abandon, installation in progress * @since 3.0.4.4 - */ private static int openInEMP( final DownloadManager dm, final int _file_index, final boolean complete_only, final String referal ) { try { int file_index = -1; if ( _file_index == -1 ){ EnhancedDownloadManager edm = DownloadManagerEnhancer.getSingleton().getEnhancedDownload( dm ); if (edm != null) { file_index = edm.getPrimaryFileIndex(); } }else{ file_index = _file_index; } if ( file_index == -1 ){ return( 1 ); } final int f_file_index = file_index; org.gudy.azureus2.plugins.disk.DiskManagerFileInfo file = PluginCoreUtils.wrap( dm ).getDiskManagerFileInfo()[ file_index ]; final URL url; if ((! complete_only ) && file.getDownloaded() != file.getLength()){ url = PlayUtils.getMediaServerContentURL( file ); }else{ url = null; } if ( url != null ){ if ( PlayUtils.isStreamPermitted()){ final boolean show_debug_window = false; new AEThread2( "stream:async" ) { public void run() { StreamManager sm = StreamManager.getSingleton(); synchronized( TorrentListViewsUtils.class ){ if ( current_stream != null && !current_stream.isCancelled()){ if ( current_stream.getURL().equals( url )){ current_stream.setPreviewMode( !current_stream.getPreviewMode()); return; } current_stream.cancel(); current_stream = null; } if ( show_debug_window && ( stream_viewer == null || stream_viewer.isDisposed())){ Utils.execSWTThread( new Runnable() { public void run() { if ( stream_viewer != null ){ stream_viewer.close(); } stream_viewer = new TextViewerWindow( "Stream Status", "Debug information for stream process", "", false ); stream_viewer.addListener( new TextViewerWindow.TextViewerWindowListener() { public void closed() { synchronized( TorrentListViewsUtils.class ){ if ( current_stream != null ){ current_stream.cancel(); current_stream = null; } } } }); } }); } current_stream = sm.stream( dm, f_file_index, url, false, new StreamManagerDownloadListener() { private long last_log = 0; public void updateActivity( String str ) { append( "Activity: " + str ); } public void updateStats( int secs_until_playable, int buffer_secs, long buffer_bytes, int target_secs ) { long now = SystemTime.getMonotonousTime(); if ( now - last_log >= 1000 ){ last_log = now; append( "stats: play in " + secs_until_playable + " sec, buffer=" + DisplayFormatters.formatByteCountToKiBEtc( buffer_bytes ) + "/" + buffer_secs + " sec - target=" + target_secs + " sec" ); } } public void ready() { append( "ready" ); } public void failed( Throwable error ) { append( "failed: " + Debug.getNestedExceptionMessage(error)); Debug.out( error ); } private void append( final String str ) { if ( stream_viewer != null ){ Utils.execSWTThread( new Runnable() { public void run() { if ( stream_viewer != null && !stream_viewer.isDisposed()){ stream_viewer.append( str + "\r\n" ); } } }); } } }); } } }.start(); }else{ FeatureManagerUI.openStreamPlusWindow(referal); } return( 0 ); } synchronized( TorrentListViewsUtils.class ){ if ( current_stream != null && !current_stream.isCancelled()){ current_stream.cancel(); current_stream = null; } } Class epwClass = null; try { // Assumed we have a core, since we are passed a // DownloadManager PluginInterface pi = AzureusCoreFactory.getSingleton().getPluginManager().getPluginInterfaceByID( "azemp", false ); if (pi == null) { return (installEMP(dm.getDisplayName(), new Runnable(){ public void run(){ openInEMP( dm, f_file_index,complete_only,referal ); }})); }else if ( !pi.getPluginState().isOperational()){ return( 1 ); } epwClass = pi.getPlugin().getClass().getClassLoader().loadClass( "com.azureus.plugins.azemp.ui.swt.emp.EmbeddedPlayerWindowSWT"); } catch (ClassNotFoundException e1) { return 1; } try{ Method method = epwClass.getMethod("openWindow", new Class[] { File.class, String.class }); File f = file.getFile( true ); method.invoke(null, new Object[] { f, f.getName() }); return( 0 ); }catch( Throwable e ){ debug( "file/name open method missing" ); } // fall through here if old emp Method method = epwClass.getMethod("openWindow", new Class[] { DownloadManager.class }); method.invoke(null, new Object[] { dm }); return 0; } catch (Throwable e) { e.printStackTrace(); if (e.getMessage() == null || !e.getMessage().toLowerCase().endsWith("only")) { Debug.out(e); } } return 1; }//openInEMP public static int openInEMP( final String name, final URL url ) { Class epwClass = null; try { PluginInterface pi = AzureusCoreFactory.getSingleton().getPluginManager().getPluginInterfaceByID( "azemp", false ); if ( pi == null ){ return( installEMP( name, new Runnable(){ public void run(){ openInEMP( name, url );}} )); }else if ( !pi.getPluginState().isOperational()){ return( 1 ); } epwClass = pi.getPlugin().getClass().getClassLoader().loadClass( "com.azureus.plugins.azemp.ui.swt.emp.EmbeddedPlayerWindowSWT"); } catch (ClassNotFoundException e1) { return 1; } try{ Method method = epwClass.getMethod("openWindow", new Class[] { URL.class, String.class }); method.invoke(null, new Object[] {url, name }); return( 0 ); }catch( Throwable e ){ debug( "URL/name open method missing" ); return( 1 ); } } /** * @param dm * * @since 3.0.0.7 */ private static void handleNoFileExists(final DownloadManager dm) { final UIFunctionsSWT functionsSWT = UIFunctionsManagerSWT.getUIFunctionsSWT(); if (functionsSWT == null) { return; } ManagerUtils.start(dm); String sPrefix = "v3.mb.PlayFileNotFound."; MessageBoxShell mb = new MessageBoxShell( MessageText.getString(sPrefix + "title"), MessageText.getString(sPrefix + "text", new String[] { dm.getDisplayName(), }), new String[] { MessageText.getString(sPrefix + "button.remove"), MessageText.getString(sPrefix + "button.redownload"), MessageText.getString("Button.cancel"), }, 2); mb.setRelatedObject(dm); mb.open(new UserPrompterResultListener() { public void prompterClosed(int i) { if (i == 0) { ManagerUtils.asyncStopDelete(dm, DownloadManager.STATE_STOPPED, true, false, null); } else if (i == 1) { dm.forceRecheck(new ForceRecheckListener() { public void forceRecheckComplete(DownloadManager dm) { ManagerUtils.start(dm); } }); } } }); } /** * Plays or Streams a Download * * @param dm * @param file_index Index of file in torrent to play. -1 to auto-pick * "best" play file. */ public static void playOrStream(final DownloadManager dm, int file_index ) { playOrStream(dm, file_index, PlayUtils.COMPLETE_PLAY_ONLY, false, null ); } }
/** * A Path is an equivalent of the GA gene sequence. For us, it is a valid sequence of towns that has a * fitness according to its distance (calculated with an adjacency matrix). * * A Path can: * 1. mutate to generates diversity - essential * 2. crossOver - mate with a partner to produce a (hopefully) fitter child * 3. calculate its distance and be converted to a useful String. * * Andrew Healy - HDipIT - 13250280 - April 2014 */ import java.util.ArrayList; public class Path { public double distance; public Town[] towns; public Town[] allTowns; private int size; private double[][] matrix; //1-indexed matrix public double fitness; //constructor used for random paths public Path(double[][] matrix, Town[] allTowns) { this.matrix = matrix; this.allTowns = allTowns; towns = new Town[matrix.length]; distance = 0.0; size = 0; fitness = 0.0; } //most commonly used constructor - for the crossover function public Path(double[][] matrix, Town[] allTowns, Town[] inOrder) { this.matrix = matrix; this.allTowns = allTowns; towns = inOrder; distance = 0.0; size = 0; fitness = 0; distance = calcDistance(); size = towns.length; } public Path() { }//used when filling the mating pool. not very important. //return a correctly-formatted string for submission public String makeString() { String str = ""; for (int i = 0; i < size; i++) { str += towns[i].name + "-"; } return str; } //mutation generates diversity - essential //spare mutation function? - swap 2 random Towns (not the start/end though) - works w/ higher mutation factor public void mutate(double mutationRate) { if (Math.random() < mutationRate) { int a = (int) (Math.random() * (size - 3)); int b = (int) (Math.random() * (size - 3)); //do the swap Town townA = new Town(towns[a + 1].id, towns[a + 1].name, towns[a + 1].latitude, towns[a + 1].longitude);//towns[a+1].copy(); Town townB = new Town(towns[b + 1].id, towns[b + 1].name, towns[b + 1].latitude, towns[b + 1].longitude); towns[a + 1] = townB; towns[b + 1] = townA; distance = calcDistance(); //it has a new distance of course! //System.out.println("swapping "+townA.name+" with "+townB.name); } } //mutation generates diversity - essential //better mutation function? - reverses a random subtour and puts it back in a random postion // - works w/ lower mutation factor public void mutate4(double mutationRate) { if (Math.random() < mutationRate) { //the start of the subtour between second and 4th last int a = (int) (Math.random() * (size - 5) + 1); //where to place it between second and second last int b = (int) (Math.random() * (size - 5) + 1); Town[] subTowns = new Town[3]; //reverse when putting back in! for (int i = 0; i < subTowns.length; i++) { subTowns[i] = towns[a + i]; } if (a < b) { //move everything between them down for (int i = a; i < b; i++) { towns[i] = towns[i + 3]; } } else { //move everything between them up for (int i = a; i > b; i--) { towns[i + 2] = towns[i - 1]; } } //put them back in reverse order for (int i = b, j = subTowns.length - 1; i < b + subTowns.length; i++, j--) { towns[i] = subTowns[j]; } distance = calcDistance();//it has a new distance of course! } } //simply counts up according to the adjacency matrix public double calcDistance() { double result = 0.0; for (int i = 0; i < towns.length - 1; i++) { result += matrix[towns[i].id][towns[i + 1].id]; } return result; } //at the start random paths are required. but they must be valid public void randomPath(SymbolGraph.Vertex origin) { //keeps track of visited towns boolean[] visited = new boolean[allTowns.length]; int added = 0; // Haven't added any cities towns[added++] = allTowns[origin.index() - 1]; visited[origin.index() - 1] = true; while (added < allTowns.length) { int rand = (int) (Math.random() * allTowns.length); // If we have haven't visited this random town, add it if (!visited[rand]) { towns[added++] = allTowns[rand]; visited[rand] = true; } } //join up the start and the end and calculate the distance towns[added] = towns[0]; distance = calcDistance(); size = towns.length; } //crossover is the way to get better Paths from a previous generation. Also maintains diversity. //using the edge recombinator technique - return an array of towns in order //the algorithm is described here: http://en.wikipedia.org/wiki/Edge_recombination_operator public Town[] crossOver(Path partner) { //try { //get the adjacency matrices ArrayList[] neighbours = getNeighbours(); ArrayList[] p_neighbours = partner.getNeighbours(); //take the union of these matrices ArrayList[] union = new ArrayList[towns.length]; for (int i = 1; i < neighbours.length; i++) { ArrayList temp = new ArrayList(4); for (int j = 0; j < 2; j++) { //System.out.println(neighbours[i]); Integer candidate = (Integer) neighbours[i].get(j); temp.add(candidate); } for (int j = 0; j < 2; j++) { Integer candidate = (Integer) p_neighbours[i].get(j); if (!temp.contains(candidate)) { temp.add(candidate); } } union[i] = temp; } ArrayList<Integer> list = new ArrayList<Integer>(); //to store the combined path //pick the first at random from the firsts Integer n = (Math.random() < 0.5) ? new Integer(towns[0].id) : new Integer(partner.towns[0].id); //until each town is in once while (list.size() < towns.length - 1) { list.add(n); //remove n from all neighbour lists for (int i = 1; i < union.length; i++) { boolean removed = union[i].remove(n); } int n_int = n.intValue(); ArrayList find_n = union[n_int]; if (find_n.size() > 0) {//n's neighbour list is non-empty //set initial values Integer leastI = (Integer) find_n.get(0); int least_size = union[leastI.intValue()].size(); for (int i = 1; i < find_n.size(); i++) { Integer testI = (Integer) find_n.get(i); if (union[testI.intValue()].size() < least_size) { //found new lowest, update both least_size = union[testI.intValue()].size(); leastI = (Integer) find_n.get(i); } else if (union[testI.intValue()].size() == least_size) { //found equal lowest, choose randomly if (Math.random() < 0.5) { leastI = (Integer) find_n.get(i); } } } n = leastI; } else {//neighbour list is empty so choose closest from the closest unvisited double least = 100000; Integer choose = new Integer(1); for (int i = 1; i < towns.length; i++) { Integer temp = new Integer(i); if (!list.contains(temp) && matrix[towns[i].id][towns[n_int].id] < least) { least = matrix[towns[i].id][towns[n_int].id]; choose = temp; } } n = choose; } }//end while - we've found enough Towns Integer first = (Integer) list.get(0); list.add(first); //join it up! Town[] newTowns = new Town[list.size()];//the array we will return //convert those Integers to Towns for (int i = 0; i < list.size(); i++) { Integer temp = (Integer) list.get(i); newTowns[i] = allTowns[temp.intValue() - 1]; } return newTowns; //slim possibility of a NullPointerException though } /*catch (Exception e) { System.out.println(e + " caught while towns (" + this.size + ") = "+ makeString()); return towns; } */ // } //convience function used by the crossover function. //returns a kind of "neighbour matrix" of Integers. private ArrayList[] getNeighbours() { ArrayList[] lists = new ArrayList[towns.length]; //1-indexed //the start/end is a special case ArrayList temp = new ArrayList(2); temp.add(towns[towns.length - 2].id); temp.add(towns[1].id); lists[towns[0].id] = temp; for (int i = 1; i < towns.length - 1; i++) { ArrayList temp2 = new ArrayList(2); temp2.add(towns[i - 1].id); temp2.add(towns[i + 1].id); lists[towns[i].id] = temp2; } return lists; } }
package com.example.snapup_android.service; import com.example.snapup_android.pojo.FeedBack; import java.util.List; public interface FeedBackService { public boolean createFeedBack(FeedBack feedBack); public List<FeedBack> getAllFeedBack(); public boolean deleteFeedBack(FeedBack feedBack); }
package com.stripe.model.issuing; import com.google.gson.annotations.SerializedName; import com.stripe.Stripe; import com.stripe.exception.StripeException; import com.stripe.model.BalanceTransaction; import com.stripe.model.ExpandableField; import com.stripe.model.HasId; import com.stripe.net.ApiResource; import com.stripe.net.RequestOptions; import com.stripe.param.issuing.DisputeCreateParams; import com.stripe.param.issuing.DisputeListParams; import com.stripe.param.issuing.DisputeRetrieveParams; import com.stripe.param.issuing.DisputeUpdateParams; import java.util.List; import java.util.Map; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; @Getter @Setter @EqualsAndHashCode(callSuper = false) public class Dispute extends ApiResource implements HasId { /** List of balance transactions associated with this dispute. */ @SerializedName("balance_transactions") List<BalanceTransaction> balanceTransactions; /** Unique identifier for the object. */ @Getter(onMethod_ = {@Override}) @SerializedName("id") String id; /** * Has the value {@code true} if the object exists in live mode or the value {@code false} if the * object exists in test mode. */ @SerializedName("livemode") Boolean livemode; /** * String representing the object's type. Objects of the same type share the same value. * * <p>Equal to {@code issuing.dispute}. */ @SerializedName("object") String object; /** The transaction being disputed. */ @SerializedName("transaction") @Getter(lombok.AccessLevel.NONE) @Setter(lombok.AccessLevel.NONE) ExpandableField<Transaction> transaction; /** Get ID of expandable {@code transaction} object. */ public String getTransaction() { return (this.transaction != null) ? this.transaction.getId() : null; } public void setTransaction(String id) { this.transaction = ApiResource.setExpandableFieldId(id, this.transaction); } /** Get expanded {@code transaction}. */ public Transaction getTransactionObject() { return (this.transaction != null) ? this.transaction.getExpanded() : null; } public void setTransactionObject(Transaction expandableObject) { this.transaction = new ExpandableField<Transaction>(expandableObject.getId(), expandableObject); } /** * Returns a list of Issuing <code>Dispute</code> objects. The objects are sorted in descending * order by creation date, with the most recently created object appearing first. */ public static DisputeCollection list(Map<String, Object> params) throws StripeException { return list(params, (RequestOptions) null); } /** * Returns a list of Issuing <code>Dispute</code> objects. The objects are sorted in descending * order by creation date, with the most recently created object appearing first. */ public static DisputeCollection list(Map<String, Object> params, RequestOptions options) throws StripeException { String url = String.format("%s%s", Stripe.getApiBase(), "/v1/issuing/disputes"); return ApiResource.requestCollection(url, params, DisputeCollection.class, options); } /** * Returns a list of Issuing <code>Dispute</code> objects. The objects are sorted in descending * order by creation date, with the most recently created object appearing first. */ public static DisputeCollection list(DisputeListParams params) throws StripeException { return list(params, (RequestOptions) null); } /** * Returns a list of Issuing <code>Dispute</code> objects. The objects are sorted in descending * order by creation date, with the most recently created object appearing first. */ public static DisputeCollection list(DisputeListParams params, RequestOptions options) throws StripeException { String url = String.format("%s%s", Stripe.getApiBase(), "/v1/issuing/disputes"); return ApiResource.requestCollection(url, params, DisputeCollection.class, options); } /** Creates an Issuing <code>Dispute</code> object. */ public static Dispute create(Map<String, Object> params) throws StripeException { return create(params, (RequestOptions) null); } /** Creates an Issuing <code>Dispute</code> object. */ public static Dispute create(Map<String, Object> params, RequestOptions options) throws StripeException { String url = String.format("%s%s", Stripe.getApiBase(), "/v1/issuing/disputes"); return ApiResource.request(ApiResource.RequestMethod.POST, url, params, Dispute.class, options); } /** Creates an Issuing <code>Dispute</code> object. */ public static Dispute create(DisputeCreateParams params) throws StripeException { return create(params, (RequestOptions) null); } /** Creates an Issuing <code>Dispute</code> object. */ public static Dispute create(DisputeCreateParams params, RequestOptions options) throws StripeException { String url = String.format("%s%s", Stripe.getApiBase(), "/v1/issuing/disputes"); return ApiResource.request(ApiResource.RequestMethod.POST, url, params, Dispute.class, options); } /** * Updates the specified Issuing <code>Dispute</code> object by setting the values of the * parameters passed. Any parameters not provided will be left unchanged. */ public Dispute update(Map<String, Object> params) throws StripeException { return update(params, (RequestOptions) null); } /** * Updates the specified Issuing <code>Dispute</code> object by setting the values of the * parameters passed. Any parameters not provided will be left unchanged. */ public Dispute update(Map<String, Object> params, RequestOptions options) throws StripeException { String url = String.format( "%s%s", Stripe.getApiBase(), String.format("/v1/issuing/disputes/%s", ApiResource.urlEncodeId(this.getId()))); return ApiResource.request(ApiResource.RequestMethod.POST, url, params, Dispute.class, options); } /** * Updates the specified Issuing <code>Dispute</code> object by setting the values of the * parameters passed. Any parameters not provided will be left unchanged. */ public Dispute update(DisputeUpdateParams params) throws StripeException { return update(params, (RequestOptions) null); } /** * Updates the specified Issuing <code>Dispute</code> object by setting the values of the * parameters passed. Any parameters not provided will be left unchanged. */ public Dispute update(DisputeUpdateParams params, RequestOptions options) throws StripeException { String url = String.format( "%s%s", Stripe.getApiBase(), String.format("/v1/issuing/disputes/%s", ApiResource.urlEncodeId(this.getId()))); return ApiResource.request(ApiResource.RequestMethod.POST, url, params, Dispute.class, options); } /** Retrieves an Issuing <code>Dispute</code> object. */ public static Dispute retrieve(String dispute) throws StripeException { return retrieve(dispute, (Map<String, Object>) null, (RequestOptions) null); } /** Retrieves an Issuing <code>Dispute</code> object. */ public static Dispute retrieve(String dispute, RequestOptions options) throws StripeException { return retrieve(dispute, (Map<String, Object>) null, options); } /** Retrieves an Issuing <code>Dispute</code> object. */ public static Dispute retrieve(String dispute, Map<String, Object> params, RequestOptions options) throws StripeException { String url = String.format( "%s%s", Stripe.getApiBase(), String.format("/v1/issuing/disputes/%s", ApiResource.urlEncodeId(dispute))); return ApiResource.request(ApiResource.RequestMethod.GET, url, params, Dispute.class, options); } /** Retrieves an Issuing <code>Dispute</code> object. */ public static Dispute retrieve( String dispute, DisputeRetrieveParams params, RequestOptions options) throws StripeException { String url = String.format( "%s%s", Stripe.getApiBase(), String.format("/v1/issuing/disputes/%s", ApiResource.urlEncodeId(dispute))); return ApiResource.request(ApiResource.RequestMethod.GET, url, params, Dispute.class, options); } }
package com.pokemon.pokemoncollection.controller; import com.pokemon.pokemoncollection.service.login.LoginService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class HomeController { private LoginService loginService; public HomeController(LoginService loginService) { this.loginService = loginService; } @GetMapping public String getHomePage(Model model){ if(loginService.isLogged()){ String mail = loginService.getLoggerUserMail(); model.addAttribute("email", mail); } else { model.addAttribute("email", "Niezalogowany"); } return "index"; } }
/** * Write a description of class SeqGenMinMax here. * * @author (your name) * @version (a version number or a date) */ public class SeqGenMinMax extends SeqGenMax { // instance variables - replace the example below with your own private int min; public SeqGenMinMax(int min, int max) { super(max); this.min = min; } }
/* * NAME: Bryan Talavera * PID: A14378593 */ /** * This is a Queue Implementation which utilizes a Doubly Linked List * @param <T> generic container * @author Bryan Talavera * @since 04/25/21 */ public class DLLQueue<T> { private DoublyLinkedList<T> queue; public DLLQueue() { this.queue = new DoublyLinkedList<>(); } /** * This method returns the size of the stack * @return number of elements currently stored */ public int size() { return this.queue.size(); } /** * Method checks if our stack is empty * @return True if our stack is empty, else it returns false */ public boolean isEmpty() { return this.size() == 0; } /** * Adding our data to the back of the queue * @param data - the data we will add to the queue * @throws IllegalArgumentException - if data is null */ public void enqueue(T data) { try{ if (data == null) throw new IllegalArgumentException(); this.queue.add(data); }catch (IllegalArgumentException err){ throw err; } } /** * This Method removes the top elem from the queue and returns it. * @return the first T value if there are elements, otherwise null */ public T dequeue() { if (this.isEmpty()) return null; return this.queue.remove(0); } /** * "Peek" at the top element of the queue w/o returning it * @return - the first element of our queue */ public T peek() { if (this.isEmpty()) return null; return this.queue.get(0); } }
package com.micHon.buliderClassic; public class BigCarBuilder implements CarBuilder { private Car car; public BigCarBuilder() { this.car = car; } public void buildWheels() { this.car.setWheels("Big"); } public void buildBody() { this.car.setBody("Big"); } public void buildEngine() { this.car.setEngine("Big"); } public void buildWindows() { this.car.setWindows("Big"); } public Car getCar() { return car; } }
package com.kamilbolka.util.database; public interface Database { String LOCAL_DATABASE_FILE_NAME = "database.json"; String RECORDING_TAG = "recording"; String MODULE_TAG = "module"; // Main String FIREBASE_OWNER_ID_TAG = "firebaseOwnerID"; String MODULE_NAME_TAG = "moduleName"; String RECORDING_NAME_TAG = "recordingName"; String TIME_TAKEN_TAG = "length"; // This was changed // Status String ONLINE_LINK_TAG = "onlineLink"; String UPLOADED_TAG= "uploaded"; String RECORDING_IS_UPLOADED_TAG = "recordingIsUploaded"; String SLIDE_IS_UPLOADED_TAG = "slideIsUploaded"; String RECORDING_IS_DOWNLOADED_TAG = "recordingIsDownloaded"; String SLIDE_IS_DOWNLOADED_TAG = "recordingIsDownloaded"; // Array String RECORDING_ARRAY_TAG = "recordingArray"; String RECORDING_TIME_STAMP_TAG = "recordingTimeStamp"; String SLIDE_ARRAY_TAG = "slideArray"; // Date String MODULE_CREATED_DATE_TAG = "moduleCreatedDate"; String MODULE_MODIFIED_DATE_TAG = "moduleModifiedDate"; String PROJECT_CREATED_DATE_TAG = "createdDate"; String PROJECT_MODIFIED_DATE_TAG = "modifiedDate"; // Size String RECORDING_SIZE_KILOBYTE_TAG = "recordingSizeInKilobyte"; String SLIDE_SIZE_KILOBYTE_TAG = "slideSizeInKilobyte"; // Setting String SETTING_AUTO_UPLOAD_TAG = "autoUpload"; String SETTING_AUTO_DOWNLOAD_TAG = "autoDownload"; }
package com.xxglpt.sjjs.controller; import java.util.HashMap; import java.util.List; import javax.annotation.Resource; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import com.hdsx.webutil.struts.BaseActionSupport; import com.xxglpt.utile.EasyUIPage; import com.xxglpt.sjjs.bean.Sjff; import com.xxglpt.utile.JsonUtils; import com.xxglpt.utile.ResponseUtils; import com.xxglpt.utile.WordOperation; import com.xxglpt.sjjs.server.SjffServer; /** * 系统管理Controller层 * @author xunq * */ @Scope("prototype") @Controller public class SjffController extends BaseActionSupport{ private static final long serialVersionUID = -1512493918772500846L; private int page = 1; private int rows = 10; @Resource(name = "sjffServerImpl") private SjffServer sjffServer; private Sjff sjff; private String id; private String xmlName; /** * 汇交测绘数据管理列表 */ public void selectSjffList(){ sjff.setPage(page); sjff.setRows(rows); int count=sjffServer.selectSjffListCount(sjff); List<Sjff> list=sjffServer.selectSjffList(sjff); EasyUIPage<Sjff> e=new EasyUIPage<Sjff>(); e.setRows(list); e.setTotal(count); try { JsonUtils.write(e, getresponse().getWriter()); } catch (Exception e1) { e1.printStackTrace(); } } public void selectSjffById(){ Sjff m=sjffServer.selectSjffById(sjff); try { JsonUtils.write(m, getresponse().getWriter()); } catch (Exception e1) { e1.printStackTrace(); } } /** * 添加汇交测绘数据 */ public void insertSjff(){ boolean b=sjffServer.insertSjff(sjff); System.out.println(sjff.getLxdh()); if(b!=true){ ResponseUtils.write(getresponse(), "false"); }else{ ResponseUtils.write(getresponse(), "true"); } } /** * 删除汇交测绘数据 */ public void deleteSjff(){ boolean bl = sjffServer.deleteSjff(id); if(bl == true){ ResponseUtils.write(getresponse(), "true"); }else{ ResponseUtils.write(getresponse(), "false"); } } public void sjffDownDoc(){ HashMap map=sjffServer.selectSjffById2(sjff); //HashMap map=new HashMap(); //System.out.println(map.get("A1")); map.put("a1",map.get("A1")); map.put("a2",map.get("A2")); map.put("a3",map.get("A3")); map.put("a4",map.get("A4")); map.put("a5",map.get("A5")); map.put("a6",map.get("A6")); map.put("a7",map.get("A7")); map.put("a8",map.get("A8")); map.put("a9",map.get("A9")); map.put("a10",map.get("A10")); map.put("a11",map.get("A11")); map.put("a12",map.get("A12")); map.put("a13",map.get("A13")); map.put("a14",map.get("A14")); map.put("a15",map.get("A15")); map.put("a16",map.get("A16")); map.put("a17",map.get("A17")); map.put("a18",map.get("A18")); map.put("a19",map.get("A19")); map.put("a20",map.get("A20")); map.put("a21",map.get("A21")); map.put("a22",map.get("A22")); map.put("a23",map.get("A23").toString().replaceAll("\n","<w:p></w:p>")); map.put("a24",map.get("A24").toString().replaceAll("\n","<w:p></w:p>")); map.put("a25",map.get("A25").toString().replaceAll("\n","<w:p></w:p>")); map.put("a26",map.get("A26").toString().replaceAll("\n","<w:p></w:p>")); map.put("a27",map.get("A27").toString().replaceAll("\n","<w:p></w:p>")); map.put("a28",map.get("A28").toString().replaceAll("\n","<w:p></w:p>")); map.put("a29",map.get("A29").toString().replaceAll("\n","<w:p></w:p>")); xmlName="广元市地理信息数据使用申请资料.xml"; WordOperation wo=new WordOperation(); wo.createDoc(map,xmlName,getresponse()); } /** * 删除汇交测绘数据 */ public void updateSjff(){ boolean bl = sjffServer.updateSjff(sjff); if(bl == true){ ResponseUtils.write(getresponse(), "true"); }else{ ResponseUtils.write(getresponse(), "false"); } } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public int getRows() { return rows; } public void setRows(int rows) { this.rows = rows; } public Sjff getSjff() { return sjff; } public void setSjff(Sjff sjff) { this.sjff = sjff; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getXmlName() { return xmlName; } public void setXmlName(String xmlName) { this.xmlName = xmlName; } }
package org.eldslott.hb.entity; /** * @author <a href="mailto:oscar.eriks@gmail.com">Oscar Eriksson</a> * @date 12/18/13 */ public interface Actor { }
package com.lch.mvcframework.annotation; import com.lch.mvcframework.enums.MethodEnum; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author: liuchenhui * @create: 2019-12-11 17:58 **/ @Target({ElementType.METHOD, ElementType.TYPE}) @Documented @Retention(RetentionPolicy.RUNTIME) public @interface RequestMapping { /** * url */ String value() default ""; /** * 请求方法 */ MethodEnum method() default MethodEnum.GET; }
package pkgPokerBLL; import java.util.ArrayList; import java.util.HashMap; import java.util.UUID; public class Table { private UUID TableID; // Modified from ArrayList to HashMap private HashMap<UUID,Player> TablePlayers = new HashMap<UUID,Player>(); public Table() { super(); TableID = UUID.randomUUID(); } public UUID getTableID() { return TableID; } //Modified these next two methods public Table AddPlayerToTable(Player p) { TablePlayers.put(p.getPlayerID(), p); return this; } public Table RemovePlayerFromTable(Player p) { TablePlayers.remove(p.getPlayerID()); return this; } //Modified, used only to test that the methods work correctly in the JUNIT test public int getSizeTable() { return TablePlayers.size(); } }
package com.example.android.moneytran; import android.app.Dialog; import android.content.Context; import android.content.res.Resources; import android.os.Bundle; import android.view.View; import androidx.annotation.NonNull; import androidx.databinding.DataBindingUtil; import com.example.android.moneytran.currency.BritishPound; import com.example.android.moneytran.currency.ChineseYuan; import com.example.android.moneytran.currency.CurrentCurrency; import com.example.android.moneytran.currency.Euro; import com.example.android.moneytran.currency.JapaneseYen; import com.example.android.moneytran.currency.RussianRuble; import com.example.android.moneytran.currency.UkrainianHryvnia; import com.example.android.moneytran.currency.UnitedStatesDollar; import com.example.android.moneytran.databinding.BottomSheetBinding; import com.google.android.material.bottomsheet.BottomSheetBehavior; import com.google.android.material.bottomsheet.BottomSheetDialog; import com.google.android.material.bottomsheet.BottomSheetDialogFragment; /* 29.09.2020 1) For BottomSheet could be used another approach: setting RecyclerView and custom RadioGroup, worth considering just in case of adding a lot of currencies. 2) title "Choose currency" moves badly (when BottomSheet changes state). Developed according to the design red lines. */ public class BottomSheet extends BottomSheetDialogFragment { private BottomSheetBehavior bottomSheetBehavior; private BottomSheetBinding binding; onCurrencyChangedListener eventListener; public interface onCurrencyChangedListener { void currentCurrencyChanged(); } @Override public void onAttach(@NonNull Context context) { super.onAttach(context); try { eventListener = (onCurrencyChangedListener) getActivity(); } catch (ClassCastException e) { throw new ClassCastException("Activity must implement onCurrencyChangedListener"); } } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { BottomSheetDialog bottomSheet = (BottomSheetDialog) super.onCreateDialog(savedInstanceState); View rootView = View.inflate(getContext(), R.layout.bottom_sheet, null); binding = DataBindingUtil.bind(rootView); bottomSheet.setContentView(rootView); bottomSheetBehavior = BottomSheetBehavior.from((View) (rootView.getParent())); //setting Peek at the 16:9 ratio keyline of its parent. bottomSheetBehavior.setPeekHeight(BottomSheetBehavior.PEEK_HEIGHT_AUTO); //setting height of bottom sheet for expanded state binding.extraSpace.setMinimumHeight((Resources.getSystem().getDisplayMetrics().heightPixels) / 3); binding.expandedStateClose.setOnClickListener(view -> dismiss()); binding.expandedStateBar.setVisibility(View.GONE); setCurrenciesUnchecked(); setCurrentCurrencyChecked(); setCardViewsListeners(); bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() { @Override public void onStateChanged(@NonNull View view, int i) { if (BottomSheetBehavior.STATE_EXPANDED == i) { binding.expandedStateBar.setVisibility(View.VISIBLE); binding.collapsedStateBar.setVisibility(View.GONE); } if (BottomSheetBehavior.STATE_COLLAPSED == i) { binding.collapsedStateBar.setVisibility(View.VISIBLE); binding.expandedStateBar.setVisibility(View.GONE); } if (BottomSheetBehavior.STATE_HIDDEN == i) { dismiss(); } } @Override public void onSlide(@NonNull View view, float v) { } }); return bottomSheet; } @Override public void onStart() { super.onStart(); bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); } @Override public void onPause() { super.onPause(); eventListener.currentCurrencyChanged(); } @Override public int getTheme() { return R.style.BottomSheetDialogTheme; } private void setCurrenciesUnchecked() { binding.imageViewCheckEUR.setVisibility(View.GONE); binding.imageViewCheckUSD.setVisibility(View.GONE); binding.imageViewCheckGBP.setVisibility(View.GONE); binding.imageViewCheckRUB.setVisibility(View.GONE); binding.imageViewCheckCNY.setVisibility(View.GONE); binding.imageViewCheckJPY.setVisibility(View.GONE); binding.imageViewCheckUAH.setVisibility(View.GONE); } private void setCurrentCurrencyChecked() { if (CurrentCurrency.currentCurrency instanceof Euro) { binding.imageViewCheckEUR.setVisibility(View.VISIBLE); } if (CurrentCurrency.currentCurrency instanceof UnitedStatesDollar) { binding.imageViewCheckUSD.setVisibility(View.VISIBLE); } if (CurrentCurrency.currentCurrency instanceof BritishPound) { binding.imageViewCheckGBP.setVisibility(View.VISIBLE); } if (CurrentCurrency.currentCurrency instanceof RussianRuble) { binding.imageViewCheckRUB.setVisibility(View.VISIBLE); } if (CurrentCurrency.currentCurrency instanceof ChineseYuan) { binding.imageViewCheckCNY.setVisibility(View.VISIBLE); } if (CurrentCurrency.currentCurrency instanceof JapaneseYen) { binding.imageViewCheckJPY.setVisibility(View.VISIBLE); } if (CurrentCurrency.currentCurrency instanceof UkrainianHryvnia) { binding.imageViewCheckUAH.setVisibility(View.VISIBLE); } } private void setCardViewsListeners() { binding.cardViewCurrencyEUR.setOnClickListener(v -> { setCurrenciesUnchecked(); CurrentCurrency.currentCurrency = new Euro(); setCurrentCurrencyChecked(); }); binding.cardViewCurrencyUSD.setOnClickListener(v -> { setCurrenciesUnchecked(); CurrentCurrency.currentCurrency = new UnitedStatesDollar(); setCurrentCurrencyChecked(); }); binding.cardViewCurrencyGBP.setOnClickListener(v -> { setCurrenciesUnchecked(); CurrentCurrency.currentCurrency = new BritishPound(); setCurrentCurrencyChecked(); }); binding.cardViewCurrencyRUB.setOnClickListener(v -> { setCurrenciesUnchecked(); CurrentCurrency.currentCurrency = new RussianRuble(); setCurrentCurrencyChecked(); }); binding.cardViewCurrencyCNY.setOnClickListener(v -> { setCurrenciesUnchecked(); CurrentCurrency.currentCurrency = new ChineseYuan(); setCurrentCurrencyChecked(); }); binding.cardViewCurrencyJPY.setOnClickListener(v -> { setCurrenciesUnchecked(); CurrentCurrency.currentCurrency = new JapaneseYen(); setCurrentCurrencyChecked(); }); binding.cardViewCurrencyUAH.setOnClickListener(v -> { setCurrenciesUnchecked(); CurrentCurrency.currentCurrency = new UkrainianHryvnia(); setCurrentCurrencyChecked(); }); } }
package collection; import java.util.Comparator; import java.util.HashSet; import java.util.TreeSet; public class HashSetDemo { public static void main(String[] args) { TreeSet hs=new TreeSet(); //HashSet hs=new HashSet(); hs.add("Ram"); hs.add("Shyam"); hs.add("Karan"); System.out.println(hs); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package controller.character.helpers; import model.character.AbstractCharacter; /** * * @author Dr.Chase */ public class StartingSkillPointsHelper { private static final int CLASS_A_MAX_SKILLPOINTS = 50; private static final int CLASS_B_MAX_SKILLPOINTS = 40; private static final int CLASS_C_MAX_SKILLPOINTS = 34; private static final int CLASS_D_MAX_SKILLPOINTS = 30; private static final int CLASS_E_MAX_SKILLPOINTS = 27; private AbstractCharacter character; public StartingSkillPointsHelper(AbstractCharacter character) { this.character = character; } public AbstractCharacter getCharacter() { return character; } public void setCharacter(AbstractCharacter character) { this.character = character; } public static int getMaxSkillpointsFromCharacter(AbstractCharacter character) { int nTemp = 0; switch (character.getPrioSkills()) { case PRIORITY_A: nTemp = CLASS_A_MAX_SKILLPOINTS; break; case PRIORITY_B: nTemp = CLASS_B_MAX_SKILLPOINTS; break; case PRIORITY_C: nTemp = CLASS_C_MAX_SKILLPOINTS; break; case PRIORITY_D: nTemp = CLASS_D_MAX_SKILLPOINTS; break; case PRIORITY_E: nTemp = CLASS_E_MAX_SKILLPOINTS; break; } return nTemp; } }
package com.samson.chess; public class IllegalChessMoveException extends IllegalArgumentException { public IllegalChessMoveException() { super("A move was performed which was not legal on the given board."); } public IllegalChessMoveException(String message) { super(message); } }
package com.microsoft.bingads.v11.api.test.entities.ad_extension.site_link2.read; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses( { BulkSitelink2AdExtensionReadFromRowValuesDisplayTextTest.class, BulkSitelink2AdExtensionReadFromRowValuesDescription1Test.class, BulkSitelink2AdExtensionReadFromRowValuesDescription2Test.class, BulkSitelink2AdExtensionReadFromRowValuesDestinationUrlTest.class, BulkSitelink2AdExtensionReadFromRowValuesFinalMobileUrlsTest.class, BulkSitelink2AdExtensionReadFromRowValuesFinalUrlsTest.class, BulkSitelink2AdExtensionReadFromRowValuesTrackingTemplateTest.class, BulkSitelink2AdExtensionReadFromRowValuesUrlCustomParametersTest.class } ) public class BulkSitelink2AdExtensionReadTests { }
package com.nt.service; import java.io.File; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Service; @Service("service") public class FileDownloadServiceImpl implements FileDownloadService { @Override public List<String> fetchAllFile(String uploadStore) { //create File object reprsenting uplodStore folder (E:/store) File fileStore=new File(uploadStore); //get All files and subfolders of uploadStore folder (E:/store) File content[]=fileStore.listFiles(); List<String> fileNamesList=new ArrayList<>(); for(File f:content) { if(f.isFile()) fileNamesList.add(f.getName()); }//for return fileNamesList; } }
package pl.basistam.web; import pl.basistam.books.Book; import pl.basistam.books.State; import pl.basistam.ejb.Library; import javax.faces.bean.ApplicationScoped; import javax.faces.bean.ManagedBean; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import java.util.Hashtable; import java.util.List; @ManagedBean(name = "libraryBean") @ApplicationScoped public class LibraryBean { private Library library; public LibraryBean() throws NamingException { this.library = lookupLibraryEjb(); Book book = new Book(); } public List<Book> getReservedBooks() { return library.getBooks(State.RESERVED); } public List<Book> getLoanedBooks() { return library.getBooks(State.LOANED); } public List<Book> getIdleBooks() { return library.getBooks(State.IDLE); } public void reserveBook(String isbn) { try { library.changeBookState(isbn, State.RESERVED); } catch (NumberFormatException e) { e.printStackTrace(); } } public void loanBook(String isbn) { try { library.changeBookState(isbn, State.LOANED); } catch (NumberFormatException e) { e.printStackTrace(); } } public void returnBook(String isbn) { try { library.changeBookState(isbn, State.IDLE); } catch (NumberFormatException e) { e.printStackTrace(); } } private Library lookupLibraryEjb() throws NamingException { final Hashtable<String, String> jndiProperties = new Hashtable<String, String>(); jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming"); final Context context = new InitialContext(jndiProperties); return (Library) context.lookup("ejb:/library-ejb/LibraryImpl!pl.basistam.ejb.Library"); } }
/* * Copyright 2015 Grzegorz Skorupa <g.skorupa at gmail.com>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cricketmsf; import com.cedarsoftware.util.io.JsonWriter; import org.cricketmsf.annotation.EventHook; import com.sun.net.httpserver.Filter; import org.cricketmsf.config.AdapterConfiguration; import org.cricketmsf.config.ConfigSet; import org.cricketmsf.config.Configuration; import org.cricketmsf.in.InboundAdapter; import org.cricketmsf.out.OutboundAdapter; import java.util.logging.Logger; import static java.lang.Thread.MIN_PRIORITY; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.TimeZone; import java.util.UUID; import java.util.logging.Level; import org.cricketmsf.config.HttpHeader; import org.cricketmsf.out.DispatcherException; import org.cricketmsf.out.DispatcherIface; import org.cricketmsf.out.EventDispatcherAdapter; import org.cricketmsf.out.log.LoggerAdapterIface; import org.cricketmsf.out.log.StandardLogger; /** * Microkernel. * * @author Grzegorz Skorupa */ public abstract class Kernel { // emergency LOGGER private static final Logger LOGGER = Logger.getLogger(org.cricketmsf.Kernel.class.getName()); // standard logger protected static LoggerAdapterIface logger = new StandardLogger().getDefault(); // event dispatcher protected DispatcherIface eventDispatcher = null; // singleton private static Object instance = null; private UUID uuid; //autogenerated when service starts - unpredictable private HashMap<String, String> eventHookMethods = new HashMap<>(); private String id; //identifying service private String name; // name identifying service deployment (various names will have the same id) public boolean liftMode = false; // adapters public HashMap<String, Object> adaptersMap = new HashMap<>(); // user defined properties public HashMap<String, Object> properties = new HashMap<>(); public SimpleDateFormat dateFormat = null; // http server private String host = null; private int port = 0; private Httpd httpd; private boolean httpHandlerLoaded = false; private boolean inboundAdaptersLoaded = false; private static long eventSeed = System.currentTimeMillis(); protected ConfigSet configSet = null; private Filter securityFilter = new SecurityFilter(); private ArrayList corsHeaders; private long startedAt = 0; private boolean started = false; private boolean initialized=false; public Kernel() { } public boolean isStarted() { return started; } void setStartedAt(long time) { startedAt = time; } private void addHookMethodNameForEvent(String eventCategory, String hookMethodName) { eventHookMethods.put(eventCategory, hookMethodName); } private void getEventHooks() { EventHook ah; String eventCategory; getLogger().print("REGISTERING EVENT HOOKS"); // for every method of a Kernel instance (our service class extending Kernel) for (Method m : this.getClass().getMethods()) { ah = (EventHook) m.getAnnotation(EventHook.class); // we search for annotated method if (ah != null) { eventCategory = ah.eventCategory(); addHookMethodNameForEvent(eventCategory, m.getName()); getLogger().print("hook method for event category " + eventCategory + " : " + m.getName()); } } getLogger().print("END REGISTERING EVENT HOOKS"); } private String getHookMethodNameForEvent(String eventCategory) { String result; result = eventHookMethods.get(eventCategory); if (null == result) { result = eventHookMethods.get("*"); } return result; } /** * Invokes the service method annotated as dedicated to this event category * * @param event event object that should be processed */ public Object handleEvent(Event event) { Object o = null; try { Method m = getClass() .getMethod(getHookMethodNameForEvent(event.getCategory()), Event.class); o = m.invoke(this, event); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { e.printStackTrace(); } return o; } /** * Sends event object to the event queue using registered dispatcher adapter. In case the dispatcher adapter is not registered or throws exception, * the Kernel.handle(event) method will be called. * * @param event the event object that should be send to the event queue * @return null if dispatcher adapter is registered, otherwise returns result of the Kernel.handle(event) method */ public Object dispatchEvent(Event event){ try { eventDispatcher.dispatch(event); return null; } catch (NullPointerException | DispatcherException ex) { return handleEvent(event); } } /** * Invokes the service method annotated as dedicated to this event category * * @param event event object that should be processed */ public static Object handle(Event event) { return Kernel.getInstance().handleEvent(event); } public HashMap<String, Object> getAdaptersMap() { return adaptersMap; } protected Object getRegistered(String adapterName) { return adaptersMap.get(adapterName); } //protected Object registerAdapter(String adapterName, Object adapter) { // return adaptersMap.put(adapterName, adapter); //} /** * Returns next unique identifier for Event. * * @return next unique identifier */ public static long getEventId() { return eventSeed += 1; } /** * Must be used to set adapter variables after instantiating them according * to the configuration in cricket.json file. Look at EchoService example. */ public abstract void getAdapters(); public static Kernel getInstance() { return (Kernel) instance; } public static Object getInstanceWithProperties(Class c, Configuration config) { if (instance != null) { return instance; } try { instance = c.newInstance(); ((Kernel) instance).setUuid(UUID.randomUUID()); ((Kernel) instance).setId(config.getId()); ((Kernel) instance).setName((String) config.getProperties().getOrDefault("SRVC_NAME_ENV_VARIABLE", "CRICKET_NAME")); ((Kernel) instance).setProperties(config.getProperties()); ((Kernel) instance).configureTimeFormat(config); ((Kernel) instance).loadAdapters(config); } catch (Exception e) { instance = null; LOGGER.log(Level.SEVERE, "{0}:{1}", new Object[]{e.getStackTrace()[0].toString(), e.getStackTrace()[1].toString()}); e.printStackTrace(); } return instance; } private void configureTimeFormat(Configuration config) { dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z"); dateFormat.setTimeZone(TimeZone.getTimeZone(config.getProperty("time-zone", "GMT"))); } private void printHeader(String version) { getLogger().print(""); getLogger().print(" __| \\ | __| Cricket"); getLogger().print(" ( |\\/ | _| Microservices Framework"); getLogger().print("\\___|_| _|_| version " + version); getLogger().print(""); // big text generated using http://patorjk.com/software/taag } /** * Instantiates adapters following configuration in cricket.json * * @param config Configuration object loaded from cricket.json * @throws Exception */ private synchronized void loadAdapters(Configuration config) throws Exception { setHttpHandlerLoaded(false); setInboundAdaptersLoaded(false); getLogger().print("LOADING SERVICE PROPERTIES FOR " + config.getService()); getLogger().print("\tUUID=" + getUuid().toString()); getLogger().print("\tenv name=" + getName()); //setHost(config.getHost()); setHost(config.getProperty("host", "0.0.0.0")); getLogger().print("\thost=" + getHost()); try { //setPort(Integer.parseInt(config.getPort())); setPort(Integer.parseInt(config.getProperty("port", "8080"))); } catch (Exception e) { e.printStackTrace(); } getLogger().print("\tport=" + getPort()); setSecurityFilter(config.getProperty("filter")); getLogger().print("\tfilter=" + getSecurityFilter().getClass().getName()); setCorsHeaders(config.getProperty("cors")); getLogger().print("\tCORS=" + getCorsHeaders()); getLogger().print("\tExtended properties: " + getProperties().toString()); getLogger().print("LOADING ADAPTERS"); String adapterName = null; AdapterConfiguration ac = null; try { HashMap<String, AdapterConfiguration> adcm = config.getAdapters(); for (Map.Entry<String, AdapterConfiguration> adapterEntry : adcm.entrySet()) { adapterName = adapterEntry.getKey(); ac = adapterEntry.getValue(); getLogger().print("ADAPTER: " + adapterName); try { Class c = Class.forName(ac.getClassFullName()); adaptersMap.put(adapterName, c.newInstance()); if (adaptersMap.get(adapterName) instanceof org.cricketmsf.in.http.HttpAdapter) { setHttpHandlerLoaded(true); } else if (adaptersMap.get(adapterName) instanceof org.cricketmsf.in.InboundAdapter) { setInboundAdaptersLoaded(true); } if (adaptersMap.get(adapterName) instanceof org.cricketmsf.out.DispatcherIface) { setEventDispatcher(adaptersMap.get(adapterName)); } // loading properties java.lang.reflect.Method loadPropsMethod = c.getMethod("loadProperties", HashMap.class, String.class); loadPropsMethod.invoke(adaptersMap.get(adapterName), ac.getProperties(), adapterName); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException ex) { adaptersMap.put(adapterName, null); getLogger().print("ERROR: " + adapterName + " configuration: " + ex.getClass().getSimpleName()); } } } catch (Exception e) { LOGGER.log(Level.SEVERE, "Adapters initialization error. Configuration for: {0}", adapterName); throw new Exception(e); } getLogger().print("END LOADING ADAPTERS"); getLogger().print(""); } private void setEventDispatcher(Object adapter){ eventDispatcher = (EventDispatcherAdapter)adapter; } private void setSecurityFilter(String filterName) { try { Class c = Class.forName(filterName); securityFilter = (Filter) c.newInstance(); } catch (ClassCastException | ClassNotFoundException | InstantiationException | IllegalAccessException e) { e.printStackTrace(); securityFilter = new SecurityFilter(); } } public Filter getSecurityFilter() { return securityFilter; } /** * @return the host */ public String getHost() { return host; } /** * @param host the host to set */ public void setHost(String host) { this.host = host; } /** * @return the port */ public int getPort() { return port; } /** * @param port the port to set */ public void setPort(int port) { this.port = port; } /** * @return the httpd */ private Httpd getHttpd() { return httpd; } /** * @param httpd the httpd to set */ private void setHttpd(Httpd httpd) { this.httpd = httpd; } /** * @return the httpHandlerLoaded */ private boolean isHttpHandlerLoaded() { return httpHandlerLoaded; } /** * @param httpHandlerLoaded the httpHandlerLoaded to set */ private void setHttpHandlerLoaded(boolean httpHandlerLoaded) { this.httpHandlerLoaded = httpHandlerLoaded; } /** * This method will be invoked when Kernel is executed without --run option */ public void runOnce() { getEventHooks(); getAdapters(); setKeystores(); printHeader(Kernel.getInstance().configSet.getKernelVersion()); } private void setKeystores() { String keystore; String keystorePass; String truststore; String truststorePass; keystore = (String) getProperties().getOrDefault("keystore", ""); keystorePass = (String) getProperties().get("keystore-password"); truststore = (String) getProperties().getOrDefault("keystore", ""); truststorePass = (String) getProperties().get("keystore-password"); if (!keystore.isEmpty() && !keystorePass.isEmpty()) { System.setProperty("javax.net.ssl.keyStore", keystore); System.setProperty("javax.net.ssl.keyStorePassword", keystorePass); } if (!truststore.isEmpty() && !truststorePass.isEmpty()) { System.setProperty("javax.net.ssl.trustStore", truststore); System.setProperty("javax.net.ssl.trustStorePassword", truststorePass); } } /** * Starts the service instance * * @throws InterruptedException */ public void start() throws InterruptedException { getAdapters(); getEventHooks(); setKeystores(); if (isHttpHandlerLoaded() || isInboundAdaptersLoaded()) { Runtime.getRuntime().addShutdownHook( new Thread() { public void run() { try { shutdown(); Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } }); getLogger().print("Running initialization tasks"); runInitTasks(); getLogger().print("Starting listeners ..."); // run listeners for inbound adapters runListeners(); getLogger().print("Starting http listener ..."); setHttpd(new Httpd(this)); getHttpd().run(); long startedIn = System.currentTimeMillis() - startedAt; printHeader(Kernel.getInstance().configSet.getKernelVersion()); if (liftMode) { getLogger().print("# Service: " + getClass().getName()); } else { getLogger().print("# Service: " + getId()); } getLogger().print("# UUID: " + getUuid()); getLogger().print("# NAME: " + getName()); getLogger().print("#"); if (getHttpd().isSsl()) { getLogger().print("# HTTPS listening on port " + getPort()); } else { getLogger().print("# HTTP listening on port " + getPort()); } getLogger().print("#"); getLogger().print("# Started in " + startedIn + "ms. Press Ctrl-C to stop"); getLogger().print(""); runFinalTasks(); Thread.currentThread().setPriority(Thread.MAX_PRIORITY); started = true; } else { getLogger().print("Couldn't find any http request hook method. Exiting ..."); System.exit(MIN_PRIORITY); } } /** * Could be overriden in a service implementation to run required code at * the service start. As the last step of the service starting procedure * before HTTP service. */ protected void runInitTasks() { setInitialized(true); } /** * Could be overriden in a service implementation to run required code at * the service start. As the last step of the service starting procedure * after HTTP service. */ protected void runFinalTasks() { } protected void runListeners() { for (Map.Entry<String, Object> adapterEntry : getAdaptersMap().entrySet()) { if (adapterEntry.getValue() instanceof org.cricketmsf.in.InboundAdapter) { if (!(adapterEntry.getValue() instanceof org.cricketmsf.in.http.HttpAdapter)) { (new Thread((InboundAdapter) adapterEntry.getValue())).start(); getLogger().print(adapterEntry.getKey() + " (" + adapterEntry.getValue().getClass().getSimpleName() + ")"); } } } } public void shutdown() { getLogger().print("Shutting down ..."); for (Map.Entry<String, Object> adapterEntry : getAdaptersMap().entrySet()) { if (adapterEntry.getValue() instanceof org.cricketmsf.in.InboundAdapter) { ((InboundAdapter) adapterEntry.getValue()).destroy(); } else if (adapterEntry.getValue() instanceof org.cricketmsf.out.OutboundAdapter) { ((OutboundAdapter) adapterEntry.getValue()).destroy(); } } try { getHttpd().stop(); } catch (NullPointerException e) { } System.out.println("Kernel stopped\r\n"); } /** * @return the configSet */ public ConfigSet getConfigSet() { return configSet; } /** * @param configSet the configSet to set */ public void setConfigSet(ConfigSet configSet) { this.configSet = configSet; } /** * Return service instance unique identifier * * @return the uuid */ public UUID getUuid() { return uuid; } /** * @param uuid the uuid to set */ public void setUuid(UUID uuid) { this.uuid = uuid; } /** * @return the id */ public String getId() { return id; } /** * @param id the id to set */ private void setId(String id) { this.id = id; } /** * @return the corsHeaders */ public ArrayList getCorsHeaders() { return corsHeaders; } /** * @param corsHeaders the corsHeaders to set */ public void setCorsHeaders(String corsHeaders) { this.corsHeaders = new ArrayList<>(); if (corsHeaders != null) { String[] headers = corsHeaders.split("\\|"); for (String header : headers) { try { this.corsHeaders.add( new HttpHeader( header.substring(0, header.indexOf(":")).trim(), header.substring(header.indexOf(":") + 1).trim() ) ); } catch (Exception e) { e.printStackTrace(); } } } } /** * @return the properties */ public HashMap<String, Object> getProperties() { return properties; } /** * @param properties the properties to set */ public void setProperties(HashMap<String, Object> properties) { this.properties = properties; } /** * @return the inboundAdaptersLoaded */ public boolean isInboundAdaptersLoaded() { return inboundAdaptersLoaded; } /** * @param inboundAdaptersLoaded the inboundAdaptersLoaded to set */ public void setInboundAdaptersLoaded(boolean inboundAdaptersLoaded) { this.inboundAdaptersLoaded = inboundAdaptersLoaded; } /** * @return the name */ public String getName() { return name; } /** * @param variableName system environment variable name which holds the name * of this service */ public void setName(String variableName) { String tmp = null; try { tmp = System.getenv(variableName); } catch (Exception e) { } this.name = tmp != null ? tmp : ""+getProperties().getOrDefault("servicename",""); if(this.name.isEmpty()){ this.name= "CricketService"; } } /** * @return the logger */ public static LoggerAdapterIface getLogger() { return logger; } /** * Returns map of the current service properties along with list of statuses * reported by all registered (running) adapters * * @return status map */ public Map reportStatus() { HashMap status = new HashMap(); status.put("name", getName()); status.put("id", getId()); status.put("uuid", getUuid().toString()); status.put("class", getClass().getName()); status.put("totalMemory", Runtime.getRuntime().totalMemory()); status.put("maxMemory", Runtime.getRuntime().maxMemory()); status.put("freeMemory", Runtime.getRuntime().freeMemory()); status.put("threads", Thread.activeCount()); ArrayList adapters = new ArrayList(); adaptersMap.keySet().forEach(key -> { try { adapters.add( ((Adapter) adaptersMap.get(key)).getStatus(key)); } catch (Exception e) { getInstance().dispatchEvent(Event.logFine(this, key + " adapter is not registered")); } }); status.put("adapters", adapters); return status; } /** * Returns status map formated as JSON * * @return JSON representation of the statuses map */ public String printStatus() { HashMap args = new HashMap(); args.put(JsonWriter.PRETTY_PRINT, true); args.put(JsonWriter.DATE_FORMAT, "dd/MMM/yyyy:kk:mm:ss Z"); args.put(JsonWriter.TYPE, false); return JsonWriter.objectToJson(reportStatus(), args); } /** * @return the initialized */ public boolean isInitialized() { return initialized; } /** * @param initialized the initialized to set */ public void setInitialized(boolean initialized) { this.initialized = initialized; } }
//jDownloader - Downloadmanager //Copyright (C) 2009 JD-Team support@jdownloader.org // //This program is free software: you can redistribute it and/or modify //it under the terms of the GNU General Public License as published by //the Free Software Foundation, either version 3 of the License, or //(at your option) any later version. // //This program is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. // //You should have received a copy of the GNU General Public License //along with this program. If not, see <http://www.gnu.org/licenses/>. package jd.plugins.decrypter; import java.io.File; import java.util.ArrayList; import jd.PluginWrapper; import jd.controlling.ProgressController; import jd.http.Browser; import jd.parser.Regex; import jd.plugins.CryptedLink; import jd.plugins.DecrypterException; import jd.plugins.DecrypterPlugin; import jd.plugins.DownloadLink; import jd.plugins.FilePackage; import jd.plugins.PluginForDecrypt; import jd.plugins.components.PluginJSonUtils; import org.jdownloader.captcha.v2.challenge.recaptcha.v1.Recaptcha; @DecrypterPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "extreme-protect.net" }, urls = { "http://(?:www\\.)?extreme\\-protect\\.net/([a-z0-9\\-_]+)" }) public class ExtremeProtectNet extends PluginForDecrypt { public ExtremeProtectNet(PluginWrapper wrapper) { super(wrapper); } private static final String RECAPTCHATEXT = "api\\.recaptcha\\.net"; private static final String RECAPTCHATEXT2 = "google\\.com/recaptcha/api/challenge"; public ArrayList<DownloadLink> decryptIt(CryptedLink param, ProgressController progress) throws Exception { ArrayList<DownloadLink> decryptedLinks = new ArrayList<DownloadLink>(); String parameter = param.toString(); String fpName = null; String[] links = null; { // this bypasses captcha etc. problem is title isn't shown... br.postPage("http://extreme-protect.net/api.php", "id=" + new Regex(parameter, this.getSupportedLinks()).getMatch(0)); fpName = PluginJSonUtils.getJsonValue(br, "titre"); String lnks = PluginJSonUtils.getJsonArray(br.toString(), "liens"); if (lnks != null) { links = new Regex(lnks, "http[^\"]+").getColumn(-1); if (links != null) { for (String dl : links) { decryptedLinks.add(createDownloadlink(dl)); } } } } if (inValidate(fpName)) { br = new Browser(); br.setFollowRedirects(true); try { br.setAllowedResponseCodes(new int[] { 500 }); } catch (final Throwable e) { // logger.info("Link can only be decrypted in JDownloader 2: " + parameter); // return decryptedLinks; } br.getPage(parameter); if (inValidate(fpName)) { fpName = br.getRegex("<title>([^<>\"]*?)</title>").getMatch(0); } if (decryptedLinks.isEmpty()) { // fail over if (br.getHttpConnection().getResponseCode() == 403 || !br.containsHTML("class=\"contenu_liens\"")) { logger.info("Link offline: " + parameter); final DownloadLink offline = createDownloadlink("directhttp://" + parameter); offline.setAvailable(false); offline.setProperty("offline", true); decryptedLinks.add(offline); return decryptedLinks; } if (br.containsHTML(RECAPTCHATEXT) || br.containsHTML(RECAPTCHATEXT2)) { boolean failed = true; for (int i = 0; i <= 5; i++) { final Recaptcha rc = new Recaptcha(br, this); rc.parse(); rc.load(); File cf = rc.downloadCaptcha(getLocalCaptchaFile()); final String c = getCaptchaCode("recaptcha", cf, param); br.postPage(br.getURL(), "recaptcha_challenge_field=" + rc.getChallenge() + "&recaptcha_response_field=" + c + "&submit_captcha=VALIDER"); if (br.containsHTML(RECAPTCHATEXT) || br.containsHTML(RECAPTCHATEXT2)) { br.getPage(parameter); continue; } failed = false; break; } if (failed) { throw new DecrypterException(DecrypterException.CAPTCHA); } } else { final String pass = generatePass(); br.getHeaders().put("X-Requested-With", "XMLHttpRequest"); br.getHeaders().put("Accept", "application/json, text/javascript, */*; q=0.01"); br.getHeaders().put("Cache-Control", null); br.postPage("/requis/captcha_formulaire.php", "action=qaptcha&qaptcha_key=" + pass); br.getHeaders().put("Accept", "text/html, application/xhtml+xml, */*"); br.getHeaders().put("X-Requested-With", null); br.postPage(parameter, pass + "=&submit_captcha=VALIDER"); } links = br.getRegex("class=\"lien\" ><a target=\"_blank\" href=\"(http[^<>\"]*?)\"").getColumn(0); if (links == null || links.length == 0) { logger.warning("Decrypter broken for link: " + parameter); return null; } for (String dl : links) { decryptedLinks.add(createDownloadlink(dl)); } if (inValidate(fpName)) { fpName = br.getRegex("<title>([^<>\"]*?)</title>").getMatch(0); } } } if (fpName != null) { FilePackage fp = FilePackage.getInstance(); fp.setName(fpName.trim()); fp.addLinks(decryptedLinks); } return decryptedLinks; } private String generatePass() { int nb = 32; final String chars = "azertyupqsdfghjkmwxcvbn23456789AZERTYUPQSDFGHJKMWXCVBN_-#@"; String pass = ""; for (int i = 0; i < nb; i++) { long wpos = Math.round(Math.random() * (chars.length() - 1)); int lool = (int) wpos; pass += chars.substring(lool, lool + 1); } return pass; } /** * Validates string to series of conditions, null, whitespace, or "". This saves effort factor within if/for/while statements * * @param s * Imported String to match against. * @return <b>true</b> on valid rule match. <b>false</b> on invalid rule match. * @author raztoki * */ private boolean inValidate(final String s) { if (s == null || s != null && (s.matches("[\r\n\t ]+") || s.equals(""))) { return true; } else { return false; } } /* NO OVERRIDE!! */ public boolean hasCaptcha(CryptedLink link, jd.plugins.Account acc) { return true; } }
package com.sheygam.loginarchitectureexample.business.addContact; import com.sheygam.loginarchitectureexample.data.dao.Contact; import com.sheygam.loginarchitectureexample.data.repositories.addContact.prefstore.IAddContactStoreRepository; import com.sheygam.loginarchitectureexample.data.repositories.addContact.web.IAddContactWebRepository; import io.reactivex.Completable; /** * Created by Kate on 17.02.2018. */ public class AddContactInteractor implements IAddContactInteractor { private IAddContactWebRepository iAddContactWebRepository; private IAddContactStoreRepository iAddContactStoreRepository; public AddContactInteractor(IAddContactWebRepository iAddContactWebRepository, IAddContactStoreRepository iAddContactStoreRepository) { this.iAddContactWebRepository = iAddContactWebRepository; this.iAddContactStoreRepository = iAddContactStoreRepository; } private String getFromRep() { return iAddContactStoreRepository.getAuthToken(); } @Override public Completable saveContact(Contact contact) { return iAddContactWebRepository.saveContact(getFromRep(), contact) .toCompletable(); } }
/* * Copyright 2015 The RPC Project * * The RPC Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.flood.rpc.network; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ReplayingDecoder; import java.util.List; public class MessageDecoder extends ReplayingDecoder<MessageDecoder.State> { public MessageDecoder() { checkpoint(State.READ_INIT); } private NetPackage message; private int headSize; public static final int HEADER_LENGTH = 4; enum State { READ_INIT, READ_HEAD, READ_BODY, READ_SUCCESS, BAD_MESSAGE, UPGRADED, NEED_DATA } @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { switch (state()) { case READ_INIT: if (readInit(in)) { checkpoint(State.READ_HEAD); } else { return; } case READ_HEAD: State nextState = readHeader(in); checkpoint(nextState); case READ_BODY: nextState = readBody(in); checkpoint(nextState); case READ_SUCCESS: out.add(message); checkpoint(State.READ_INIT); break; case BAD_MESSAGE: break; case NEED_DATA: nextState = readHeader(in); checkpoint(nextState); break; } } private boolean readInit(ByteBuf buffer) { if (buffer.readableBytes() >= HEADER_LENGTH) { return true; } return false; } private State readHeader(ByteBuf buffer) { headSize = 0; headSize = buffer.readInt(); return State.READ_BODY; } private State readBody(ByteBuf buffer) { if (buffer.readableBytes() < headSize) { return State.NEED_DATA; } message = NetPackage.create(headSize, buffer); return State.READ_SUCCESS; } }
package com.github.ofofs.jca.annotation; import com.github.ofofs.jca.constants.CoreConstants; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 限制一定时间内方法的调用次数。 * * @author kangyonggan * @since 6/27/18 */ @Retention(RetentionPolicy.SOURCE) @Target(ElementType.METHOD) public @interface Count { /** * 方法的键 * * @return 返回方法的键 */ String value() default CoreConstants.EMPTY; /** * 方法的键(和value二者至少提供一个,如果都提供,value更优先) * * @return 返回键对应的方法名称 */ String key() default CoreConstants.EMPTY; /** * 持续时间,单位毫秒 * * @return 返回持续时间 */ long during(); /** * 方法在持续时间内人最大调用次数 * * @return 返回最大调用次数 */ int count(); /** * 在持续时间内超过最大调用次数后调用此方法 * * @return 返回方法名称 */ String violate(); }
package com.pabi.miwokmediaplayer; /** * Created by Admin on 7/7/2017. */ public class Songs { private String mSongName; private int mAudioResourceId; private int mImageResourceId = NO_IMAGE_PROVIDED; private static final int NO_IMAGE_PROVIDED = -1; public Songs(String songName, int audioResourceId){ mSongName = songName; mAudioResourceId = audioResourceId; } public Songs(String songName, int imageResourceId, int audioResourceId){ mSongName =songName; mAudioResourceId = audioResourceId; mImageResourceId = imageResourceId; } public String getSongName() { return mSongName; } public int getImageResourceId() { return mImageResourceId; } public boolean hasImage() { return mImageResourceId != NO_IMAGE_PROVIDED; } public int getAudioResourceId() { return mAudioResourceId; } }
package com.tridevmc.movingworld.common.chunk.mobilechunk; import com.google.common.collect.Maps; import com.tridevmc.movingworld.client.render.MobileChunkRenderer; import com.tridevmc.movingworld.common.entity.EntityMovingWorld; import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.fml.LogicalSide; import java.util.ArrayList; import java.util.List; import java.util.Map; @OnlyIn(Dist.CLIENT) public class MobileChunkClient extends MobileChunk { public Map<BlockPos, TileEntity> fastTESRS = Maps.newHashMap(); public Map<BlockPos, TileEntity> normalTESRS = Maps.newHashMap(); private MobileChunkRenderer renderer; public MobileChunkClient(World world, EntityMovingWorld movingWorld) { super(world, movingWorld); this.renderer = new MobileChunkRenderer(this); } public MobileChunkRenderer getRenderer() { return this.renderer; } @Override public void onChunkUnload() { List<TileEntity> iterator = new ArrayList<>(this.chunkTileEntityMap.values()); for (TileEntity te : iterator) { this.removeChunkBlockTileEntity(te.getPos()); } super.onChunkUnload(); this.renderer.markRemoved(); } @Override public void setChunkModified() { super.setChunkModified(); this.renderer.markDirty(); } @Override public void setTileEntity(BlockPos pos, TileEntity tileentity) { super.setTileEntity(pos, tileentity); if (tileentity == null) { // Removed a tile, remove it from the render lists as well. this.fastTESRS.remove(pos); this.normalTESRS.remove(pos); } else { // Add a tesr, after confirming it has one, and that it's fast. if (TileEntityRendererDispatcher.instance.getRenderer(tileentity) != null) { if (tileentity.hasFastRenderer()) { this.fastTESRS.put(pos, tileentity); } else { this.normalTESRS.put(pos, tileentity); } } } } @Override public LogicalSide side() { return LogicalSide.CLIENT; } }
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.Writer; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import javax.swing.JTextArea; import gov.nih.mipav.model.algorithms.AlgorithmBase; import gov.nih.mipav.model.file.FileBase; import gov.nih.mipav.model.file.FileDicom; import gov.nih.mipav.model.file.FileIO; import gov.nih.mipav.model.file.FileInfoBase.Unit; import gov.nih.mipav.model.file.FileInfoDicom; import gov.nih.mipav.model.file.FileInfoImageXML; import gov.nih.mipav.model.file.FileInfoPARREC; import gov.nih.mipav.model.file.FilePARREC; import gov.nih.mipav.model.file.FileUtility; import gov.nih.mipav.model.file.FileWriteOptions; import gov.nih.mipav.model.structures.ModelImage; import gov.nih.mipav.model.structures.ModelStorageBase; import gov.nih.mipav.model.structures.TransMatrix; import gov.nih.mipav.view.Preferences; import gov.nih.mipav.view.ViewImageFileFilter; /** * This is the algorithm for the DTI Create List File Plug-In * @author Nish Pandya * * * References: This algorithm was developed in concert with Lin-Ching Chang D.Sc., Carlo Pierpaoli MD Ph.D., and Lindsay Walker MS of * the NIH/NICHD/LIMB/STBB group : * * Section on Tissue Biophysics and Biomimetics (STBB) * Laboratory of Integrative and Medical Biophysics (LIMB) * National Institute of Child Health & Humann Development * National Institutes of Health * * This opening acknowledgment section must be included in all copies and modifications of this code. * * A good reference on the B-matrix is: * Analytical Expressions for the b Matrix in NMR Diffusion Imaging and Spectroscopy by James Mattiello, * Peter J. Basser, and Denis LeBihan, Journal of Magnetic Resonance Series A, 108, 1994, pp. 131-141. * */ public class PlugInAlgorithmDTICreateListFile extends AlgorithmBase { /** This is the dir name of the study.* */ private String studyName; /** This is the full path of the study.* */ private String studyPath; /** par rec file name **/ private String prFileName; /** par rec file dir **/ private String prFileDir; /** This is the full path to the gradient file.* */ private String gradientFilePath; /** This is the full path to the b matrix file.* */ private String bmtxtFilePath; /** boolean if dataset is interelaved **/ private boolean isInterleaved; /** TextArea of main dialogfor text output.* */ private JTextArea outputTextArea; /** This is an ordered map of series number and seriesFileInfoTreeSet.* */ private TreeMap<Integer,TreeSet<String[]>> seriesFileInfoTreeMap; /** This is an ordered list of files per series number.* */ private TreeSet<String[]> seriesFileInfoTreeSet; /** boolean indicating if we are dealing with dicom or par/rec **/ private boolean isDICOM; /** List file name **/ private String listFileName; /** B Matrix file name **/ private String bmatrixFileName; /** Path File name **/ private String pathFileName; /** flag indicating if method was successful.* */ private boolean success = true; /** total image slices.* */ private int totalImageSlices = 0; /** total num of volumes in study.* */ private int totalNumVolumes = 0; /** boolean telling if dataset is eDTI.* */ private boolean isEDTI = false; /** boolean telling if datset is GE.* */ private boolean isGE = false; /** boolean telling if datset is SIEMENS.* */ private boolean isSiemens = false; /** first fileinfo dicom...used for list file info.* */ private FileInfoDicom firstFileInfoDicom; /** int telling software version if datset is GE.* */ private int geSoftwareVersion = -1; /** This is the image filter needed to select the correct dicom images.* */ private ViewImageFileFilter imageFilter; /** Array that holds the dicom tag info* */ private String[] dicomInfo; /** boolean if proc dir was created.* */ private boolean isProcDirCreated = false; /** this is the number of image slices per volume.* */ private int numSlicesPerVolume; /** this is the number of gradient quantities that is obtained by reading first line of gradient file.* */ private int nim; /** this is the gradient matrix that is populated when reading the gradient file.* */ private float[][] direction; /** this is an array of b-values that for each volume.* */ private ArrayList<Float> bValuesArrayList = new ArrayList<Float>(); /** FileParRec handle **/ private FilePARREC fileParRec; /** ModelImage of 4D par/rec dataset **/ private ModelImage image4D; /** x dim **/ private String originalColumnsString; /** y dim **/ private String originalRowsString; /** z dim **/ private String numSlicesString; /** t dim **/ private String nimString; /** phase encoding...hard coded to vertical **/ private String phaseEncodingString = "vertical"; /** horizontal FOV **/ private String horizontalFOVString; /** vertical FOV **/ private String verticalFOVString; /** slice gap String **/ private String sliceGapString; /** sliec thickness **/ private String sliceThicknessString; /** image orientation **/ private String imageOrientationString; /** vol parameters **/ private HashMap<String,String> volParameters; /**Philips puts in one volume as the average of all the DWIs. This volume will have a non-zero B value and 0 in the gradients Once we find this volume, exclude it.... this int represents which volume index to exclude**/ private int avgVolIndex = -1; /** boolean identifying if par/rec datset is older than version 4.1 **/ private boolean isOldVersion = false; /** arraylist of gradients for version 4 of Par/Rec **/ private ArrayList<String[]> oldVersionGradientsAL; /** this counter is used for version 4 of Par/Rec...nim is calculated from gradient file **/ private int nimCounter = 0; /** path for imageSlicesDir **/ private String imageSlicesDirPath; /** relative path for slices dir for outputting to path file **/ private String relativeImageSlicesDirPath; /** raw image format...hardcoded to float since we will be outputting par/rec slices in float format **/ private String rawImageFormatString = "float"; /** arraylist of unsorted path strings to image slices **/ private ArrayList<String> unsortedPathsArrayList = new ArrayList<String>(); /** xDIm of 4d image **/ private int xDim; /** yDim of 4d image **/ private int yDim; /** zDim of 4d image **/ private int zDim; /** tDim of 4d image **/ private int tDim; /** file info Par/Rec **/ private FileInfoPARREC fileInfoPR; /** * constructor for dicom * * @param studyPath * @param studyName * @param gradientFilePath * @param bmtxtFilePath * @param outputTextArea */ public PlugInAlgorithmDTICreateListFile(String studyPath, String studyName, String gradientFilePath, String bmtxtFilePath, JTextArea outputTextArea, boolean isInterleaved) { this.studyPath = studyPath; this.studyName = studyName; this.gradientFilePath = gradientFilePath; this.bmtxtFilePath = bmtxtFilePath; this.outputTextArea = outputTextArea; this.isInterleaved = isInterleaved; this.listFileName = studyName + ".list"; this.bmatrixFileName = studyName + ".BMTXT"; this.pathFileName = studyName + ".path"; seriesFileInfoTreeMap = new TreeMap<Integer,TreeSet<String[]>>(); isDICOM = true; } /** constructor for par/rec * */ public PlugInAlgorithmDTICreateListFile(String fileName, String fileDir, String gradientFilePath, String bmtxtFilePath, JTextArea outputTextArea) { this.prFileName = fileName; this.studyName = fileName.substring(0, fileName.indexOf(".")); this.prFileDir = fileDir; this.gradientFilePath = gradientFilePath; this.bmtxtFilePath = bmtxtFilePath; this.listFileName = studyName + ".list"; this.bmatrixFileName = studyName + ".BMTXT"; this.pathFileName = studyName + ".path"; this.outputTextArea = outputTextArea; isDICOM = false; } /** * run algorithm */ public void runAlgorithm() { if(isDICOM) { runAlgorithmDICOM(); }else { runAlgorithmPARREC(); } } /** * run algorithm for dicom * */ public void runAlgorithmDICOM() { long begTime = System.currentTimeMillis(); Preferences.debug("** Beginning Algorithm v2.3\n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("** Beginning Algorithm v2.3\n"); } System.out.println("** Beginning Algorithm v2.3\n"); //remove last slash from study path if it has it if(String.valueOf(studyPath.charAt(studyPath.length() - 1)).equals(File.separator)) { studyPath = studyPath.substring(0,studyPath.length() - 1); } Preferences.debug("* The study path is " + studyPath + " \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("* The study path is " + studyPath + " \n"); } System.out.println("* The study path is " + studyPath + " \n"); if(isInterleaved) { Preferences.debug("* Interleaved dataset \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("* Interleaved dataset \n"); } System.out.println("* Interleaved dataset \n"); } if(isInterleaved && bmtxtFilePath.equals("")) { //this means that no b-matrix file was provided along with this interleaved dataset Preferences.debug("* For interleaved datasets, b-matrix file is required \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("* For interleaved datasets, b-matrix file is required \n"); } System.out.println("* For interleaved datasets, b-matrix file is required \n"); finalize(); setCompleted(true); return; } // first create a File object based upon the study path File studyPathRoot = new File(studyPath); // parse the directory Preferences.debug("* Parsing", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("* Parsing"); } System.out.print("* Parsing"); try { success = parse(studyPathRoot); } catch (OutOfMemoryError e) { if (outputTextArea != null) { outputTextArea.append("! ERROR: out of memory....exiting algorithm \n"); } System.out.println("! ERROR: " + e.getCause().toString() + "\n"); System.out.println("! ERROR: out of memory....exiting algorithm \n"); finalize(); setCompleted(true); return; } catch (IOException e) { if (outputTextArea != null) { outputTextArea.append("! ERROR: IOException....exiting algorithm \n"); } System.out.println("! ERROR: " + e.toString() + "\n"); System.out.println("! ERROR: IOException....exiting algorithm \n"); finalize(); setCompleted(true); return; } if (success == false) { finalize(); setCompleted(true); return; } System.gc(); Preferences.debug("\n* Number of image slices in study dir is " + totalImageSlices + " \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("\n* Number of image slices in study dir is " + totalImageSlices + " \n"); } System.out.println("\n\n* Number of image slices in study dir is " + totalImageSlices + " \n"); if (totalImageSlices == 0) { finalize(); setCompleted(true); return; } // set initial info success = setInitialInfo(); if (success == false) { finalize(); setCompleted(true); return; } // create proc dir Preferences.debug("* Creating proc dir \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("* Creating proc dir \n"); } System.out.println("* Creating proc dir \n"); success = createProcDirDICOM(); if (success == false) { finalize(); setCompleted(true); return; } // create path file Preferences.debug("* Creating path file \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("* Creating path file \n"); } System.out.println("* Creating path file \n"); if(isInterleaved) { success = createPathFileForInterleavedDICOM(); }else { success = createPathFileDICOM(); } if (success == false) { finalize(); setCompleted(true); return; } // create list file Preferences.debug("* Creating list file \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("* Creating list file \n"); } System.out.println("* Creating list file \n"); success = createListFileDICOM(); if (success == false) { finalize(); setCompleted(true); return; } if (!gradientFilePath.equals("")) { // this means user provided gradient file...so... // read gradient file Preferences.debug("* Reading gradient file \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("* Reading gradient file \n"); } System.out.println("* Reading gradient file \n"); success = readGradientFileDICOM(); if (success == false) { finalize(); setCompleted(true); return; } // obtain b-values Preferences.debug("* Obtaining b-values \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("* Obtaining b-values \n"); } System.out.println("* Obtaining b-values \n"); success = obtainBValuesDICOM(); if (success == false) { finalize(); setCompleted(true); return; } // create b matrix file Preferences.debug("* Creating b-matrix file \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("* Creating b-matrix file \n"); } System.out.println("\n* Creating b-matrix file \n"); success = createBMatrixFileDICOM(); if (success == false) { finalize(); setCompleted(true); return; } } else { // this means that the bmtxt file was provided instead...so... // copy and rename b-matrix file Preferences.debug("* b-matrix file provided \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("* b-matrix file provided \n"); } System.out.println("* b-matrix file provided \n"); success = copyBMatrixFile(); if (success == false) { finalize(); setCompleted(true); return; } } Preferences.debug("** Ending Algorithm \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("** Ending Algorithm \n"); } System.out.println("** Ending Algorithm \n"); finalize(); long endTime = System.currentTimeMillis(); long diffTime = endTime - begTime; float seconds = ((float) diffTime) / 1000; Preferences.debug("** Algorithm took " + seconds + " seconds \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("** Algorithm took " + seconds + " seconds \n"); } System.out.println("** Algorithm took " + seconds + " seconds \n"); setCompleted(true); } /** * run algorithm for par/rec * */ public void runAlgorithmPARREC() { long begTime = System.currentTimeMillis(); Preferences.debug("** Beginning Algorithm v1.0\n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("** Beginning Algorithm v1.0\n"); } fileParRec = new FilePARREC(prFileName, prFileDir + File.separator); //read in 4d par/rec data try { image4D = fileParRec.readImage(false); }catch (Exception e) { e.printStackTrace(); finalize(); setCompleted(true); return; } //create proc dir Preferences.debug("* Creating proc dir and imageSlices dir \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("* Creating proc dir and imageSlices dir \n"); } success = createProcDirAndImageSlicesDirParRec(); if (success == false) { finalize(); setCompleted(true); return; } isProcDirCreated = true; //obtain list file data success = obtainListFileDataParRec(); if (success == false) { finalize(); setCompleted(true); return; } // create list file Preferences.debug("* Creating list file \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("* Creating list file \n"); } success = createListFileParRec(); if (success == false) { finalize(); setCompleted(true); return; } //create b matrix file Preferences.debug("* Creating b-matrix file \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("* Creating b-matrix file \n"); } success = createBMatrixFileParRec(); if (success == false) { finalize(); setCompleted(true); return; } //write out image slices Preferences.debug("* Writing out image slices", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("* Writing out image slices"); } success = writeImageSlicesParRec(); if (success == false) { finalize(); setCompleted(true); return; } //create path file Preferences.debug("\n* Creating path file \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("\n* Creating path file \n"); } success = createPathFileParRec(); if (success == false) { finalize(); setCompleted(true); return; } //ending algorithm Preferences.debug("** Ending Algorithm \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("** Ending Algorithm \n"); } finalize(); long endTime = System.currentTimeMillis(); long diffTime = endTime - begTime; float seconds = ((float) diffTime) / 1000; Preferences.debug("** Algorithm took " + seconds + " seconds \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("** Algorithm took " + seconds + " seconds \n"); } image4D.disposeLocal(); image4D = null; setCompleted(true); } //--------methods for dicom --------------------------------------------------------------------------------------- /** * this method sets initial info about the study. * * @return boolean success */ public boolean setInitialInfo() { // checking to see if it eDTI // first check private tag 0019,109C....if its not null, determine if it is eDTI from there // if it is null, check public tag 0008,103E and determine if it is eDTI from there String privateTag0019109C = null; String publicTag0008103E = null; try { if (firstFileInfoDicom.getTagTable().getValue("0019,109C") != null) { privateTag0019109C = (String) firstFileInfoDicom.getTagTable().getValue("0019,109C"); } if ((privateTag0019109C != null) && (privateTag0019109C.toLowerCase().indexOf("edti") != -1)) { isEDTI = true; Preferences.debug("* eDTI data set \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("* eDTI data set \n"); } System.out.println("* eDTI data set \n"); } else { Preferences.debug("* DTI data set \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("* DTI data set \n"); } System.out.println("* DTI data set \n"); } } catch (NullPointerException e) { publicTag0008103E = (String) firstFileInfoDicom.getTagTable().getValue("0008,103E"); if ((publicTag0008103E != null) && (publicTag0008103E.toLowerCase().indexOf("edti") != -1)) { isEDTI = true; Preferences.debug("* eDTI data set \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("* eDTI data set \n"); } System.out.println("* eDTI data set \n"); } else { Preferences.debug("* DTI data set \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("* DTI data set \n"); } System.out.println("* DTI data set \n"); } } // checking to see if it is GE or SIEMENS String manufacturer = ((String) firstFileInfoDicom.getTagTable().getValue("0008,0070")).trim(); if (manufacturer.toLowerCase().startsWith("ge")) { isGE = true; isSiemens = false; Preferences.debug("* Manufacturer : GE \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("* Manufacturer : GE \n"); } System.out.println("* Manufacturer : GE \n"); // getting software version for GE if regular DTI and not eDTI if (!isEDTI) { String softwareVersion = ((String) firstFileInfoDicom.getTagTable().getValue("0018,1020")).trim(); try { geSoftwareVersion = new Integer(softwareVersion).intValue(); Preferences.debug("* Software Version : " + geSoftwareVersion + " \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("* Software Version : " + geSoftwareVersion + " \n"); } System.out.println("* Software Version : " + geSoftwareVersion + " \n"); } catch (NumberFormatException e) { //software version might be in a format like "12, blah, kdfhasdukfblah"....extract the first number (12) StringBuffer versionSB = new StringBuffer(); for(int i=0;i<softwareVersion.length();i++) { char c = softwareVersion.charAt(i); if(Character.isDigit(c)) { versionSB.append(c); } else { break; } } if(versionSB.length() > 0) { geSoftwareVersion = new Integer(versionSB.toString().trim()).intValue(); Preferences.debug("* Software Version : " + geSoftwareVersion + " \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("* Software Version : " + geSoftwareVersion + " \n"); } System.out.println("* Software Version : " + geSoftwareVersion + " \n"); } else { Preferences.debug("! ERROR: Unable to determine software version for GE dataset....exiting algorithm \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("! ERROR: Unable to determine software version for GE dataset....exiting algorithm \n"); } System.out.println("! ERROR: Unable to determine software version for GE dataset....exiting algorithm \n"); return false; } } } } else { isSiemens = true; isGE = false; Preferences.debug("* Manufacturer : SIEMENS \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("* Manufacturer : SIEMENS \n"); } System.out.println("* Manufacturer : SIEMENS \n"); } return true; } /** * this method parses the study dir sort into lists using series number that is available in dicom tag. then based * on the filename, get vol number (for example mipav_dicom_dti_series11_volume10005.dcm), and sort within lists * using vol number and instance number that comes from dicom tag. * * @param file * * @return boolean success * * @throws IOException * @throws OutOfMemoryError */ public boolean parse(File file) throws IOException, OutOfMemoryError { imageFilter = new ViewImageFileFilter(new String[] { ".dcm", ".DCM", ".ima", ".IMA" }); File[] children = file.listFiles(); FileDicom imageFile = null; try { for (int i = 0; i < children.length; i++) { if (isThreadStopped()) { return false; } if (children[i].isDirectory()) { parse(children[i]); } else if (!children[i].isDirectory()) { try { if (imageFile == null) { imageFile = new FileDicom(children[i].getName(), children[i].getParent() + File.separatorChar); } else { imageFile.setFileName(children[i], firstFileInfoDicom); } if (imageFilter.accept(children[i])) { success = imageFile.readHeader(true); } else { imageFile.finalize(); imageFile = null; continue; } } catch (IOException error) { /*error.printStackTrace(); System.gc(); i--; continue;*/ error.printStackTrace(); throw error; } FileInfoDicom fileInfoDicom = (FileInfoDicom) imageFile.getFileInfo(); if (totalImageSlices == 0) { // we need the first file info dicom handle so we can use it for the list file firstFileInfoDicom = fileInfoDicom; } // get relevant info from fileinfodicom and place it in array that is then sorted by // instance number and vol in its appropriate series list dicomInfo = new String[8]; String instanceNo = ((String) fileInfoDicom.getTagTable().getValue("0020,0013")).trim(); if (instanceNo.trim().equals("")) { Preferences.debug("! ERROR: instance number dicom field is empty.....exiting algorithm \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("! ERROR: instance number dicom field is empty.....exiting algorithm \n"); } System.out.println("! ERROR: instance number dicom field is empty.....exiting algorithm \n"); return false; } TransMatrix matrix = null; float[] tPt = new float[3]; matrix = fileInfoDicom.getPatientOrientation(); if (matrix != null) { /* transform the x location, y location, and z location, found * from the Image Position tag, by the matrix. The tPt array now has the three numbers arranged * as if this image had been transformed. The third place in the array holds the number that * the axis is being sliced along. xlocation, ylocation, zlocation are from the DICOM tag * 0020,0032 patient location.....in other words tPt[2] is the slice location; */ matrix.transform(fileInfoDicom.xLocation, fileInfoDicom.yLocation, fileInfoDicom.zLocation, tPt); } else { Preferences.debug("! ERROR: unable to obtain image orientation matrix.....exiting algorithm \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("! ERROR: unable to obtain image orientation matrix.....exiting algorithm \n"); } System.out.println("! ERROR: unable to obtain image orientation matrix.....exiting algorithm \n"); return false; } String absPath = fileInfoDicom.getFileDirectory(); String fileName = fileInfoDicom.getFileName(); String publicTag00180024 = ((String) fileInfoDicom.getTagTable().getValue("0018,0024")); String privateTag00431039 = null; String privateTag001910B9 = null; try { if (fileInfoDicom.getTagTable().getValue("0043,1039") != null) { privateTag00431039 = (String) fileInfoDicom.getTagTable().getValue("0043,1039"); } } catch (NullPointerException e) { privateTag00431039 = null; } try { if (fileInfoDicom.getTagTable().getValue("0019,10B9") != null) { privateTag001910B9 = (String) fileInfoDicom.getTagTable().getValue("0019,10B9"); } } catch (NullPointerException e) { privateTag001910B9 = null; } String imageSlice = ((String) fileInfoDicom.getTagTable().getValue("0020,1041")).trim(); if(imageSlice.trim().equals("")) { Preferences.debug("! ERROR: image slice dicom field is empty.....exiting algorithm \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("! ERROR: image slice dicom field is empty.....exiting algorithm \n"); } return false; } dicomInfo[0] = instanceNo; dicomInfo[1] = String.valueOf(tPt[2]); dicomInfo[2] = absPath; dicomInfo[3] = fileName; dicomInfo[4] = publicTag00180024; dicomInfo[5] = privateTag00431039; dicomInfo[6] = privateTag001910B9; dicomInfo[7] = imageSlice; String seriesNumber_String = ((String) fileInfoDicom.getTagTable().getValue("0020,0011")).trim(); if ((seriesNumber_String == null) || seriesNumber_String.equals("")) { seriesNumber_String = "0"; } Integer seriesNumber = new Integer(seriesNumber_String); if(isInterleaved) { if (seriesFileInfoTreeMap.get(seriesNumber) == null) { seriesFileInfoTreeSet = new TreeSet<String[]>(new InstanceNumberVolComparator()); seriesFileInfoTreeSet.add(dicomInfo); seriesFileInfoTreeMap.put(seriesNumber, seriesFileInfoTreeSet); } else { seriesFileInfoTreeSet = (TreeSet<String[]>) seriesFileInfoTreeMap.get(seriesNumber); seriesFileInfoTreeSet.add(dicomInfo); seriesFileInfoTreeMap.put(seriesNumber, seriesFileInfoTreeSet); } } else { if (seriesFileInfoTreeMap.get(seriesNumber) == null) { seriesFileInfoTreeSet = new TreeSet<String[]>(new InstanceNumberComparator()); seriesFileInfoTreeSet.add(dicomInfo); seriesFileInfoTreeMap.put(seriesNumber, seriesFileInfoTreeSet); } else { seriesFileInfoTreeSet = (TreeSet<String[]>) seriesFileInfoTreeMap.get(seriesNumber); seriesFileInfoTreeSet.add(dicomInfo); seriesFileInfoTreeMap.put(seriesNumber, seriesFileInfoTreeSet); } } dicomInfo = null; fileInfoDicom = null; if ((totalImageSlices % 100) == 0) { Preferences.debug(".", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("."); } System.out.print("."); } if ((totalImageSlices % 500) == 0) { System.gc(); } totalImageSlices++; } } } finally { if(imageFile != null) { imageFile.finalize(); imageFile = null; } } return true; } /** * this method creates the proc dir in which the list file, path file, and b-matrix file go. * * @return boolean success */ public boolean createProcDirDICOM() { // create parallel proc dir to study path that will hold list file, path // file, and b matrix file File procDir = new File(studyPath + "_proc"); if (!procDir.isDirectory()) { boolean success = new File(studyPath + "_proc").mkdir(); if (!success) { Preferences.debug("! ERROR: Creation of proc directory failed....exiting algorithm \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("! ERROR: Creation of proc directory failed....exiting algorithm \n"); } System.out.println("! ERROR: Creation of proc directory failed....exiting algorithm \n"); return false; } } else { // we should delete all the files in the procDir if there are any File[] listFiles = procDir.listFiles(); if (listFiles.length > 0) { for (int i = 0; i < listFiles.length; i++) { String name = listFiles[i].getName(); if (name.equals(studyName + ".path") || name.equals(studyName + ".list") || name.equals(studyName + ".BMTXT")) { listFiles[i].delete(); } } } } Preferences.debug(" - proc dir created : " + studyPath + "_proc \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append(" - proc dir created : " + studyPath + "_proc \n"); } System.out.println(" - proc dir created : " + studyPath + "_proc \n"); isProcDirCreated = true; return true; } /** * This method creates the path file for interleaverd datasets * * @return boolean success */ public boolean createPathFileForInterleavedDICOM() { try { File pathFile = new File(studyPath + "_proc" + File.separator + studyName + ".path"); FileOutputStream outputStream = new FileOutputStream(pathFile); PrintStream printStream = new PrintStream(outputStream); Set<Integer> ketSet = seriesFileInfoTreeMap.keySet(); Iterator<Integer> iter = ketSet.iterator(); ArrayList<Integer> numSlicesCheckList = new ArrayList<Integer>(); while (iter.hasNext()) { TreeSet<String[]> seriesFITS = (TreeSet<String[]>) seriesFileInfoTreeMap.get(iter.next()); Iterator<String[]> iter2 = seriesFITS.iterator(); // lets get the first element and remember its imageSlice String imageSlice = ((String) (((String[]) seriesFITS.first())[7])).trim(); // now we need to figure out how many slices are in each // vol...do this by // finding at what value the counter is when it is equal to the // first one since // the imageSlice wraps around...this represents the next // vol...so the num of slices // in each vol is 1 less that int counter = 1; int sliceNum = 0; while (iter2.hasNext()) { String[] arr = (String[]) iter2.next(); String imgSlice = ((String) arr[7]).trim(); //this is to just get total num volumes if (imgSlice.equals(imageSlice)) { totalNumVolumes = totalNumVolumes + 1; } //this is to compare the image slices...but we dont want to get the first one if (imgSlice.equals(imageSlice) && counter != 1) { numSlicesCheckList.add(new Integer(counter - 1 - sliceNum)); sliceNum = counter - 1; } ++counter; } } numSlicesPerVolume = ((Integer)numSlicesCheckList.get(0)).intValue(); for(int i=1;i<numSlicesCheckList.size();i++) { if(((Integer)numSlicesCheckList.get(0)).intValue() != numSlicesPerVolume) { Preferences.debug("! ERROR: There are not equal number of image slices in all volumes of this study....exiting algorithm \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("! ERROR: There are not equal number of image slices in all volumes of this study....exiting algorithm \n"); } return false; } } //ok....we have equal # of image slices in all volumes of the study Object[] keyArray = seriesFileInfoTreeMap.keySet().toArray(); String relPath; for(int i=0;i<numSlicesPerVolume;i++) { for(int k=0;k<keyArray.length;k++) { Object[] fidArr = ((TreeSet<String[]>) seriesFileInfoTreeMap.get(keyArray[k])).toArray(); int numVols = fidArr.length / numSlicesPerVolume; String absPath = (String)((String[]) fidArr[i])[2]; relPath = new String(".." + File.separator + studyName +absPath.substring(absPath.lastIndexOf(studyName) + studyName.length(), absPath.length())); printStream.println(relPath + (String)((String[]) fidArr[i])[3]); for (int j = 1; j < numVols; j++) { absPath = (String)((String[]) fidArr[i + (numSlicesPerVolume * j)])[2]; relPath = new String(".." + File.separator + studyName + absPath.substring(absPath.lastIndexOf(studyName) + studyName.length(), absPath.length())); printStream.println(relPath + (String)((String[]) fidArr[i + (numSlicesPerVolume * j)])[3]); } } } outputStream.close(); Preferences.debug(" - path file created : " + studyPath + "_proc" + File.separator + studyName + ".path" + " \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append(" - path file created : " + studyPath + "_proc" + File.separator + studyName + ".path" + " \n"); } return true; } catch(Exception e) { Preferences.debug("! ERROR: " + e.toString() + "\n", Preferences.DEBUG_ALGORITHM); Preferences.debug("! ERROR: Creation of path file failed....exiting algorithm \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("! ERROR: " + e.toString() + "\n"); outputTextArea.append("! ERROR: Creation of path file failed....exiting algorithm \n"); } e.printStackTrace(); return false; } } /** * This method creates the path file. * * @return boolean success */ public boolean createPathFileDICOM() { try { pathFileName = studyName + ".path"; File pathFile = new File(studyPath + "_proc" + File.separator + pathFileName); FileOutputStream outputStream = new FileOutputStream(pathFile); PrintStream printStream = new PrintStream(outputStream); Set<Integer> ketSet = seriesFileInfoTreeMap.keySet(); Iterator<Integer> iter = ketSet.iterator(); ArrayList<Integer> numSlicesCheckList = new ArrayList<Integer>(); while (iter.hasNext()) { TreeSet<String[]> seriesFITS = (TreeSet<String[]>) seriesFileInfoTreeMap.get(iter.next()); Iterator<String[]> iter2 = seriesFITS.iterator(); // lets get the first element and remember its slice location String sliceLocation = ((String) (((String[]) seriesFITS.first())[1])).trim(); // now we need to figure out how many slices are in each // vol...do this by // finding at what value the counter is when it is equal to the // first one since // the sliceLocation wraps around...this represents the next // vol...so the num of slices // in each vol is 1 less that int counter = 1; int sliceNum = 0; while (iter2.hasNext()) { String[] arr = (String[]) iter2.next(); String imgSlice = ((String) arr[1]).trim(); // this is to just get total num volumes if (imgSlice.equals(sliceLocation)) { totalNumVolumes = totalNumVolumes + 1; } // this is to compare the image slices...but we dont want to get the first one if (imgSlice.equals(sliceLocation) && (counter != 1)) { numSlicesCheckList.add(new Integer(counter - 1 - sliceNum)); sliceNum = counter - 1; } ++counter; } } numSlicesPerVolume = ((Integer) numSlicesCheckList.get(0)).intValue(); for (int i = 1; i < numSlicesCheckList.size(); i++) { if (((Integer) numSlicesCheckList.get(0)).intValue() != numSlicesPerVolume) { Preferences.debug("! ERROR: There are not equal number of image slices in all volumes of this study....exiting algorithm \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("! ERROR: There are not equal number of image slices in all volumes of this study....exiting algorithm \n"); } System.out.println("! ERROR: There are not equal number of image slices in all volumes of this study....exiting algorithm \n"); return false; } } // ok....we have equal # of image slices in all volumes of the study Object[] keyArray = seriesFileInfoTreeMap.keySet().toArray(); String relPath; for (int i = 0; i < numSlicesPerVolume; i++) { for (int k = 0; k < keyArray.length; k++) { Object[] fidArr = ((TreeSet<String[]>) seriesFileInfoTreeMap.get(keyArray[k])).toArray(); int numVols = fidArr.length / numSlicesPerVolume; String absPath = (String) ((String[]) fidArr[i])[2]; relPath = new String(".." + File.separator + studyName + absPath.substring(absPath.lastIndexOf(studyName) + studyName.length(), absPath.length())); printStream.println(relPath + (String) ((String[]) fidArr[i])[3]); for (int j = 1; j < numVols; j++) { absPath = (String) ((String[]) fidArr[i + (numSlicesPerVolume * j)])[2]; relPath = new String(".." + File.separator + studyName + absPath.substring(absPath.lastIndexOf(studyName) + studyName.length(), absPath.length())); printStream.println(relPath + (String) ((String[]) fidArr[i + (numSlicesPerVolume * j)])[3]); } } } outputStream.close(); Preferences.debug(" - path file created : " + studyPath + "_proc" + File.separator + studyName + ".path" + " \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append(" - path file created : " + studyPath + "_proc" + File.separator + studyName + ".path" + " \n"); } System.out.println(" - path file created : " + studyPath + "_proc" + File.separator + studyName + ".path" + " \n"); return true; } catch (Exception e) { Preferences.debug("! ERROR: " + e.toString() + "\n", Preferences.DEBUG_ALGORITHM); Preferences.debug("! ERROR: Creation of path file failed....exiting algorithm \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("! ERROR: " + e.toString() + "\n"); outputTextArea.append("! ERROR: Creation of path file failed....exiting algorithm \n"); } System.out.println("! ERROR: " + e.toString() + "\n"); System.out.println("! ERROR: Creation of path file failed....exiting algorithm \n"); e.printStackTrace(); return false; } } /** * This method creates the list file. * * @return boolean success */ public boolean createListFileDICOM() { // we can get the info for the list file from just 1 of the imageSlices' FileInfoDicom TreeSet firstTS = // (TreeSet)seriesFileInfoTreeMap.get(seriesFileInfoTreeMap.firstKey()); FileInfoDicom fileInfoDicom = // (FileInfoDicom)firstTS.first(); Short originalColumns = (Short) (firstFileInfoDicom.getTagTable().getValue("0028,0011")); originalColumnsString = originalColumns.toString(); Short originalRows = (Short) (firstFileInfoDicom.getTagTable().getValue("0028,0010")); originalRowsString = originalRows.toString(); String dir = ((String) (firstFileInfoDicom.getTagTable().getValue("0018,1312"))).trim(); if (dir.equalsIgnoreCase("col")) { phaseEncodingString = "vertical"; } else if (dir.equalsIgnoreCase("row")) { phaseEncodingString = "horizontal"; } sliceThicknessString = ((String) (firstFileInfoDicom.getTagTable().getValue("0018,0050"))).trim(); float sliceTh = new Float(sliceThicknessString.trim()).floatValue(); sliceGapString = ((String) (firstFileInfoDicom.getTagTable().getValue("0018,0088"))).trim(); float sliceGp = new Float(sliceGapString.trim()).floatValue(); sliceGp = sliceTh - sliceGp; sliceGapString = String.valueOf(sliceGp); String fieldOfView = (String) (firstFileInfoDicom.getTagTable().getValue("0018,1100")); if ((fieldOfView == null) || fieldOfView.trim().equals("")) { // get pixel space in x direction String xyPixelSpacingString = ((String) (firstFileInfoDicom.getTagTable().getValue("0028,0030"))).trim(); int index = xyPixelSpacingString.indexOf("\\"); String xPixelSpacingString = xyPixelSpacingString.substring(index+1, xyPixelSpacingString.length()); float xPixelSpacing = new Float(xPixelSpacingString).floatValue(); float fieldOfViewFloat = xPixelSpacing * originalColumns.shortValue(); fieldOfView = String.valueOf(fieldOfViewFloat); } // hard coded for now String imagePlane = "axial"; // hard coded for now String rawImageFormat = "dicom"; String pathFilename = studyName + ".path"; String bmtrixFilename = studyName + ".BMTXT"; nimString = String.valueOf(totalNumVolumes); try { listFileName = studyName + ".list"; File listFile = new File(studyPath + "_proc" + File.separator + listFileName); FileOutputStream outputStream = new FileOutputStream(listFile); PrintStream printStream = new PrintStream(outputStream); printStream.println("<!-- DTI initialization file -->"); printStream.println("<!-- do not remove the above comment line -->"); printStream.println(); printStream.println("<!-- NUMBER OF COLUMNS -->"); printStream.println("<original_columns>" + originalColumnsString + "</original_columns>"); printStream.println(); printStream.println("<!-- NUMBER OF ROWS -->"); printStream.println("<original_rows>" + originalRowsString + "</original_rows>"); printStream.println(); printStream.println("<!-- NUMBER OF SLICES -->"); printStream.println("<slice>" + numSlicesPerVolume + "</slice>"); printStream.println(); printStream.println("<!-- NUMBER OF BMATRICES -->"); printStream.println("<nim>" + nimString + "</nim>"); printStream.println(); printStream.println("<!-- ORIENTATION OF PHASE ENCODING (vertical, horizontal) -->"); printStream.println("<phase_encode_direction>" + phaseEncodingString + "</phase_encode_direction>"); printStream.println(); printStream.println("<!-- HORIZONTAL FIELD OF VIEW (in mm) -->"); printStream.println("<x_field_of_view>" + fieldOfView + "</x_field_of_view>"); printStream.println(); printStream.println("<!-- VERTICAL FIELD OF VIEW (in mm) -->"); printStream.println("<y_field_of_view>" + fieldOfView + "</y_field_of_view>"); printStream.println(); printStream.println("<!-- FORMAT OF RAW IMAGES (integer, float, dicom, dummy) -->"); printStream.println("<rawimageformat>" + rawImageFormat + "</rawimageformat>"); printStream.println(); printStream.println("<!-- NAME OF BMATRIX FILE -->"); printStream.println("<bmatrixfile>" + bmtrixFilename + "</bmatrixfile>"); printStream.println(); printStream.println("<!-- GAP BETWEEN SLICES (in mm. Write 0 for contiguous slices) -->"); printStream.println("<slice_gap>" + sliceGapString + "</slice_gap>"); printStream.println(); printStream.println("<!-- SLICE THICKNESS (in mm) -->"); printStream.println("<slice_thickness>" + sliceThicknessString + "</slice_thickness>"); printStream.println(); printStream.println("<!-- IMAGE PLANE (axial,coronal,sagittal) -->"); printStream.println("<image_plane>" + imagePlane + "</image_plane>"); printStream.println(); printStream.println("<!-- NAME OF FILE CONTAINING PATH OF RAW IMAGES -->"); printStream.println("<raw_image_path_filename>" + pathFilename + "</raw_image_path_filename>"); outputStream.close(); } catch (Exception e) { Preferences.debug("! ERROR: " + e.toString() + "\n", Preferences.DEBUG_ALGORITHM); Preferences.debug("! ERROR: Creation of list file failed....exiting algorithm \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("! ERROR: " + e.toString() + "\n"); outputTextArea.append("! ERROR: Creation of list file failed....exiting algorithm \n"); } System.out.println("! ERROR: " + e.toString() + "\n"); System.out.println("! ERROR: Creation of list file failed....exiting algorithm \n"); return false; } Preferences.debug(" - list file created : " + studyPath + "_proc" + File.separator + studyName + ".list" + " \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append(" - list file created : " + studyPath + "_proc" + File.separator + studyName + ".list" + " \n"); } System.out.println(" - list file created : " + studyPath + "_proc" + File.separator + studyName + ".list" + " \n"); return true; } /** * This method reads in the gradient file gradient file can be in 2 differetn ways....for eDTI, there will be a * number on first line followed by correct number of gradients if it is DTI, there will be no number and just 7 * linies of gradients....this needs to be duplicated as many times as there are series. * * @return boolean success */ public boolean readGradientFileDICOM() { try { String str; FileInputStream fis = new FileInputStream(gradientFilePath); BufferedReader d = new BufferedReader(new InputStreamReader(fis)); String firstLine = d.readLine(); String[] firstLineSplits = firstLine.split("\\s+"); ArrayList<Float> arrList = new ArrayList<Float>(); ArrayList<Float> arrList2 = new ArrayList<Float>(); for (int i = 0; i < firstLineSplits.length; i++) { if (!(firstLineSplits[i].trim().equals(""))) { arrList.add(new Float(firstLineSplits[i])); } } if (arrList.size() == 1) { // this means the first line is just 1 number...indicating eDTI grad file nim = ((Float) arrList.get(0)).intValue(); direction = new float[nim][3]; while ((str = d.readLine()) != null) { str = str.trim(); String[] arr = str.split("\\s+"); for (int i = 0; i < arr.length; i++) { if (!(arr[i].trim().equals(""))) { arrList2.add(new Float(arr[i])); } } } for (int j = 0, k = 0; j < nim; j++, k = k + 3) { direction[j][0] = ((Float) arrList2.get(k)).floatValue(); direction[j][1] = ((Float) arrList2.get(k + 1)).floatValue(); direction[j][2] = ((Float) arrList2.get(k + 2)).floatValue(); } } else { // this means it is for reg DTI grad file nim = totalNumVolumes; direction = new float[nim][3]; while ((str = d.readLine()) != null) { str = str.trim(); String[] arr = str.split("\\s+"); for (int i = 0; i < arr.length; i++) { if (!(arr[i].trim().equals(""))) { arrList.add(new Float(arr[i])); } } } //we want to handle the case of gradient directions that have //7 lines in the gradient file as well if number of lines in //gradient file match up with totalNumVOlumes if(arrList.size() == 7 || (arrList.size() == nim*3)) { if(arrList.size() == 7) { for (int j = 0, k = 0; j < 7; j++, k = k + 3) { direction[j][0] = ((Float) arrList.get(k)).floatValue(); direction[j][1] = ((Float) arrList.get(k + 1)).floatValue(); direction[j][2] = ((Float) arrList.get(k + 2)).floatValue(); } // we got the first 7 lines for the direction already...so start on the 8th int counter2 = 0; for (int i = 8; i <= totalNumVolumes; i++) { direction[i - 1][0] = direction[counter2][0]; direction[i - 1][1] = direction[counter2][1]; direction[i - 1][2] = direction[counter2][2]; if ((i % 7) == 0) { // reset counter counter2 = 0; } else { counter2++; } } }else { //this is the case if num lines in gradient file match up with total num volumes for (int j = 0, k = 0; j < totalNumVolumes; j++, k = k + 3) { direction[j][0] = ((Float) arrList.get(k)).floatValue(); direction[j][1] = ((Float) arrList.get(k + 1)).floatValue(); direction[j][2] = ((Float) arrList.get(k + 2)).floatValue(); } } }else { Preferences.debug("! ERROR: Number of line entries in gradient file do not match up with number of volumes in dataset...exiting algorithm \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("! ERROR: Number of line entries in gradient file do not match up with number of volumes in dataset...exiting algorithm \n"); } System.out.println("! ERROR: Number of line entries in gradient file do not match up with number of volumes in dataset...exiting algorithm \n"); return false; } } fis.close(); } catch (Exception e) { Preferences.debug("! ERROR: " + e.toString() + "\n", Preferences.DEBUG_ALGORITHM); Preferences.debug("! ERROR: reading of gradient file failed....exiting algorithm \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("! ERROR: " + e.toString() + "\n"); outputTextArea.append("! ERROR: reading of gradient file failed....exiting algorithm \n"); } System.out.println("! ERROR: " + e.toString() + "\n"); System.out.println("! ERROR: reading of gradient file failed....exiting algorithm \n"); return false; } Preferences.debug(" - gradient file read \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append(" - gradient file read \n"); } System.out.println(" - gradient file read \n"); return true; } /** * This method obtains the b-values for each volume from either the public tag or the private tag. * * @return boolean success */ public boolean obtainBValuesDICOM() { // get b-values for each volume set // For DTI: 1. If Siemens, then extract b-value from public tag 0018,0024...the b-value is the number after ep_b // and before # 2. If GE and if Software Version is <= 8, then extract b-value from private tag // 0019,10B9...the b-value is the number after ep_b 3. If GE and if Software Version is > 8, then extract // b-value from private tag 0043,1039....the b-value is the first number in the string // For eDTI: 1. If Siemens, then extract b-value from public tag 0018,0024...the b-value is the number after // ep_b and before # 2. If GE, then extract b-value from private tag 0043,1039....the b-value is the first // number in the string Set<Integer> ketSet = seriesFileInfoTreeMap.keySet(); Iterator<Integer> iter = ketSet.iterator(); Preferences.debug(" - b-values :\n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append(" - b-values :\n"); } System.out.println(" - b-values :\n"); while (iter.hasNext()) { TreeSet<String[]> seriesFITS = (TreeSet<String[]>) seriesFileInfoTreeMap.get(iter.next()); int seriesFITSSize = seriesFITS.size(); int numVols = seriesFITSSize / numSlicesPerVolume; Object[] fidArr = seriesFITS.toArray(); String bValueLongString_pubTag = ""; String bValueLongString_privTag_0043 = ""; String bValueString_privTag_001910B9 = ""; String bValueString; Float bValue; int poundIndex = -1; for (int k = 0; k < numVols; k++) { if (isSiemens) { bValueLongString_pubTag = (String) (((String[]) fidArr[numSlicesPerVolume * k])[4]); int length = 0; int index = -1; if ((bValueLongString_pubTag != null) && (!bValueLongString_pubTag.trim().equals(""))) { String ep_b = "ep_b"; length = ep_b.length(); index = bValueLongString_pubTag.indexOf(ep_b); poundIndex = bValueLongString_pubTag.indexOf('#'); if (index != -1) { index = index + length; if ((poundIndex != -1) && (poundIndex > index)) { bValueString = (bValueLongString_pubTag.substring(index, poundIndex)).trim(); } else { bValueString = (bValueLongString_pubTag.substring(index, bValueLongString_pubTag.length())) .trim(); } if (bValueString.equals("") || (bValueString == null)) { Preferences.debug("! ERROR: No b-value found in private tag 0018,0024....exiting algorithm \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("! ERROR: No b-value found in private tag 0018,0024....exiting algorithm \n"); } System.out.println("! ERROR: No b-value found in private tag 0018,0024....exiting algorithm \n"); return false; } bValue = new Float(bValueString); bValuesArrayList.add(bValue); continue; } else { Preferences.debug("! ERROR: No b-value found in private tag 0018,0024....if dataset is interleaved, b-matrix file must be provided....exiting algorithm \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("! ERROR: No b-value found in private tag 0018,0024....if dataset is interleaved, b-matrix file must be provided....exiting algorithm \n"); } System.out.println("! ERROR: No b-value found in private tag 0018,0024....if dataset is interleaved, b-matrix file must be provided....exiting algorithm \n"); return false; } } } if (isGE) { if (!isEDTI && (geSoftwareVersion <= 8)) { if (((String[]) fidArr[numSlicesPerVolume * k])[6] != null) { bValueString_privTag_001910B9 = (String) (((String[]) fidArr[numSlicesPerVolume * k])[6]); bValueString = bValueString_privTag_001910B9.trim(); if (bValueString.equals("") || (bValueString == null)) { Preferences.debug("! ERROR: No b-value found in private tag 0019,10B9....exiting algorithm \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("! ERROR: No b-value found in private tag 0019,10B9....exiting algorithm \n"); } System.out.println("! ERROR: No b-value found in private tag 0019,10B9....exiting algorithm \n"); return false; } bValue = new Float(bValueString); bValuesArrayList.add(bValue); continue; } else { Preferences.debug("! ERROR: No b-value found in private tag 0019,10B9....exiting algorithm \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("! ERROR: No b-value found in private tag 0019,10B9....exiting algorithm \n"); } System.out.println("! ERROR: No b-value found in private tag 0019,10B9....exiting algorithm \n"); return false; } } else { if (((String[]) fidArr[numSlicesPerVolume * k])[5] != null) { bValueLongString_privTag_0043 = (String) (((String[]) fidArr[numSlicesPerVolume * k])[5]); } else { Preferences.debug("! ERROR: No b-value found in private tag 0043,1039....exiting algorithm \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("! ERROR: No b-value found in private tag 0043,1039....exiting algorithm \n"); } System.out.println("! ERROR: No b-value found in private tag 0043,1039....exiting algorithm \n"); return false; } if ((bValueLongString_privTag_0043 != null) && (!bValueLongString_privTag_0043.trim().equals(""))) { int index_privTag = bValueLongString_privTag_0043.indexOf("\\"); if (index_privTag != -1) { bValueString = (bValueLongString_privTag_0043.substring(0, index_privTag)).trim(); bValue = new Float(bValueString); bValuesArrayList.add(bValue); continue; } else { Preferences.debug("! ERROR: No b-value found in private tag 0043,1039....exiting algorithm \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("! ERROR: No b-value found in private tag 0043,1039....exiting algorithm \n"); } System.out.println("! ERROR: No b-value found in private tag 0043,1039....exiting algorithm \n"); return false; } } else { Preferences.debug("! ERROR: No b-value found in private tag 0043,1039....exiting algorithm \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("! ERROR: No b-value found in private tag 0043,1039....exiting algorithm \n"); } System.out.println("! ERROR: No b-value found in private tag 0043,1039....exiting algorithm \n"); return false; } } } } } // lets output the b-values to screen: Preferences.debug(" - [ ", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append(" - [ "); } System.out.print(" - [ "); for (int i = 0; i < bValuesArrayList.size(); i++) { float b = ((Float) bValuesArrayList.get(i)).floatValue(); Preferences.debug(String.valueOf(b) + " ", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append(String.valueOf(b) + " "); } System.out.print(String.valueOf(b) + " "); } Preferences.debug("] \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("] \n"); } System.out.print("] \n"); // check that num of b-values and num vols in gradient file are same if (bValuesArrayList.size() != direction.length) { Preferences.debug("! ERROR: the num of b values obtained, " + bValuesArrayList.size() + ", and the number of vols in the gradient file, " + direction.length + ", are not the same....exiting algorithm \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("! ERROR: the num of b values obtained, " + bValuesArrayList.size() + ", and the number of vols in the gradient file, " + direction.length + ", are not the same....exiting algorithm \n"); } System.out.println("! ERROR: the num of b values obtained, " + bValuesArrayList.size() + ", and the number of vols in the gradient file, " + direction.length + ", are not the same....exiting algorithm \n"); return false; } return true; } /** * This method creates the b-matrix file. * * @return boolean success */ public boolean createBMatrixFileDICOM() { try { StringBuffer sb; int padLength; bmatrixFileName = studyName + ".BMTXT"; File bMatrixFile = new File(studyPath + "_proc" + File.separator + bmatrixFileName); FileOutputStream outputStream = new FileOutputStream(bMatrixFile); PrintStream printStream = new PrintStream(outputStream); // formula for bmtxt values is : // bxx 2bxy 2bxz byy 2byz bzz // x, y, and z values come from the direction[][] for (int i = 0; i < bValuesArrayList.size(); i++) { float b = ((Float) bValuesArrayList.get(i)).floatValue(); float x = direction[i][0]; float y = direction[i][1]; float z = direction[i][2]; float _bxx = b * x * x; if (Math.abs(_bxx) == 0) { _bxx = Math.abs(_bxx); } float _2bxy = 2 * b * x * y; if (Math.abs(_2bxy) == 0) { _2bxy = Math.abs(_2bxy); } float _2bxz = 2 * b * x * z; if (Math.abs(_2bxz) == 0) { _2bxz = Math.abs(_2bxz); } float _byy = b * y * y; if (Math.abs(_byy) == 0) { _byy = Math.abs(_byy); } float _2byz = 2 * b * y * z; if (Math.abs(_2byz) == 0) { _2byz = Math.abs(_2byz); } float _bzz = b * z * z; if (Math.abs(_bzz) == 0) { _bzz = Math.abs(_bzz); } // following is for 1.4 compliant // otherwise, it would be : printStream.printf("%16f", b*x*x); String _bxx_string = String.valueOf(_bxx); int _bxx_stringLength = _bxx_string.length(); sb = new StringBuffer(16); padLength = 16 - _bxx_stringLength; for (int j = 0; j < padLength; j++) { sb.insert(j, " "); } sb.insert(padLength, _bxx_string); printStream.print(sb.toString()); String _2bxy_string = String.valueOf(_2bxy); int _2bxy_stringLength = _2bxy_string.length(); sb = new StringBuffer(16); padLength = 16 - _2bxy_stringLength; for (int j = 0; j < padLength; j++) { sb.insert(j, " "); } sb.insert(padLength, _2bxy_string); printStream.print(sb.toString()); String _2bxz_string = String.valueOf(_2bxz); int _2bxz_stringLength = _2bxz_string.length(); sb = new StringBuffer(16); padLength = 16 - _2bxz_stringLength; for (int j = 0; j < padLength; j++) { sb.insert(j, " "); } sb.insert(padLength, _2bxz_string); printStream.print(sb.toString()); String _byy_string = String.valueOf(_byy); int _byy_stringLength = _byy_string.length(); sb = new StringBuffer(16); padLength = 16 - _byy_stringLength; for (int j = 0; j < padLength; j++) { sb.insert(j, " "); } sb.insert(padLength, _byy_string); printStream.print(sb.toString()); String _2byz_string = String.valueOf(_2byz); int _2byz_stringLength = _2byz_string.length(); sb = new StringBuffer(16); padLength = 16 - _2byz_stringLength; for (int j = 0; j < padLength; j++) { sb.insert(j, " "); } sb.insert(padLength, _2byz_string); printStream.print(sb.toString()); String _bzz_string = String.valueOf(_bzz); int _bzz_stringLength = _bzz_string.length(); sb = new StringBuffer(16); padLength = 16 - _bzz_stringLength; for (int j = 0; j < padLength; j++) { sb.insert(j, " "); } sb.insert(padLength, _bzz_string); printStream.print(sb.toString()); printStream.println(); } outputStream.close(); } catch (Exception e) { Preferences.debug("! ERROR: " + e.toString() + "\n", Preferences.DEBUG_ALGORITHM); Preferences.debug("! ERROR: Creation of b-matrix file failed....exiting algorithm \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("! ERROR: " + e.toString() + "\n"); outputTextArea.append("! ERROR: Creation of b-matrix file failed....exiting algorithm \n"); } System.out.println("! ERROR: " + e.toString() + "\n"); System.out.println("! ERROR: Creation of b-matrix file failed....exiting algorithm \n"); return false; } Preferences.debug(" - b-matrix file created : " + studyPath + "_proc" + File.separator + studyName + ".BMTXT" + " \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append(" - b-matrix file created : " + studyPath + "_proc" + File.separator + studyName + ".BMTXT" + " \n"); } System.out.println(" - b-matrix file created : " + studyPath + "_proc" + File.separator + studyName + ".BMTXT" + " \n"); return true; } //------methods for par/rec ---------------------------------------------------------------------------------- /** * This method obtains list file data mostly from the 1st slice * * @return */ public boolean obtainListFileDataParRec() { try{ fileInfoPR = (FileInfoPARREC)image4D.getFileInfo(0); int extents[] = image4D.getExtents(); originalColumnsString = String.valueOf(extents[0]); originalRowsString = String.valueOf(extents[1]); numSlicesString = String.valueOf(extents[2]); volParameters = fileInfoPR.getVolParameters(); String fovString = (String)volParameters.get("scn_fov"); String[] fovs = fovString.trim().split("\\s+"); horizontalFOVString = fovs[0]; verticalFOVString = fovs[2]; //slices = fileInfoPR.getSlices(); //get some list file info from 1st slice FileInfoPARREC firstFileInfo = (FileInfoPARREC)image4D.getFileInfo(0); String slice = firstFileInfo.getSliceInfo(); String[] values = slice.split("\\s+"); //slice gap sliceGapString = values[23]; //slice thickness sliceThicknessString = values[22]; //slice orientation int sliceOrientation = (Integer.valueOf(values[25])).intValue(); if(sliceOrientation == 1) { imageOrientationString = "axial"; }else if(sliceOrientation == 2) { imageOrientationString = "sagittal"; }else if(sliceOrientation == 3) { imageOrientationString = "coronal"; } //Philips puts in one volume as the average of all the DWIs. This //volume will have a non-zero B value and 0 in the gradients //Once we find this volume, exclude avgVolIndex = -1; for(int i = 0,vol=0; i < (extents[2] * extents[3]);i=i+extents[2],vol++) { FileInfoPARREC fileInfoPR = (FileInfoPARREC)image4D.getFileInfo(i); slice = fileInfoPR.getSliceInfo(); values = slice.split("\\s+"); float bValue = (Float.valueOf(values[33])).floatValue(); float grad1 = (Float.valueOf(values[45])).floatValue(); float grad2 = (Float.valueOf(values[46])).floatValue(); float grad3 = (Float.valueOf(values[47])).floatValue(); if(bValue != 0 && grad1 == 0 && grad2 == 0 && grad3 == 0) { avgVolIndex = vol; } } if(avgVolIndex != -1) { nimString = String.valueOf(extents[3]-1); }else { nimString = String.valueOf(extents[3]); } } catch(ArrayIndexOutOfBoundsException e) { //this means that we the Par/Rec version is an older one //so first check if gradient file was supplied...if so, get nimString //by the number of lines in that file....if no gradient file was supplied, //this means the b-matrix file was provided...so copy //also...might as well just read the gradient file at this point if((gradientFilePath == null || gradientFilePath.trim().equals("")) && (bmtxtFilePath == null || bmtxtFilePath.trim().equals(""))) { Preferences.debug("! ERROR: A valid gradient file or bmatrix file must be supplied for this dataset....exiting algorithm \n", Preferences.DEBUG_ALGORITHM); outputTextArea.append("! ERROR: A valid gradient file or bmatrix file must be supplied for this dataset....exiting algorithm \n"); return false; }else { if(gradientFilePath == null || gradientFilePath.trim().equals("")) { //this means that the bmtxt file was provided instead...so... // copy and rename b-matrix file Preferences.debug("* b-matrix file provided \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("* b-matrix file provided \n"); } System.out.println("* b-matrix file provided \n"); success = copyBMatrixFile(); if (success == false) { finalize(); setCompleted(true); return false; } }else { boolean success = readGradientFileParRec(); if(success == false) { Preferences.debug("! ERROR: Error in reading gradient file....exiting algorithm \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("! ERROR: Error in reading gradient file....exiting algorithm \n"); } return false; } else { isOldVersion = true; //Philips puts in one volume as the average of all the DWIs. This //volume will have a non-zero B value and 0 in the gradients //Once we find this volume, exclude avgVolIndex = -1; int extents[] = image4D.getExtents(); int k = 0; for(int i = 0,vol=0; i < (extents[2] * extents[3]);i=i+extents[2],vol++) { FileInfoPARREC fileInfoPR = (FileInfoPARREC)image4D.getFileInfo(i); String slice = fileInfoPR.getSliceInfo(); String[] values = slice.split("\\s+"); float bValue = (Float.valueOf(values[33])).floatValue(); if(bValue != 0) { String[] gradStrings = oldVersionGradientsAL.get(k); float grad1 = (Float.valueOf(gradStrings[0])).floatValue(); float grad2 = (Float.valueOf(gradStrings[1])).floatValue(); float grad3 = (Float.valueOf(gradStrings[2])).floatValue(); if(grad1 == 0 && grad2 == 0 && grad3 == 0) { avgVolIndex = vol; } k++; } } if(avgVolIndex != -1) { nimString = String.valueOf(extents[3]-1); }else { nimString = String.valueOf(extents[3]); } } } } } catch(Exception e) { Preferences.debug("! ERROR: " + e.toString() + "\n", Preferences.DEBUG_ALGORITHM); Preferences.debug("! ERROR: Obtaining list file data falied....exiting algorithm \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("! ERROR: " + e.toString() + "\n"); outputTextArea.append("! ERROR: Obtaining list file data failed....exiting algorithm \n"); } return false; } return true; } /** * this method reads the gradient file * * @return */ public boolean readGradientFileParRec() { try { String str; FileInputStream fis = new FileInputStream(gradientFilePath); BufferedReader d = new BufferedReader(new InputStreamReader(fis)); oldVersionGradientsAL = new ArrayList<String[]>(); while ((str = d.readLine()) != null) { str = str.trim(); String[] arr = str.split("\\s+"); oldVersionGradientsAL.add(arr); nimCounter++; } fis.close(); } catch(Exception e) { return false; } return true; } /** * this method creates the proc dir in which the list file, path file, and b-matrix file go. * * @return boolean success */ public boolean createProcDirAndImageSlicesDirParRec() { // create parallel proc dir to study path that will hold list file, path file, and b matrix file File procDir = new File(prFileDir + "_proc"); if (!procDir.isDirectory()) { boolean success = new File(prFileDir + "_proc").mkdir(); if (!success) { Preferences.debug("! ERROR: Creation of proc directory failed....exiting algorithm \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("! ERROR: Creation of proc directory failed....exiting algorithm \n"); } return false; } } else { // we should delete all the files in the procDir if there are any File[] listFiles = procDir.listFiles(); if (listFiles.length > 0) { for (int i = 0; i < listFiles.length; i++) { String name = listFiles[i].getName(); if (name.equals(studyName + ".path") || name.equals(studyName + ".list") || name.equals(studyName + ".BMTXT")) { listFiles[i].delete(); } } } } Preferences.debug(" - proc dir created : " + prFileDir + "_proc \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append(" - proc dir created : " + prFileDir + "_proc \n"); } //create image slices dir imageSlicesDirPath = prFileDir + "_proc" + File.separator + studyName + "_slices"; relativeImageSlicesDirPath = "./" + studyName + "_slices/"; File imageSlicesDir = new File(imageSlicesDirPath); if(!imageSlicesDir.isDirectory()) { boolean success = imageSlicesDir.mkdir(); if (!success) { Preferences.debug("! ERROR: Creation of image slices directory failed....exiting algorithm \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("! ERROR: Creation of image slices directory failed....exiting algorithm \n"); } return false; } }else { //we should delete all the fils under the imageSlicesDir File[] listFiles = imageSlicesDir.listFiles(); if (listFiles.length > 0) { for (int i = 0; i < listFiles.length; i++) { listFiles[i].delete(); } } } Preferences.debug(" - imageSlices dir created : " + prFileDir + File.separator + "imageSlices \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append(" - imageSlices dir created : " + prFileDir + File.separator + "imageSlices \n"); } return true; } /** * This method creates the list file. * * @return boolean success */ public boolean createListFileParRec() { try { File listFile = new File(prFileDir + "_proc" + File.separator + listFileName); FileOutputStream outputStream = new FileOutputStream(listFile); PrintStream printStream = new PrintStream(outputStream); printStream.println("<!-- DTI initialization file -->"); printStream.println("<!-- do not remove the above comment line -->"); printStream.println(); printStream.println("<!-- NUMBER OF COLUMNS -->"); printStream.println("<original_columns>" + originalColumnsString + "</original_columns>"); printStream.println(); printStream.println("<!-- NUMBER OF ROWS -->"); printStream.println("<original_rows>" + originalRowsString + "</original_rows>"); printStream.println(); printStream.println("<!-- NUMBER OF SLICES -->"); printStream.println("<slice>" + numSlicesString + "</slice>"); printStream.println(); printStream.println("<!-- NUMBER OF BMATRICES -->"); printStream.println("<nim>" + nimString + "</nim>"); printStream.println(); printStream.println("<!-- ORIENTATION OF PHASE ENCODING (vertical, horizontal) -->"); printStream.println("<phase_encode_direction>" + phaseEncodingString + "</phase_encode_direction>"); printStream.println(); printStream.println("<!-- HORIZONTAL FIELD OF VIEW (in mm) -->"); printStream.println("<x_field_of_view>" + horizontalFOVString + "</x_field_of_view>"); printStream.println(); printStream.println("<!-- VERTICAL FIELD OF VIEW (in mm) -->"); printStream.println("<y_field_of_view>" + verticalFOVString + "</y_field_of_view>"); printStream.println(); printStream.println("<!-- FORMAT OF RAW IMAGES (integer, float, dicom, dummy) -->"); printStream.println("<rawimageformat>" + rawImageFormatString + "</rawimageformat>"); printStream.println(); printStream.println("<!-- NAME OF BMATRIX FILE -->"); printStream.println("<bmatrixfile>" + bmatrixFileName + "</bmatrixfile>"); printStream.println(); printStream.println("<!-- GAP BETWEEN SLICES (in mm. Write 0 for contiguous slices) -->"); printStream.println("<slice_gap>" + sliceGapString + "</slice_gap>"); printStream.println(); printStream.println("<!-- SLICE THICKNESS (in mm) -->"); printStream.println("<slice_thickness>" + sliceThicknessString + "</slice_thickness>"); printStream.println(); printStream.println("<!-- IMAGE PLANE (axial,coronal,sagittal) -->"); printStream.println("<image_plane>" + imageOrientationString + "</image_plane>"); printStream.println(); printStream.println("<!-- NAME OF FILE CONTAINING PATH OF RAW IMAGES -->"); printStream.println("<raw_image_path_filename>" + pathFileName + "</raw_image_path_filename>"); outputStream.close(); }catch(Exception e) { Preferences.debug("! ERROR: " + e.toString() + "\n", Preferences.DEBUG_ALGORITHM); Preferences.debug("! ERROR: Creation of list file failed....exiting algorithm \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("! ERROR: " + e.toString() + "\n"); outputTextArea.append("! ERROR: Creation of list file failed....exiting algorithm \n"); } return false; } Preferences.debug(" - list file created : " + prFileDir + "_proc" + File.separator + listFileName + " \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append(" - list file created : " + prFileDir + "_proc" + File.separator + listFileName + " \n"); } return true; } /** * This method creates the B-Matrix file * * @return */ public boolean createBMatrixFileParRec() { int extents[] = image4D.getExtents(); String slice; String[] values; try { StringBuffer sb; int padLength; File bMatrixFile = new File(prFileDir + "_proc" + File.separator + bmatrixFileName); FileOutputStream outputStream = new FileOutputStream(bMatrixFile); PrintStream printStream = new PrintStream(outputStream); float x = 0; float y = 0; float z = 0; float b; int k = 0; for(int i = 0,vol=0; i < (extents[2] * extents[3]);i=i+extents[2],vol++) { FileInfoPARREC fileInfoPR = (FileInfoPARREC)image4D.getFileInfo(i); if(vol!=avgVolIndex) { slice = fileInfoPR.getSliceInfo(); values = slice.split("\\s+"); b = (Float.valueOf(values[33])).floatValue(); if(!isOldVersion) { x = (Float.valueOf(values[45])).floatValue(); y = (Float.valueOf(values[46])).floatValue(); z = (Float.valueOf(values[47])).floatValue(); }else { if(b != 0) { String[] grads = oldVersionGradientsAL.get(k); x = Float.valueOf(grads[0]).floatValue(); y = Float.valueOf(grads[1]).floatValue(); z = Float.valueOf(grads[2]).floatValue(); k++; } } // For Par/Rec datasets, Philips uses another coordinate frame // formula for bmtxt values is : // bzz 2bxz -2byz bxx -2bxy byy float _bxx = b * x * x; if (Math.abs(_bxx) == 0) { _bxx = Math.abs(_bxx); } float _2bxy = -2.0f * b * x * y; if (Math.abs(_2bxy) == 0) { _2bxy = Math.abs(_2bxy); } float _2bxz = 2.0f * b * x * z; if (Math.abs(_2bxz) == 0) { _2bxz = Math.abs(_2bxz); } float _byy = b * y * y; if (Math.abs(_byy) == 0) { _byy = Math.abs(_byy); } float _2byz = -2.0f * b * y * z; if (Math.abs(_2byz) == 0) { _2byz = Math.abs(_2byz); } float _bzz = b * z * z; if (Math.abs(_bzz) == 0) { _bzz = Math.abs(_bzz); } // following is for 1.4 compliant // otherwise, it would be : printStream.printf("%16f", b*x*x); String _bzz_string = String.valueOf(_bzz); int _bzz_stringLength = _bzz_string.length(); sb = new StringBuffer(16); padLength = 16 - _bzz_stringLength; for (int j = 0; j < padLength; j++) { sb.insert(j, " "); } sb.insert(padLength, _bzz_string); printStream.print(sb.toString()); String _2bxz_string = String.valueOf(_2bxz); int _2bxz_stringLength = _2bxz_string.length(); sb = new StringBuffer(16); padLength = 16 - _2bxz_stringLength; for (int j = 0; j < padLength; j++) { sb.insert(j, " "); } sb.insert(padLength, _2bxz_string); printStream.print(sb.toString()); String _2byz_string = String.valueOf(_2byz); int _2byz_stringLength = _2byz_string.length(); sb = new StringBuffer(16); padLength = 16 - _2byz_stringLength; for (int j = 0; j < padLength; j++) { sb.insert(j, " "); } sb.insert(padLength, _2byz_string); printStream.print(sb.toString()); String _bxx_string = String.valueOf(_bxx); int _bxx_stringLength = _bxx_string.length(); sb = new StringBuffer(16); padLength = 16 - _bxx_stringLength; for (int j = 0; j < padLength; j++) { sb.insert(j, " "); } sb.insert(padLength, _bxx_string); printStream.print(sb.toString()); String _2bxy_string = String.valueOf(_2bxy); int _2bxy_stringLength = _2bxy_string.length(); sb = new StringBuffer(16); padLength = 16 - _2bxy_stringLength; for (int j = 0; j < padLength; j++) { sb.insert(j, " "); } sb.insert(padLength, _2bxy_string); printStream.print(sb.toString()); String _byy_string = String.valueOf(_byy); int _byy_stringLength = _byy_string.length(); sb = new StringBuffer(16); padLength = 16 - _byy_stringLength; for (int j = 0; j < padLength; j++) { sb.insert(j, " "); } sb.insert(padLength, _byy_string); printStream.print(sb.toString()); printStream.println(); } } outputStream.close(); }catch(Exception e) { Preferences.debug("! ERROR: " + e.toString() + "\n", Preferences.DEBUG_ALGORITHM); Preferences.debug("! ERROR: Creation of bmatrix file failed....exiting algorithm \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("! ERROR: " + e.toString() + "\n"); outputTextArea.append("! ERROR: Creation of bmatrix file failed....exiting algorithm \n"); } return false; } Preferences.debug(" - b-matrix file created : " + prFileDir + "_proc" + File.separator + bmatrixFileName + " \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append(" - b-matrix file created : " + prFileDir + "_proc" + File.separator + bmatrixFileName + " \n"); } return true; } /** * This method writes out the image slices as raw float * * @return */ public boolean writeImageSlicesParRec() { //When writing out the image slices, the floating point value should be determined by: //# === PIXEL VALUES ============================================================= // # PV = pixel value in REC file, FP = floating point value, DV = displayed value on console // # RS = rescale slope, RI = rescale intercept, SS = scale slope // # DV = PV * RS + RI FP = DV / (RS * SS) //get some of the values for eqautions above from 1st slice FileInfoPARREC firstFileInfo = (FileInfoPARREC)image4D.getFileInfo(0); String slice = firstFileInfo.getSliceInfo(); String[] values = slice.split("\\s+"); float RS = Float.valueOf(values[12]).floatValue(); float RI = Float.valueOf(values[11]).floatValue(); float SS = Float.valueOf(values[13]).floatValue(); float PV; float DV; float FP; xDim = image4D.getExtents()[0]; yDim = image4D.getExtents()[1]; zDim = image4D.getExtents()[2]; tDim = image4D.getExtents()[3]; int volLength = xDim * yDim * zDim; int sliceLength = xDim * yDim; int[] sliceExtents = new int[2]; sliceExtents[0] = xDim; sliceExtents[1] = yDim; float[] volBuffer = new float[volLength]; float[] sliceBuffer = new float[sliceLength]; FileInfoImageXML fileInfoXML; String dir = prFileDir + "_proc" + File.separator + studyName + "_slices" + File.separator; String filename; int[] sliceUnits = new int[2]; sliceUnits[0] = Unit.MILLIMETERS.getLegacyNum(); sliceUnits[1] = Unit.MILLIMETERS.getLegacyNum(); float[] sliceResols = new float[2]; float xRes = Float.valueOf(horizontalFOVString)/xDim; float yRes = Float.valueOf(verticalFOVString)/yDim; sliceResols[0] = xRes; sliceResols[1] = yRes; int type = ModelStorageBase.FLOAT; FileIO fileIO = new FileIO(); fileIO.setQuiet(true); ModelImage sliceImage = new ModelImage(ModelStorageBase.FLOAT, sliceExtents, studyName); int image4DLength = xDim * yDim * zDim * tDim; float[] image4DBuffer = new float[image4DLength]; try { image4D.exportData(0, image4DLength, image4DBuffer); }catch(Exception e) { e.printStackTrace(); return false; } int volStart = 0; int filenameVol = 0; for(int volIndex=0;volIndex<tDim;volIndex++) { if(volIndex != avgVolIndex) { try { //extract the volume buffer from the 4D buffer for(int i=volStart,j=0;i<volLength;i++,j++) { volBuffer[j] = image4DBuffer[i]; } int index = 0; for(int sliceIndex=0;sliceIndex<zDim;sliceIndex++) { for(int i=0;i<sliceBuffer.length;i++) { //do calculations to rescale PV = volBuffer[index]; DV = PV * RS + RI; FP = DV / (RS * SS); sliceBuffer[i] = FP; index++; } //write out slice...we will write out starting with 1...so add 1 int volInt = filenameVol + 1; String volString; if(volInt < 10) { volString = "0" + volInt; }else { volString = String.valueOf(volInt); } filename = "vol" + volString + "slice" + (sliceIndex + 1); String pathString = relativeImageSlicesDirPath + filename; unsortedPathsArrayList.add(pathString); fileInfoXML = new FileInfoImageXML(filename, dir, FileUtility.RAW); fileInfoXML.setDataType(type); fileInfoXML.setExtents(sliceExtents); fileInfoXML.setUnitsOfMeasure(sliceUnits); fileInfoXML.setResolutions(sliceResols); fileInfoXML.setEndianess(FileBase.LITTLE_ENDIAN); fileInfoXML.setOffset(0); sliceImage.importData(0, sliceBuffer, false); sliceImage.setFileInfo(fileInfoXML,0); FileWriteOptions opts = new FileWriteOptions(true); opts.setFileType(FileUtility.RAW); opts.setFileDirectory(dir); opts.setFileName(filename); opts.setBeginSlice(0); opts.setEndSlice(0); opts.setOptionsSet(true); fileIO.writeImage(sliceImage, opts); } filenameVol++; } catch (Exception e) { Preferences.debug("! ERROR: " + e.toString() + "\n", Preferences.DEBUG_ALGORITHM); Preferences.debug("! ERROR: Writing of image slices failed....exiting algorithm \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("! ERROR: " + e.toString() + "\n"); outputTextArea.append("! ERROR: Writing of image slices failed....exiting algorithm \n"); } return false; } } volStart = volStart + volLength; Preferences.debug(".", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("."); } } sliceImage.disposeLocal(); sliceImage = null; return true; } /** * This method creates the path file * * @return */ public boolean createPathFileParRec() { try { File listFile = new File(prFileDir + "_proc" + File.separator + pathFileName); FileOutputStream outputStream = new FileOutputStream(listFile); PrintStream printStream = new PrintStream(outputStream); for(int i=0;i<zDim;i++) { for(int j=i;j<unsortedPathsArrayList.size();j=j+zDim) { printStream.println(((String)unsortedPathsArrayList.get(j)) + ".raw"); } } outputStream.close(); }catch(Exception e) { Preferences.debug("! ERROR: " + e.toString() + "\n", Preferences.DEBUG_ALGORITHM); Preferences.debug("! ERROR: Creation of path file failed....exiting algorithm \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("! ERROR: " + e.toString() + "\n"); outputTextArea.append("! ERROR: Creation of path file failed....exiting algorithm \n"); } return false; } Preferences.debug(" - path file created : " + prFileDir + "_proc" + File.separator + pathFileName+ " \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append(" - path file created : " + prFileDir + "_proc" + File.separator + pathFileName + " \n"); } return true; } //-------for both par/rec and dicom ------------------------------------------------------------------------ //------------metods used by dicom and par-rec ------------------------------------------------------------ /** * this method cleans up the proc dir if success is false and it sets the lists to null. */ public void finalize() { // delete any of the files that were created if success is false if (success == false) { if (isProcDirCreated) { Preferences.debug("! Deleting .list, .path, and .BMTXT (if created) from proc dir \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("! Deleting .list, .path, and .BMTXT (if created) from proc dir \n"); } System.out.println("! Deleting .list, .path, and .BMTXT (if created) from proc dir \n"); File procDir; if(isDICOM) { procDir = new File(studyPath + "_proc"); }else { procDir = new File(prFileDir + "_proc"); } File[] files = procDir.listFiles(); if (files.length > 0) { for (int i = 0; i < files.length; i++) { String name = files[i].getName(); if (name.equals(pathFileName) || name.equals(listFileName) || name.equals(bmatrixFileName)) { files[i].delete(); } } } procDir.delete(); } } if(isDICOM) { seriesFileInfoTreeSet = null; seriesFileInfoTreeMap = null; } success = true; } /** * This method copies the optional b matrix file that user provided, and copies it to proc dir and renames it to the * correct naming syntax. * * @return boolean */ public boolean copyBMatrixFile() { File from = new File(bmtxtFilePath); String pathString; if(isDICOM) { pathString = studyPath; }else { pathString = prFileDir; } File to = new File(pathString + "_proc" + File.separator + studyName + ".BMTXT"); Writer out = null; FileInputStream fis = null; FileOutputStream fos = null; try { String str; fis = new FileInputStream(from); fos = new FileOutputStream(to); out = new OutputStreamWriter(fos); BufferedReader d = new BufferedReader(new InputStreamReader(fis)); while ((str = d.readLine()) != null) { out.write(str + "\n"); out.flush(); } } catch (Exception e) { Preferences.debug("! ERROR: " + e.toString() + "\n", Preferences.DEBUG_ALGORITHM); Preferences.debug("! ERROR: copying of b-matrix to proc dir failed....exiting algorithm \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append("! ERROR: " + e.toString() + "\n"); outputTextArea.append("! ERROR: copying of b-matrix to proc dir failed....exiting algorithm \n"); } System.out.println("! ERROR: " + e.toString() + "\n"); System.out.println("! ERROR: copying of b-matrix to proc dir failed....exiting algorithm \n"); return false; } finally { try { if (out != null) { out.close(); } if (fos != null) { fos.close(); } if (fis != null) { fis.close(); } } catch (IOException e) { } } Preferences.debug(" - b-matrix file copied and renamed to : " + pathString + "_proc" + File.separator + studyName + ".BMTXT" + " \n", Preferences.DEBUG_ALGORITHM); if (outputTextArea != null) { outputTextArea.append(" - b-matrix file copied and renamed to : " + pathString + "_proc" + File.separator + studyName + ".BMTXT" + " \n"); } System.out.println(" - b-matrix file copied and renamed to : " + pathString + "_proc" + File.separator + studyName + ".BMTXT" + " \n"); return true; } //---------INNER CLASSES ------------------------------------------------------------------------------------- //~ Inner Classes -------------------------------------------------------------------------------------------------- /** * This inner class is used to sort the list by instance number and vol. the vol is determined by the filename */ private class InstanceNumberVolComparator implements Comparator<Object> { /** * * @param oA * @param oB * * @return int */ public int compare(Object oA, Object oB) { String[] aA = (String[]) oA; String[] aB = (String[]) oB; String instancNoA_String = ((String) aA[0]).trim(); if (instancNoA_String == null) { instancNoA_String = ""; } String instancNoB_String = ((String) aB[0]).trim(); if (instancNoB_String == null) { instancNoB_String = ""; } int instanceNoA = new Integer(instancNoA_String).intValue(); int instanceNoB = new Integer(instancNoB_String).intValue(); String filenameA = ((String) aA[3]).trim(); String filenameB = ((String) aB[3]).trim(); String volStringA = filenameA.substring(filenameA.lastIndexOf("volume") + 6, filenameA.lastIndexOf('.')); int volNumberA = new Integer(volStringA).intValue(); String volStringB = filenameB.substring(filenameB.lastIndexOf("volume") + 6, filenameB.lastIndexOf('.')); int volNumberB = new Integer(volStringB).intValue(); if (volNumberA == volNumberB) { if (instanceNoA < instanceNoB) { return -1; } if (instanceNoA > instanceNoB) { return 1; } } if (volNumberA < volNumberB) { return -1; } if (volNumberA > volNumberB) { return 1; } // this should never happen return -1; } } /** * This inner class is used to sort * the list by instance number */ private class InstanceNumberComparator implements Comparator<Object> { public int compare(Object oA, Object oB) { String[] aA = (String[]) oA; String[] aB = (String[]) oB; String instancNoA_String = ((String)aA[0]).trim(); if (instancNoA_String == null) { instancNoA_String = ""; } String instancNoB_String = ((String)aB[0]).trim(); if (instancNoB_String == null) { instancNoB_String = ""; } if ((!instancNoA_String.equals("")) && (!instancNoB_String.equals(""))) { int instanceNoA = new Integer(instancNoA_String).intValue(); int instanceNoB = new Integer(instancNoB_String).intValue(); if (instanceNoA < instanceNoB) { return -1; } if (instanceNoA > instanceNoB) { return 1; } } return 0; } } }
package com.example.edvisor; import android.content.Context; import android.database.Cursor; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.concurrent.Semaphore; public class DataBase_Implementation implements DB_Interface { Db_Helper db; ArrayList<Edvisor> edvisor; ArrayList<Booking> booking; ArrayList<Edvisor>[] a2; Edvisor edvisor1; Object obj=new Object(); Semaphore available = new Semaphore(0); public DataBase_Implementation(Context context) { } @Override public boolean Save_Booking(ArrayList<Booking> booking , DatabaseReference myRef) { myRef.setValue(booking); return true; } @Override public boolean Save_Edvisor(ArrayList<Edvisor> edvisor, DatabaseReference myRef) { myRef.setValue(edvisor); return true; } @Override public boolean Save_Mesage(ArrayList<String> chat, DatabaseReference myRef) { return false; } @Override public boolean Save_Customer(Customer customer,DatabaseReference myRef) { myRef.setValue(customer); return true; } }
/*A Java program to perform Matching a String against regular expression using matches()*/ class Matchreg { public static void main(String[] args) { String str=new String("Welcome to Javacode.com"); System.out.println("Return value:"); System.out.println(str.matches("(.*)Tutorials(.*)")); System.out.println("Return value:"); System.out.println(str.matches("Tutorials")); System.out.println("Return value:"); System.out.println(str.matches("Welcome(.*)")); } }
public class TwoWayNode<T>{ private T data; private TwoWayNode<T> next; private TwoWayNode<T> previous; private static TwoWayNode freelist = null; public TwoWayNode(T dt){ this.data = dt; } public TwoWayNode(T dt, TwoWayNode<T> nxt){ this.data = dt; this.next = nxt; } public TwoWayNode(T dt, TwoWayNode<T> nxt, TwoWayNode<T> prv){ this.data = dt; this.next = nxt; this.previous = prv; } public static <T> TwoWayNode<T> get(T data, TwoWayNode<T> nxt, TwoWayNode<T> prv){ if (freelist == null) return new TwoWayNode<T>(data, nxt, prv); TwoWayNode<T> temporal = freelist; freelist = freelist.getNext(); temporal.setData(data); temporal.setNext(nxt); temporal.setPrevious(prv); return temporal; } public void release(){ data = null; next = freelist; freelist = this; } public void setData(T dt){ this.data = dt; } public void setNext(TwoWayNode<T> nxt){ this.next = nxt; } public void setPrevious(TwoWayNode<T> prv){ this.previous = prv; } public T getData(){ return this.data; } public TwoWayNode<T> getNext(){ return this.next; } public TwoWayNode<T> getPrevious(){ return this.previous; } @Override public String toString(){ return this.data.toString(); } }
package Account_Module.Wallet; import Account_Module.util.BtcAddressUtils; import com.google.common.collect.Maps; import lombok.Cleanup; import Account_Module.util.Base58Check; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.CipherOutputStream; import javax.crypto.SealedObject; import javax.crypto.spec.SecretKeySpec; import java.io.*; import java.util.Map; import java.util.Set; /** * 钱包工具类 * 功能: * 1.初始化创建钱包的文件,从磁盘加载钱包文件 * 2.保存所有的钱包到磁盘中(使用AES对称加密,密码由用户设置) * 3.获取钱包文件的所有的地址 * 4.根据一个地址获取一个钱包 * 5.根据公钥获取钱包地址 * 6.创建一个钱包(公钥,私钥) * @author dingkonghua * @date 2018/07/27 */ public class WalletUtils { //钱包工具实例 private volatile static WalletUtils instance; public static WalletUtils getInstance() { if (instance == null) { synchronized (WalletUtils.class) { if (instance == null) { instance = new WalletUtils(); } } } return instance; } private WalletUtils() { initWalletFile(); } //钱包文件 private final static String WALLET_FILE = "wallet.dat"; //加密算法AES对称加密,将保存的钱包数据通过密码进行对称加密 private static final String ALGORITHM = "AES"; //todo 保存钱包的密码,这里应该由每个账户来指定 private static final byte[] CIPHER_TEXT = "2oF@5sC%DNf32y!TmiZi!tG9W5rLaniD".getBytes(); /** * 初始化钱包文件 */ private void initWalletFile() { File file = new File(WALLET_FILE); if (!file.exists()) { this.saveToDisk(new Wallets()); } else { this.loadFromDisk(); } } /** * 获取所有的钱包地址 * @return */ public Set<String> getAddresses() { Wallets wallets = this.loadFromDisk(); return wallets.getAddresses(); } /** * 获取钱包数据 * @param address 钱包地址 * @return */ public Wallet getWallet(String address) { Wallets wallets = this.loadFromDisk(); return wallets.getWallet(address); } /** * 根据公钥Hash获取钱包地址 * @return */ public synchronized String getAddressByPublicHashKey(byte[] publicHashKey) { try { // 2. 添加版本 0x00 ByteArrayOutputStream addrStream = new ByteArrayOutputStream(); addrStream.write((byte) 0); addrStream.write(publicHashKey); byte[] versionedPayload = addrStream.toByteArray(); // 3. 计算校验码 byte[] checksum = BtcAddressUtils.checksum(versionedPayload); // 4. 得到 version + paylod + checksum 的组合 addrStream.write(checksum); byte[] binaryAddress = addrStream.toByteArray(); // 5. 执行Base58转换处理 return Base58Check.rawBytesToBase58(binaryAddress); } catch (IOException e) { e.printStackTrace(); } return null; } /** * 根据公钥获取钱包地址 * @return */ public synchronized String getAddressByPublicKey(byte[] publicKey) { try { // 1. 获取 ripemdHashedKey byte[] ripemdHashedKey = BtcAddressUtils.ripeMD160Hash(publicKey); // 2. 添加版本 0x00 ByteArrayOutputStream addrStream = new ByteArrayOutputStream(); addrStream.write((byte) 0); addrStream.write(ripemdHashedKey); byte[] versionedPayload = addrStream.toByteArray(); // 3. 计算校验码 byte[] checksum = BtcAddressUtils.checksum(versionedPayload); // 4. 得到 version + paylod + checksum 的组合 addrStream.write(checksum); byte[] binaryAddress = addrStream.toByteArray(); // 5. 执行Base58转换处理 return Base58Check.rawBytesToBase58(binaryAddress); } catch (IOException e) { e.printStackTrace(); } return null; } /** * 创建钱包 * @return */ public Wallet createWallet() { Wallet wallet = new Wallet(); Wallets wallets = this.loadFromDisk(); wallets.addWallet(wallet); this.saveToDisk(wallets); return wallet; } /** * 保存钱包数据 */ private void saveToDisk(Wallets wallets) { try { if (wallets == null) { System.out.println("保存钱包失败, wallets is null "); throw new Exception("ERROR: Fail to save wallet to file !"); } SecretKeySpec sks = new SecretKeySpec(CIPHER_TEXT, ALGORITHM); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, sks); SealedObject sealedObject = new SealedObject(wallets, cipher); // Wrap the output stream @Cleanup CipherOutputStream cos = new CipherOutputStream(new BufferedOutputStream(new FileOutputStream(WALLET_FILE)), cipher); @Cleanup ObjectOutputStream outputStream = new ObjectOutputStream(cos); outputStream.writeObject(sealedObject); } catch (Exception e) { System.out.println("保存钱包到磁盘失败"); e.printStackTrace(); throw new RuntimeException("Fail to save wallet to disk !"); } } /** * 加载钱包数据 */ private Wallets loadFromDisk() { try { SecretKeySpec sks = new SecretKeySpec(CIPHER_TEXT, ALGORITHM); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, sks); @Cleanup CipherInputStream cipherInputStream = new CipherInputStream(new BufferedInputStream(new FileInputStream(WALLET_FILE)), cipher); @Cleanup ObjectInputStream inputStream = new ObjectInputStream(cipherInputStream); SealedObject sealedObject = (SealedObject) inputStream.readObject(); return (Wallets) sealedObject.getObject(cipher); } catch (Exception e) { System.out.println("Fail to load wallet from disk ! "); e.printStackTrace(); throw new RuntimeException("Fail to load wallet from disk ! "); } } /** * 钱包存储对象 */ public static class Wallets implements Serializable { private static final long serialVersionUID = -2542070981569243131L; private Map<String, Wallet> walletMap = Maps.newHashMap(); /** * 添加钱包 * @param wallet */ private void addWallet(Wallet wallet) { try { this.walletMap.put(wallet.getAddress(), wallet); } catch (Exception e) { System.out.println("添加钱包失败"); e.printStackTrace(); } } /** * 获取所有的钱包地址 * @return */ public Set<String> getAddresses() { if (walletMap == null || walletMap.size() == 0) { System.out.println("当前没有钱包创建"); return null; } return walletMap.keySet(); } /** * 根据钱包地址获取钱包数据 * @param address 钱包地址 * @return */ Wallet getWallet(String address) { // 检查钱包地址是否合法 try { Base58Check.base58ToBytes(address); } catch (Exception e) { System.out.println("获取钱包失败,钱包地址为address=" + address); e.printStackTrace(); return null; } Wallet wallet = walletMap.get(address); if (wallet == null) { System.out.println("获取钱包失败,当前没有该地址的钱包 address=" + address); return null; } return wallet; } } }
package com.beike.util.singletonlogin; import java.util.UUID; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import com.beike.entity.user.User; import com.beike.service.user.UserService; import com.beike.userloginlog.model.UserLoginLog; import com.beike.util.Constant; import com.beike.util.MobilePurseSecurityUtils; import com.beike.util.PropertyUtil; import com.beike.util.WebUtils; import com.beike.util.cache.cachedriver.service.MemCacheService; import com.beike.util.cache.cachedriver.service.impl.MemCacheServiceImpl; import com.beike.wap.service.MUserService; /** * <p> * Title:单例登录相关操作 * </p> * <p> * Description: * </p> * <p> * Copyright: Copyright (c) 2011 * </p> * <p> * Company: Sinobo * </p> * * @date Jun 10, 2011 * @author ye.tian * @version 1.0 */ public class SingletonLoginUtils { public static final int RANDOM_STRING_NUMBER = 6; private static final String SINGLETON_COOKIE_KEY = "SINGLETON_COOKIE_KEY"; private static MemCacheService memCacheService = MemCacheServiceImpl .getInstance(); private static PropertyUtil propertyUtil = PropertyUtil .getInstance(Constant.PROPERTY_FILE_NAME); private static String domainName = propertyUtil.getProperty("domainname"); // 一个月cookie private static int validy = 60 * 60 * 24 * 30; /** * 获得当前登录用户 返回null 时需要到库里查询 * * @param request * @return */ public static User getMemcacheUser(HttpServletRequest request) { Long uid = SingletonLoginUtils.getLoginUserid(request); if (uid == null) return null; User user = (User) memCacheService.get(Constant.MEMCACHE_USER_LOGIN + uid); // if(user!=null){ // request.getSession().setAttribute(Constant.USER_LOGIN, user); // } return user; } public static User getMemcacheMobileUser(String uuid){ Long uid = SingletonLoginUtils.getMobileLoginUserId(uuid); if(uid == null) return null; User user = (User) memCacheService.get(Constant.MEMCACHE_USER_LOGIN+ uid); return user; } /** * 获得用户id * * @param request * @return */ public static Long getLoginUserid(HttpServletRequest request) { Long uid = null; try { String uuid = WebUtils .getCookieValue(SINGLETON_COOKIE_KEY, request); if (StringUtils.isBlank(uuid)) return null; String sigletonValue = (String) memCacheService.get(uuid); if (!StringUtils.isBlank(sigletonValue)) { String userid = sigletonValue.substring(0, sigletonValue.indexOf("|")); uid = Long.parseLong(userid); } } catch (Exception e) { e.printStackTrace(); return null; } return uid; } public static Long getMobileLoginUserId(String uuid){ Long uid = null; try{ String sigletonValue = (String) memCacheService.get(uuid); if (!StringUtils.isBlank(sigletonValue)) { String userid = sigletonValue.substring(0, sigletonValue.indexOf("|")); uid = Long.parseLong(userid); } }catch(Exception e){ e.printStackTrace(); return null; } return uid; } /** * 用户登录后使用 * memcache所存key为userKey,value为:uuid|当前毫秒数|6位随机数|前面字符串生成的签名(用userkey生成) * cookie所存userkey 30天过期 * * @param userKey * user表里的customerKey * @param response * HttpServletResponse * @param isForever * 是否永久登录 */ public static void addSingleton(User user, UserService userService, String userid, HttpServletResponse response, boolean isForever, HttpServletRequest request) { // 将userKey放到cookie里 // if(isForever){ // validy=60*60*24*3000; // } // 成功 记录到memcache 根据customerKey查询User // 一天一超时 int timeout = 24 * 60 * 60; if (user != null) { memCacheService.set(Constant.MEMCACHE_USER_LOGIN + userid, user, timeout); } else { user = (User) memCacheService.get(Constant.MEMCACHE_USER_LOGIN + userid); if (user == null) { user = userService.findById(Long.parseLong(userid)); memCacheService.set( Constant.MEMCACHE_USER_LOGIN + user.getId(), user, timeout); } else { memCacheService.set( Constant.MEMCACHE_USER_LOGIN + user.getId(), user, timeout); } } UUID uuid = UUID.randomUUID(); String uuidStr = uuid.toString(); // UUID Cookie cookie = WebUtils.cookie(SINGLETON_COOKIE_KEY, uuidStr, validy); response.addCookie(cookie); // CurrentTime long currentTime = System.currentTimeMillis(); // 组装Memcache 里存放数据 StringBuilder sb = new StringBuilder(); sb.append(userid); sb.append("|"); sb.append(currentTime); sb.append("|"); String hmac = MobilePurseSecurityUtils.hmacSign(sb.toString(), userid); sb.append(hmac); // 设置memcache memCacheService.set(uuidStr, sb.toString()); // request.getSession().getServletContext().setAttribute(uuidStr, // sb.toString()); } public static void addSingletonForMobile(User user, UserService userService,String uuid){ int timeout = 24 * 60 * 60; Long userid = user.getId(); if (user != null) { memCacheService.set(Constant.MEMCACHE_USER_LOGIN + userid, user, timeout); } else { user = (User) memCacheService.get(Constant.MEMCACHE_USER_LOGIN+userid); if (user == null) { user = userService.findById(userid); memCacheService.set(Constant.MEMCACHE_USER_LOGIN + userid, user,timeout); } else { memCacheService.set(Constant.MEMCACHE_USER_LOGIN + userid, user,timeout); } } long currentTime = System.currentTimeMillis(); // 组装Memcache 里存放数据 StringBuilder sb = new StringBuilder(); sb.append(userid); sb.append("|"); sb.append(currentTime); sb.append("|"); String hmac = MobilePurseSecurityUtils.hmacSign(sb.toString(),String.valueOf(userid)); sb.append(hmac); // 设置memcache memCacheService.set(uuid,sb.toString()); } /** * wap登录后使用 * memcache所存key为userKey,value为:uuid|当前毫秒数|6位随机数|前面字符串生成的签名(用userkey生成) * cookie所存userkey 30天过期 * * @param userKey * user表里的customerKey * @param response * HttpServletResponse * @param isForever * 是否永久登录 */ public static void addMSingleton(User user, MUserService mUserService, String userid, HttpServletResponse response, boolean isForever, HttpServletRequest request, int vTime) { // 将userKey放到cookie里 // 成功 记录到memcache 根据customerKey查询User // 一天一超时 if (user != null) { memCacheService.set(Constant.MEMCACHE_USER_LOGIN + userid, user, vTime); } else { user = (User) memCacheService.get(Constant.MEMCACHE_USER_LOGIN + userid); if (user == null) { user = mUserService.findById(Long.parseLong(userid)); memCacheService.set( Constant.MEMCACHE_USER_LOGIN + user.getId(), user, vTime); } else { memCacheService.set( Constant.MEMCACHE_USER_LOGIN + user.getId(), user, vTime); } } UUID uuid = UUID.randomUUID(); String uuidStr = uuid.toString(); // UUID WebUtils.setMCookieByKey(response, SINGLETON_COOKIE_KEY, uuidStr, vTime); // CurrentTime long currentTime = System.currentTimeMillis(); // 组装Memcache 里存放数据 StringBuilder sb = new StringBuilder(); sb.append(userid); sb.append("|"); sb.append(currentTime); sb.append("|"); String hmac = MobilePurseSecurityUtils.hmacSign(sb.toString(), userid); sb.append(hmac); // 设置memcache memCacheService.set(uuidStr, sb.toString()); } /** * 清除cookie、memcache * * @param userKey * @param response */ public static void removeSingleton(HttpServletResponse response, HttpServletRequest request) { String userKey = WebUtils.getCookieValue(SINGLETON_COOKIE_KEY, request); if (userKey != null) { memCacheService.remove(userKey); WebUtils.removeMCookieByKey(response, SINGLETON_COOKIE_KEY); // Cookie cookie = WebUtils.removeableCookie(SINGLETON_COOKIE_KEY, // ".qianpin.com"); // response.addCookie(cookie); } User user = getMemcacheUser(request); if (user != null) { memCacheService.remove(Constant.MEMCACHE_USER_LOGIN + user.getId()); } // if(userKey!=null){ // memCacheService.remove(userKey); // } } }
package vues; import controleur.Controleur; import controleur.exceptions.LoginDejaPritException; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.layout.FlowPane; import java.io.IOException; import java.net.URL; /** * Created by reda on 29/12/2016. */ public class InscriptionVue { public TextField getPseudo() { return pseudo; } public TextField getMotDepasse() { return motDePasse; } @FXML private TextField pseudo; @FXML private PasswordField motDePasse; @FXML private PasswordField motDePasseConfirm; @FXML private FlowPane racine; private Controleur monControleur; private Scene maScene; public static InscriptionVue creerInstance(Controleur c) { URL location = InscriptionVue.class.getResource("/vues/Inscription.fxml"); FXMLLoader fxmlLoader = new FXMLLoader(location); Parent root = null; try{ root = (Parent)fxmlLoader.load(); } catch(IOException e) { e.printStackTrace(); } InscriptionVue vue = fxmlLoader.getController(); vue.setMoncontroleur(c); return vue; } public void setMoncontroleur(Controleur moncontroleur){ this.monControleur = moncontroleur; } public Controleur getMonControleur(){ return monControleur; } public FlowPane getRacine(){ return this.racine; } public void setMaScene(Scene maScene) { this.maScene = maScene; } public Scene getMaScene(){ return this.maScene; } public void validerInscription(ActionEvent ActionEvent) { validerIns(); } public void validerInscr(KeyEvent k){ if(k.getCode() == KeyCode.ENTER){ validerIns(); } } public void validerIns(){ String motDePasse = this.motDePasse.getText(); String confirmationMotDePasse = this.motDePasseConfirm.getText(); String nom = this.pseudo.getText(); if (motDePasse.length() == 0 || confirmationMotDePasse.length() == 0 || nom.length() == 0) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Erreur"); alert.setHeaderText("Problème d'inscription"); alert.setContentText("Tous les champs sont obligatoires"); alert.showAndWait(); } else if(this.pseudo.getText().length()>=4) { if (this.motDePasse.getText().length() >= 4) { if (this.motDePasse.getText().equals(this.motDePasseConfirm.getText())) { try { this.getMonControleur().inscription(nom, motDePasse); } catch (LoginDejaPritException event) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Erreur"); alert.setHeaderText("Problème d'inscription"); alert.setContentText(event.getMessage()); alert.showAndWait(); } } else { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Erreur"); alert.setHeaderText("Problème d'inscription"); alert.setContentText("Les mots de passe sont diffèrents !"); alert.showAndWait(); } } else { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Erreur"); alert.setHeaderText("Problème de mot de passe"); alert.setContentText("Le mot de passe doit être composé d'au moins 4 caractères"); alert.showAndWait(); } } else{ Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Erreur"); alert.setHeaderText("Problème de mot de passe"); alert.setContentText("Le login doit être composé d'au moins 4 caractères"); alert.showAndWait(); } } public void cliqueRetour(ActionEvent ActionEvent) { this.getMonControleur().goToConnexion(); } public void pressR(KeyEvent k){ if(k.getCode() == KeyCode.ENTER){ this.getMonControleur().goToConnexion(); } } }
package tools; import javax.xml.stream.Location; /** * Created by oleh on 28.10.2014. */ public class UserInfo { String name; String surname; boolean online; }
package com.roshandemo.creational.abstractfactory; public interface IShape { /** * Draws the shape */ void draw(); }
/* * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.expression.spel.standard; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.UUID; import org.junit.jupiter.api.Test; import org.springframework.expression.Expression; import org.springframework.expression.spel.support.StandardEvaluationContext; import static org.assertj.core.api.Assertions.assertThat; /** * @author Mark Fisher */ public class PropertiesConversionSpelTests { private static final SpelExpressionParser parser = new SpelExpressionParser(); @Test public void props() { Properties props = new Properties(); props.setProperty("x", "1"); props.setProperty("y", "2"); props.setProperty("z", "3"); Expression expression = parser.parseExpression("foo(#props)"); StandardEvaluationContext context = new StandardEvaluationContext(); context.setVariable("props", props); String result = expression.getValue(context, new TestBean(), String.class); assertThat(result).isEqualTo("123"); } @Test public void mapWithAllStringValues() { Map<String, Object> map = new HashMap<>(); map.put("x", "1"); map.put("y", "2"); map.put("z", "3"); Expression expression = parser.parseExpression("foo(#props)"); StandardEvaluationContext context = new StandardEvaluationContext(); context.setVariable("props", map); String result = expression.getValue(context, new TestBean(), String.class); assertThat(result).isEqualTo("123"); } @Test public void mapWithNonStringValue() { Map<String, Object> map = new HashMap<>(); map.put("x", "1"); map.put("y", 2); map.put("z", "3"); map.put("a", new UUID(1, 1)); Expression expression = parser.parseExpression("foo(#props)"); StandardEvaluationContext context = new StandardEvaluationContext(); context.setVariable("props", map); String result = expression.getValue(context, new TestBean(), String.class); assertThat(result).isEqualTo("1null3"); } @Test public void customMapWithNonStringValue() { CustomMap map = new CustomMap(); map.put("x", "1"); map.put("y", 2); map.put("z", "3"); Expression expression = parser.parseExpression("foo(#props)"); StandardEvaluationContext context = new StandardEvaluationContext(); context.setVariable("props", map); String result = expression.getValue(context, new TestBean(), String.class); assertThat(result).isEqualTo("1null3"); } private static class TestBean { @SuppressWarnings("unused") public String foo(Properties props) { return props.getProperty("x") + props.getProperty("y") + props.getProperty("z"); } } @SuppressWarnings("serial") private static class CustomMap extends HashMap<String, Object> { } }
package com.ggw.vem; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.ListFragment; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.util.Log; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.ContextMenu.ContextMenuInfo; import android.view.View.OnCreateContextMenuListener; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; public class BankTitlesFragment extends ListFragment { private BankActivity myActivity = null; int mCurCheckPosition = 0; boolean isSuc; private String add = "绑定新的银行卡"; List<String> cardID = new ArrayList(); List<String> bankType = new ArrayList(); int length = 0; private static final int ITEM0 = 0; private static final int ITEM1 = 1; private String userID; private String selectedCard; private String menuSelectedCard; private String defaultCard = "none"; ArrayList<Map<String, Object>> mData = new ArrayList<Map<String, Object>>();; Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); Bundle data = msg.getData(); int val = data.getInt("result"); switch (val) { case 1: Toast.makeText(getActivity().getApplicationContext(), "网络异常", Toast.LENGTH_SHORT).show(); break; case 2: int i = data.getInt("i"); length = i; int j = 0; cardID.clear(); bankType.clear(); mData.clear(); defaultCard = data.getString("defCardID"); for (j = 0; j < i; j++) { cardID.add(data.getString("cardID" + j)); bankType.add(data.getString("bankType" + j)); } cardID.add(add); bankType.add(null); for (int i1 = 0; i1 <= length; i1++) { Map<String, Object> item = new HashMap<String, Object>(); if(cardID.get(i1).equals(add)){ item.put("title", cardID.get(i1)); item.put("text", bankType.get(i1)); item.put("ItemImage", null); } else{ item.put("title", "卡号:"+cardID.get(i1)); int bank =i=Integer.parseInt(bankType.get(i1)); switch(bank){ case 1: item.put("text","中国工商银行" ); } if(cardID.get(i1).equals(defaultCard)){ item.put("ItemImage", R.drawable.love); } else{ item.put("ItemImage", null); } } mData.add(item); } setListAdapter(new SimpleAdapter(getActivity() .getApplicationContext(), mData, R.layout.list_bank, new String[] { "title", "text", "ItemImage"}, new int[] {R.id.cardID,R.id.bankType,R.id.ItemImage })); ListView lv = getListView(); lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE); lv.setSelection(mCurCheckPosition); lv.setOnCreateContextMenuListener(new OnCreateContextMenuListener() { @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { AdapterView.AdapterContextMenuInfo mi; mi = (AdapterView.AdapterContextMenuInfo)menuInfo; int selected = Integer.parseInt(String.valueOf(mi.id)); menuSelectedCard = cardID.get(selected); if(!menuSelectedCard.equals(add)) { menu.setHeaderTitle("设置"); menu.add(0, ITEM0, 0, "设置为默认银行卡"); menu.add(0, ITEM1, 0, "删除银行卡"); } } }); break; case 3: Toast.makeText(getActivity().getApplicationContext(), "设置默认支付卡号成功", Toast.LENGTH_SHORT).show(); break; case 4: Toast.makeText(getActivity().getApplicationContext(), "设置默认支付卡号不成功", Toast.LENGTH_SHORT).show(); break; case 5: Toast.makeText(getActivity().getApplicationContext(), "银行卡刪除成功", Toast.LENGTH_SHORT).show(); break; case 6: Toast.makeText(getActivity().getApplicationContext(), "银行卡刪除不成功", Toast.LENGTH_SHORT).show(); break; } } }; public void deleteCard(int selected){ selectedCard = cardID.get(selected); new Thread() { public void run() { try { String url = "http://222.205.47.11/server/index.php/server/deleteCard/" + userID+"/"+selectedCard; HttpJsonGet requestSent = new HttpJsonGet(url); JSONObject jsonTemp = requestSent.getJsonObject(); if (jsonTemp == null) { Message msg = new Message(); Bundle data = new Bundle(); data.putInt("result", 1); msg.setData(data); handler.sendMessage(msg); } else { isSuc = jsonTemp.getBoolean("result"); Log.v("TestActivity", "result:" + isSuc); if (isSuc) { Message msg = new Message(); Bundle data = new Bundle(); data.putInt("result", 5); msg.setData(data); handler.sendMessage(msg); } else { Message msg = new Message(); Bundle data = new Bundle(); data.putInt("result", 6); msg.setData(data); handler.sendMessage(msg); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO: handle exception } } }.start(); } public void setDefaultCard(int selected){ selectedCard = cardID.get(selected); new Thread() { public void run() { try { String url = "http://222.205.47.11/server/index.php/server/setDefaultCard/" + userID+"/"+selectedCard; HttpJsonGet requestSent = new HttpJsonGet(url); JSONObject jsonTemp = requestSent.getJsonObject(); if (jsonTemp == null) { Message msg = new Message(); Bundle data = new Bundle(); data.putInt("result", 1); msg.setData(data); handler.sendMessage(msg); } else { isSuc = jsonTemp.getBoolean("result"); Log.v("TestActivity", "result:" + isSuc); if (isSuc) { Message msg = new Message(); Bundle data = new Bundle(); data.putInt("result", 3); msg.setData(data); handler.sendMessage(msg); } else { Message msg = new Message(); Bundle data = new Bundle(); data.putInt("result", 4); msg.setData(data); handler.sendMessage(msg); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO: handle exception } } }.start(); } public void showCard(){ new Thread() { public void run() { try { String defCard = null; String url1 = "http://222.205.47.11/server/index.php/server/viewinfo/" + userID; HttpJsonGet requestSent1 = new HttpJsonGet(url1); JSONObject jsonTemp1 = requestSent1.getJsonObject(); JSONObject jsonResult1 ; jsonResult1 = jsonTemp1.getJSONObject("result"); String url2 = "http://222.205.47.11/server/index.php/server/getCards/"+userID; List<String> cardIDTemp = new ArrayList(); List<String> bankTypeTemp = new ArrayList(); HttpJsonGet requestSent2 = new HttpJsonGet(url2); JSONArray jsonResult2; JSONObject jsonTemp2 = requestSent2.getJsonObject(); if (jsonTemp1 == null || jsonTemp2 == null) { Message msg = new Message(); Bundle data = new Bundle(); data.putInt("result", 1); msg.setData(data); handler.sendMessage(msg); // Toast.makeText(Login.this, "网络异常", // Toast.LENGTH_SHORT).show(); } else { Message msg = new Message(); Bundle data = new Bundle(); data.putInt("result", 2); defCard = jsonResult1.getString("DefaultCard"); data.putString("defCardID", defCard); jsonResult2 = jsonTemp2.getJSONArray("result"); int i; for (i = 0; i < jsonResult2.length(); i++) { JSONObject jsonObj = ((JSONObject) jsonResult2.opt(i)); cardIDTemp.add(jsonObj.getString("CardID")); bankTypeTemp.add(jsonObj.getString("BankType")); } data.putInt("i", i); for (int j = 0; j < i; j++) { data.putString("cardID" + j, cardIDTemp.get(j)); data.putString("bankType" + j, bankTypeTemp.get(j)); } msg.setData(data); handler.sendMessage(msg); // inforeditor.putString("inforname",inforRealName); // inforeditor.commit(); } } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }.start(); } //菜单单击响应 public boolean onContextItemSelected(MenuItem item){ //获取当前被选择的菜单项的信息 AdapterView.AdapterContextMenuInfo menuInfo; menuInfo = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo(); int selected = Integer.parseInt(String.valueOf(menuInfo.id)); switch(item.getItemId()){ case ITEM0: //设置为默认银行卡 setDefaultCard(selected); showCard(); break; case ITEM1: //删除银行卡 //selectedCard = cardID.get(featureId); deleteCard(selected); showCard(); break; } return true; } @Override public void onInflate(AttributeSet attrs, Bundle icicle) { Log.v(BankActivity.TAG, "in TitlesFragment onInflate. AttributeSet contains:"); for (int i = 0; i < attrs.getAttributeCount(); i++) { Log.v(BankActivity.TAG, " " + attrs.getAttributeName(i) + " = " + attrs.getAttributeValue(i)); } super.onInflate(attrs, icicle); /* * See defect 14796. onInflate() is getting called after onCreateView() * when the orientation changes from landscape to portrait. If we try to * set arguments, we get an IllegalStateException. Bundle bundle = * this.getArguments(); if(bundle == null) bundle = new Bundle(); * bundle.putString("Dave", "Dave"); this.setArguments(bundle); */ } @Override public void onAttach(Activity myActivity) { Log.v(BankActivity.TAG, "in TitlesFragment onAttach; activity is: " + myActivity); super.onAttach(myActivity); this.myActivity = (BankActivity) myActivity; userID = this.myActivity.getUserid(); } @Override public void onCreate(Bundle icicle) { Log.v(BankActivity.TAG, "in TitlesFragment onCreate. Bundle contains:"); if (icicle != null) { for (String key : icicle.keySet()) { Log.v(BankActivity.TAG, " " + key); } } else { Log.v(BankActivity.TAG, " myBundle is null"); } super.onCreate(icicle); if (icicle != null) { // Restore last state for checked position. mCurCheckPosition = icicle.getInt("curChoice", 0); } } @Override public View onCreateView(LayoutInflater myInflater, ViewGroup container, Bundle icicle) { Log.v(BankActivity.TAG, "in TitlesFragment onCreateView. container is " + container); return super.onCreateView(myInflater, container, icicle); } @Override public void onActivityCreated(Bundle icicle) { Log.v(BankActivity.TAG, "in TitlesFragment onActivityCreated. icicle contains:"); if (icicle != null) { for (String key : icicle.keySet()) { Log.v(BankActivity.TAG, " " + key); } } else { Log.v(BankActivity.TAG, " icicle is null"); } super.onActivityCreated(icicle); // Populate list with our static array of titles. showCard(); // myActivity.showDetails(mCurCheckPosition); } @Override public void onStart() { Log.v(BankActivity.TAG, "in TitlesFragment onStart"); super.onStart(); } @Override public void onResume() { Log.v(BankActivity.TAG, "in TitlesFragment onResume"); super.onResume(); } @Override public void onPause() { Log.v(BankActivity.TAG, "in TitlesFragment onPause"); super.onPause(); } @Override public void onSaveInstanceState(Bundle icicle) { Log.v(BankActivity.TAG, "in TitlesFragment onSaveInstanceState"); super.onSaveInstanceState(icicle); icicle.putInt("curChoice", mCurCheckPosition); } @Override public void onListItemClick(ListView l, View v, int pos, long id) { Log.v(BankActivity.TAG, "in TitlesFragment onListItemClick. pos = " + pos); if (cardID.get(pos).equals(add)) { myActivity.showDetails(cardID.get(pos)); mCurCheckPosition = pos; } } @Override public void onStop() { Log.v(BankActivity.TAG, "in TitlesFragment onStop"); super.onStop(); } @Override public void onDestroyView() { Log.v(BankActivity.TAG, "in TitlesFragment onDestroyView"); super.onDestroyView(); } @Override public void onDestroy() { Log.v(BankActivity.TAG, "in TitlesFragment onDestroy"); super.onDestroy(); } @Override public void onDetach() { Log.v(BankActivity.TAG, "in TitlesFragment onDetach"); super.onDetach(); myActivity = null; } }
package com.jpj; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * @Author:haoly * @Description: * @Date:2018/1/3上午10:15 **/ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/spring-context.xml") public abstract class BaseTest { }
package com.bwie.juan_mao.jingdong_kanglijuan.view.shop; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.webkit.WebResourceRequest; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import com.bwie.juan_mao.jingdong_kanglijuan.HomeActivity; import com.bwie.juan_mao.jingdong_kanglijuan.R; import com.bwie.juan_mao.jingdong_kanglijuan.base.BaseActivity; import com.bwie.juan_mao.jingdong_kanglijuan.bean.CategoryBean; import com.bwie.juan_mao.jingdong_kanglijuan.bean.ProductBean; import com.bwie.juan_mao.jingdong_kanglijuan.bean.ProductCategoryBean; import com.bwie.juan_mao.jingdong_kanglijuan.bean.ProductDetailsBean; import com.bwie.juan_mao.jingdong_kanglijuan.bean.RegisterBean; import com.bwie.juan_mao.jingdong_kanglijuan.bean.ShopListBean; import com.bwie.juan_mao.jingdong_kanglijuan.bean.ShopperBean; import com.bwie.juan_mao.jingdong_kanglijuan.presenter.ClassifyPresenter; import com.bwie.juan_mao.jingdong_kanglijuan.utils.Https2http; import com.bwie.juan_mao.jingdong_kanglijuan.view.IClassifyView; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class ShopWebActivity extends BaseActivity<ClassifyPresenter> implements IClassifyView { @BindView(R.id.wv_shop_web) WebView wvShopWeb; @BindView(R.id.img_jump_cart) ImageView imgJumpCart; @BindView(R.id.btn_add_cart) Button btnAddCart; @BindView(R.id.btn_immediate_purchase) Button btnImmediatePurchase; private int pid; private boolean notEmpty = false; private List<ShopperBean<List<ProductBean>>> list; @Override protected void initData() { Intent intent = getIntent(); pid = intent.getIntExtra("pid", 0); presenter.getProductDetail(pid); } @Override protected ClassifyPresenter providePresenter() { return new ClassifyPresenter(); } @Override protected int provideLayoutId() { return R.layout.activity_shop_web; } @Override public Context getContext() { return this; } /** * 用不到 * * @param data */ @Override public void getCategory(CategoryBean data) { } /** * 用不到 * * @param data */ @Override public void getProductCategory(ProductCategoryBean data) { } /** * 用不到 * * @param data */ @Override public void getShopList(ShopListBean data) { } @Override public void addCart(RegisterBean data) { // 加入购物车成功 Toast.makeText(this, "加入购物车成功", Toast.LENGTH_SHORT).show(); startActivity(new Intent(this, CartActivity.class)); } @Override public void getProductDetail(ProductDetailsBean data) { notEmpty = true; ProductDetailsBean.DataBean productDetails = data.getData(); wvShopWeb.loadUrl(Https2http.replace(productDetails.getDetailUrl())); wvShopWeb.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { return super.shouldOverrideUrlLoading(view, request); } }); // 自己创建一个shopperBean ProductBean productBean = new ProductBean(productDetails.getImages(), 1, productDetails.getPrice(), productDetails.getTitle()); List<ProductBean> productList = new ArrayList<>(); productList.add(productBean); ShopperBean<List<ProductBean>> listShopperBean = new ShopperBean<>(); listShopperBean.setList(productList); listShopperBean.setSellerName(data.getSeller().getName()); list = new ArrayList<>(); list.add(listShopperBean); } @Override public void onClassifyFailed(Throwable t) { notEmpty = false; Toast.makeText(this, t.getMessage(), Toast.LENGTH_SHORT).show(); } @OnClick({R.id.img_jump_cart, R.id.btn_add_cart, R.id.btn_immediate_purchase}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.img_jump_cart: startActivity(new Intent(this, CartActivity.class)); break; case R.id.btn_add_cart: presenter.addCart(pid); break; case R.id.btn_immediate_purchase: if (notEmpty) { Intent intent = new Intent(this, PlaceOrderActivity.class); intent.putExtra("list", (Serializable) list); startActivity(intent); } else { Toast.makeText(this, "该商品暂时无法购买", Toast.LENGTH_SHORT).show(); } break; } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ import lab12.Hashtable; import org.junit.Test; import static org.junit.Assert.*; /** * * @author ayush488 */ public class TestHashTable { public TestHashTable() { } @Test public void testadd() { Hashtable ht=new Hashtable(); ht.add("Ayush",25); ht.add("Kushu",23); int n=ht.getNumELements(); assertEquals(2,n); } @Test public void testremove() { Hashtable ht=new Hashtable(); ht.add("Ayush",25); ht.add("Kushu",23); ht.remove("Ayush"); int n=ht.getNumELements(); assertEquals(1,n); ht.remove("Kush"); n=ht.getNumELements(); assertEquals(1,n); } }
package board.grid; import board.blockingobject.Wall; import board.square.Square; import items.*; import path.PathGenerator; import util.Coordinate; import util.Direction; import util.WallDirection; import java.util.ArrayList; import java.util.List; import java.util.Random; public class NormalGridBuilder extends GridBuilder { private final static Random generator = new Random(); private final static double MAX_WALL_COVERAGE = 0.20; private final static double MAX_GRENADE_COVERAGE = 0.02; private final static double MAX_IDENTITYDISC_COVERAGE = 0.02; private final static double MAX_TELEPORTER_COVERAGE = 0.03; private final static double MAX_FORCEFIELDGENERATOR_COVERAGE = 0.07; private final static double MAX_RELATIVE_WALL_LENGTH = 0.50; private final static double ROUND_ERROR_DELTA = 0.000000001; /** * Calculate amount of walls to be generated and generate. * */ @Override public void buildWalls() { double tmp = MAX_WALL_COVERAGE * grid.getNumberOfSquares(); if (Math.abs(tmp - Math.round(tmp)) < ROUND_ERROR_DELTA) tmp = Math.round(tmp); int maxWallAmount = (int) Math.ceil(tmp); int wallAmount = generator.nextInt(maxWallAmount - 1) + 2; generateWalls(wallAmount); } /** * Generate random walls in the grid with following constraints: - Amount of * squares with a wall equals given amount. - No wall is longer than * MAX_RELATIVE_WALL_LENGTH times the gridlength. - A wall consists of * minimal 2 squares. * * @param amount * Maximum amount of squares in the grid that can have a wall. * @throws IllegalArgumentException * Given amount is below zero. */ private void generateWalls(int amount) throws IllegalArgumentException { if (amount < 0) throw new IllegalArgumentException(); if (amount == 0) return; int maxLength = 0; int length = 0; WallDirection direction = null; Coordinate origin = null; do { direction = WallDirection.values()[generator.nextInt(2)]; origin = new Coordinate(generator.nextInt(grid.getWidth() + 1), generator.nextInt(grid.getHeight() + 1)); switch (direction) { case HORIZONTAL: maxLength = (int) Math.ceil(MAX_RELATIVE_WALL_LENGTH * grid.getWidth()); break; case VERTICAL: maxLength = (int) Math.ceil(MAX_RELATIVE_WALL_LENGTH * grid.getHeight()); break; } do { length = generator.nextInt(Math.min(maxLength - 1, amount - 1)) + 2; } while (length == amount - 1); } while (!isPossibleNewWall(new Wall(length, direction, grid.getSquareFrom(origin)))); addWall(new Wall(length, direction, grid.getSquareFrom(origin))); generateWalls(amount - length); } /** * Adds the wall to the grid on the coordinates in the wall * * @param wall */ protected void addWall(Wall wall) { Square position = wall.getRootPosition(); position.setBlockingObject(wall); for (int i = 1; i < wall.getLength(); i++) { switch (wall.getDirection()) { case HORIZONTAL: position = position.getNeighbour(Direction.EAST); break; case VERTICAL: position = position.getNeighbour(Direction.SOUTH); break; } position.setBlockingObject(wall); } } /** * Checks if given wall is possible in the grid. * * @param wall * @return False if - any square of given wall is part of another wall. - * any square of given wall touches or intersects another wall. - * any square of given wall is on startposition of player. Otherwise * true * * @throws NullPointerException * The given wall is null. */ private boolean isPossibleNewWall(Wall wall) throws NullPointerException { if (wall == null) throw new NullPointerException(); Square position = wall.getRootPosition(); if (position.isOutOfBound() || position.hasBlockingObject()) return false; for (Coordinate coord : startPositions) if (grid.getSquareFrom(coord).equals(position)) return false; for (int i = 1; i < wall.getLength(); i++) { switch (wall.getDirection()) { case HORIZONTAL: position = position.getNeighbour(Direction.EAST); break; case VERTICAL: position = position.getNeighbour(Direction.SOUTH); break; } if (position.isOutOfBound() || position.hasBlockingObject()) return false; for (Coordinate coord : startPositions) if (grid.getSquareFrom(coord).equals(position)) return false; } if (this.hasTouchingWalls(wall)) return false; return true; } /** * Checks if grid has touching walls after addition of given wall. * * @param wall * Wall which is added to grid for checking the touching of * walls. * @return True if - Any square of given wall touches another wall otherwise * False. * @throws NullPointerException * The given wall is null. */ private boolean hasTouchingWalls(Wall wall) throws NullPointerException { if (wall == null) throw new NullPointerException(); if (isFirstAndLastTouching(wall)) return true; for (int i = 0; i < wall.getLength(); i++) { if (isTouchingSquare(i, wall)) return true; } return false; } /** * Checks if first and last square of wall touches other wall. * * @param wall * Wall of which the first and last square are checked. * @return True if first square or last square of given wall touches any * other wall. Note: above/below (horizontal wall) or left/right * (vertical wall) directions are not checked. Otherwise false. * @throws NullPointerException * The given wall is null. */ private boolean isFirstAndLastTouching(Wall wall) throws NullPointerException { if (wall == null) throw new NullPointerException(); int squareIndex = 0; Coordinate wallCo = null; for (int x = 0; x < grid.getWidth(); x++) { for (int y = 0; y < grid.getHeight(); y++) { if (grid.getSquareFrom(new Coordinate(x, y)).equals( wall.getRootPosition())) { wallCo = new Coordinate(x, y); break; } } } for (int i = 0; i < 2; i++) { int add = 1; if (squareIndex == 0) add = -1; for (int j = -1; j <= 1; j++) { Coordinate tmp = null; switch (wall.getDirection()) { case HORIZONTAL: tmp = new Coordinate(wallCo.getX() + squareIndex + add, wallCo.getY() + j); break; case VERTICAL: tmp = new Coordinate(wallCo.getX() + j, wallCo.getY() + squareIndex + add); break; } if (!grid.getSquareFrom(tmp).isOutOfBound() && grid.getSquareFrom(tmp).hasBlockingObject()) return true; } squareIndex = wall.getLength() - 1; } return false; } /** * Checks if square (with given squareIndex in wall) touches another wall. * * @param squareIndex * The index of the to-be-checked square in the wall. * @param wall * The wall to which the square belongs. * @return True if square touches other wall - above or under (Horizontal * wall) - left or right (Vertical wall) Otherwise false. */ private boolean isTouchingSquare(int squareIndex, Wall wall) { Square s1 = null; Square s2 = null; Square position = wall.getRootPosition(); if (position == null || position.isOutOfBound()) System.out.println("Error"); switch (wall.getDirection()) { case HORIZONTAL: while (squareIndex > 0) { position = position.getNeighbour(Direction.EAST); squareIndex--; } s1 = position.getNeighbour(Direction.NORTH); s2 = position.getNeighbour(Direction.SOUTH); break; case VERTICAL: while (squareIndex > 0) { position = position.getNeighbour(Direction.SOUTH); squareIndex--; } s1 = position.getNeighbour(Direction.EAST); s2 = position.getNeighbour(Direction.WEST); break; } if (!s1.isOutOfBound() && s1.hasBlockingObject()) return true; if (!s2.isOutOfBound() && s2.hasBlockingObject()) return true; return false; } @Override public void buildTeleporters() { generateTeleporters(getAmountFrom(MAX_TELEPORTER_COVERAGE)); } @Override public void buildLightGrenades() { generateLightGrenades(getAmountFrom(MAX_GRENADE_COVERAGE)); } @Override public void buildIdentityDisks() { generateIdentityDisks(getAmountFrom(MAX_IDENTITYDISC_COVERAGE)); } @Override public void buildChargedIdentityDisks() { generateChargedIdentityDisks(); } @Override public void buildForceFieldGenerator() { generateForceFieldGenerator(getAmountFrom(MAX_FORCEFIELDGENERATOR_COVERAGE)); } /** * Generates given amount of items in the grid. * * @param amount * Amount of items to be generated into the grid. * @throws IllegalArgumentException * Given amount is 0 or below. */ private void generateLightGrenades(int amount) throws IllegalArgumentException { Square temp; if (amount < 0) throw new IllegalArgumentException(); for (Square s : getRandomNonBlockingSquares(amount - startPositions.size())) { s.addItem(new LightGrenade()); } for (Coordinate co : startPositions) { do { // a 5x5 length arround the staring position is equal to 2 // squares distance from the middle square temp = getRandomNonBlockingSquaresIn(2, co); } while (temp.hasItem(LightGrenade.class)); temp.addItem(new LightGrenade()); } } /** * Method that generates a certain amount of identity discs on the grid * * @param amount */ private void generateIdentityDisks(int amount) { Square temp; for (Square s : getRandomNonBlockingSquares(amount - startPositions.size())) { s.addItem(new IdentityDisc()); } for (Coordinate co : startPositions) { do { // a 7x7 length arround the staring position is equal to 3 // squares distance from the middle square temp = getRandomNonBlockingSquaresIn(3, co); } while (temp.hasItem(IdentityDisc.class)); temp.addItem(new IdentityDisc()); } } /** * Method that generates a charged IdentityDisk */ private void generateChargedIdentityDisks() { PathGenerator pathGenerator = new PathGenerator(); List<Square> possibleSquares = new ArrayList<Square>(); List<Square> startSquares = new ArrayList<Square>(); for(Coordinate co : startPositions){ startSquares.add(grid.getSquareFrom(co)); } AllSquares: for (Square s : grid.getSquares()) { if (!s.hasBlockingObject() && !s.isOutOfBound()) { int pathLength = pathGenerator.findShortestPath(grid, startSquares.get(0), s).getPathList().size(); for(Square startSq: startSquares){ if (Math.abs(pathLength - pathGenerator.findShortestPath(grid, startSq, s) .getPathList().size()) > 2) continue AllSquares; } possibleSquares.add(s); } } if (possibleSquares.size() > 0) possibleSquares.get(generator.nextInt(possibleSquares.size())) .addItem(new ChargedIdentityDisc()); } /** * Method that generates a certain amount of forcefieldgenerators * * @param amount */ private void generateForceFieldGenerator(int amount) { if (amount < 0) throw new IllegalArgumentException(); for (Square s : getRandomNonBlockingSquares(amount)) { new ForceFieldGenerator(s); } } /** * Method that generates a certain amount of teleporters * * @param amount */ private void generateTeleporters(int amount) { if(amount < 2) return; List<Teleporter> teleporters = new ArrayList<Teleporter>(); Teleporter t; List<Square> rand = getRandomNonBlockingSquares(amount); if(rand.size()<2) return; for (Square s : rand) { t = new Teleporter(s); s.addItem(t); teleporters.add(t); } Teleporter destination; for (Teleporter teleporter : teleporters) { do { destination = teleporters.get(generator.nextInt(teleporters .size())); } while (destination.equals(teleporter)); teleporter.setDestination(destination); } } /** * Method that gets a list from all non blocking squares * * @param amount * The amount of non blocking squares * @return List<Square> */ private List<Square> getRandomNonBlockingSquares(int amount) { List<Square> result = new ArrayList<Square>(); if (amount <= 0) { return result; } List<Square> startingSquares = new ArrayList<Square>(); for(Coordinate co : startPositions){ startingSquares.add(grid.getSquareFrom(co)); } List<Square> possibleSquares = new ArrayList<Square>(); for(Square s: grid.getSquares()){ if(!startingSquares.contains(s) && ! s.hasBlockingObject() && !s.isOutOfBound()) possibleSquares.add(s); } if(amount >= possibleSquares.size()) return possibleSquares; int n; for (int i = 0; i < amount; i++) { n = generator.nextInt(possibleSquares.size()); result.add(possibleSquares.remove(n)); } return result; } /** * Method that getes all random non blocking squares in a certain range from * a location * * @param range * @param middlePosition * @return */ private Square getRandomNonBlockingSquaresIn(int range, Coordinate middlePosition) { Coordinate position; int i, j; do { i = generator.nextInt(range * 2 + 1) - range; j = generator.nextInt(range * 2 + 1) - range; position = new Coordinate(middlePosition.getX() + i, middlePosition.getY() + j); } while (grid.getSquareFrom(position).hasBlockingObject() || startPositions.contains(position) || grid.getSquareFrom(position).isOutOfBound()); return grid.getSquareFrom(position); } /** * Method that gets the amount from the given coverage. * * @param coverage * @return The amount of items that need to be made */ private int getAmountFrom(double coverage) { double tmp = coverage * grid.getNumberOfSquares(); if (Math.abs(tmp - Math.round(tmp)) < ROUND_ERROR_DELTA) tmp = Math.round(tmp); return (int) Math.floor(tmp); } }
package net.maizegenetics.trait; import cern.colt.matrix.DoubleFactory2D; import cern.colt.matrix.DoubleMatrix2D; import net.maizegenetics.taxa.TaxaList; import net.maizegenetics.taxa.TaxaListBuilder; import net.maizegenetics.util.Utils; import java.io.BufferedReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.TreeSet; import java.util.regex.Pattern; public class ReadPhenotypeUtils { public final static String missing = "\\?|nan|-999"; private static Pattern missingPattern = Pattern.compile("\\?|nan|-999", Pattern.CASE_INSENSITIVE); //to prevent instantiation of this utility class private ReadPhenotypeUtils(){} /** * @param original the original class or discrete data * @param tonumber a double array, the same length as the original data, which will hold the class indices * @param name the trait name * @param type the trait type * @return the new Trait */ public static Trait makeCharacterTrait(String[] original, double[] tonumber, String name, String type) { TreeSet<String> dataset = new TreeSet<String>(); for (String str : original) { if (!missingPattern.matcher(str).matches() && !str.contains("?")) dataset.add(str); } String[] levelNames = new String[dataset.size()]; dataset.toArray(levelNames); int n = original.length; for (int i = 0; i < n; i++) { tonumber[i] = Arrays.binarySearch(levelNames, original[i]); if (tonumber[i] < -0.1) tonumber[i] = Double.NaN; } Trait trait = new Trait(name, true, type); trait.setLevelLabels(levelNames); return trait; } public static double[] doubleFromCharacterTrait(Trait trait, String[] textdata) { TreeSet<String> dataset = new TreeSet<String>(); int n = textdata.length; double[] dbldata = new double[n]; for (String str : textdata) { if (!missingPattern.matcher(str).matches() && !str.contains("?")) dataset.add(str); } String[] levelNames = new String[dataset.size()]; dataset.toArray(levelNames); for (int i = 0; i < n; i++) { dbldata[i] = Arrays.binarySearch(levelNames, textdata[i]); if (dbldata[i] < -0.1) dbldata[i] = Double.NaN; } trait.setProperty(Trait.PROP_LEVEL_LABELS, levelNames); return dbldata; } /** * @param inputFile the input file in TASSEL v2 polymorphism format * @return a Phenotype * @throws IOException */ public static Phenotype readPolymorphismAlignment(String inputFile) throws IOException { //BufferedReader br = new BufferedReader(new FileReader(inputFile)); BufferedReader br = Utils.getBufferedReader(inputFile); String sep = "[\\s]+"; String[] parsedline = br.readLine().split("[:\\s]+"); int taxaNumber = Integer.parseInt(parsedline[0]); int locusNumber = Integer.parseInt(parsedline[1]); String[] taxaNames = new String[taxaNumber]; String[] locusNames = new String[locusNumber]; LinkedList<Trait> traitList = new LinkedList<Trait>(); DoubleMatrix2D genotypes = DoubleFactory2D.dense.make(taxaNumber, locusNumber); parsedline = br.readLine().split(sep); int firstLocus = 0; int n = parsedline.length; if (n != locusNumber) { if (n == locusNumber + 1) firstLocus = 1; else throw new IllegalArgumentException("Number of loci in header not equal to number of locus names in " + inputFile + ". Data not imported."); } for (int i = 0; i < locusNumber; i++) { locusNames[i] = parsedline[i + firstLocus]; } String[][] locusText = new String[locusNumber][taxaNumber]; for (int i = 0; i < taxaNumber; i++) { parsedline = br.readLine().split(sep); taxaNames[i] = parsedline[0].toUpperCase(); for (int j = 0; j < locusNumber; j++) { locusText[j][i] = parsedline[j + 1]; } } for (int i = 0; i < locusNumber; i++) { double[] dblval = new double[taxaNumber]; traitList.add(makeCharacterTrait(locusText[i], dblval, locusNames[i], Trait.TYPE_MARKER)); genotypes.viewColumn(i).assign(dblval); } TaxaList tL=new TaxaListBuilder().addAll(taxaNames).build(); return new SimplePhenotype(tL, traitList, genotypes); } /** * @param inputFile the input file in TASSEL v2 numerical format * @return * @throws IOException */ public static Phenotype readNumericalAlignment(String inputFile) throws IOException { //BufferedReader br = new BufferedReader(new FileReader(inputFile)); BufferedReader br = Utils.getBufferedReader(inputFile); String sep = "\\s+"; String[] parsedline = br.readLine().trim().split(sep); if (parsedline.length != 3) throw new IllegalArgumentException("Improper header in " + inputFile + ". Data not imported."); int taxaNumber = Integer.parseInt(parsedline[0]); int traitNumber = Integer.parseInt(parsedline[1]); int headerNumber = Integer.parseInt(parsedline[2]); if (headerNumber < 1 || headerNumber > 2) throw new IllegalArgumentException("Numerical format only allows 1 or 2 headers in " + inputFile + ". Data not imported."); parsedline = br.readLine().split(sep); ArrayList<Trait> traitList = new ArrayList<Trait>(); if (parsedline.length != traitNumber) throw new IllegalArgumentException("Incorrect number of trait names in " + inputFile + ". Data not imported."); for (int i = 0; i < traitNumber; i++) { Trait trait = new Trait(parsedline[i], false, Trait.TYPE_DATA); traitList.add(trait); } if (headerNumber > 1) { parsedline = br.readLine().split(sep); if (parsedline.length != traitNumber) throw new IllegalArgumentException("Incorrect number of environment names in " + inputFile + ". Data not imported."); for (int i = 0; i < traitNumber; i++) traitList.get(i).addFactor(Trait.FACTOR_ENV, parsedline[i]); } DoubleMatrix2D phenotypes = DoubleFactory2D.dense.make(taxaNumber, traitNumber); String[] taxaNames = new String[taxaNumber]; for (int i = 0; i < taxaNumber; i++) { parsedline = br.readLine().split(sep); // taxaNames[i] = parsedline[0].toUpperCase(); taxaNames[i] = parsedline[0]; for (int j = 0; j < traitNumber; j++) { String strval = parsedline[j+1]; if (strval.toLowerCase().matches(missing)) { phenotypes.setQuick(i, j, Double.NaN); } else phenotypes.setQuick(i, j, Double.parseDouble(strval)); } } TaxaList tL=new TaxaListBuilder().addAll(taxaNames).build(); return new SimplePhenotype(tL, traitList, phenotypes); } /** * @param inputFile the input file with TASSEL v3 annotations or with no input directives * @return * @throws IOException */ public static Phenotype readGenericFile(String inputFile) throws IOException { //BufferedReader br = new BufferedReader(new FileReader(inputFile)); BufferedReader br = Utils.getBufferedReader(inputFile); String inputline = br.readLine(); Pattern sep = Pattern.compile("\\s+"); String[] traitName = null; String[] markerName = null; ArrayList<String[]> headerList = new ArrayList<String[]>(); String[] format = null; String[] use = null; String[] chromosome = null; String[] chrpos = null; String[] locus = null; String[] locuspos = null; boolean isNumeric = false; boolean isCharacter = false; boolean isData = false; boolean isFactor = false; boolean isCovariate = false; int numberOfColumns = 0; //process header rows and count the non-blank rows int numberOfDataLines = 0; while (inputline != null) { inputline = inputline.trim(); String[] parsedline = sep.split(inputline); if (parsedline.length > 1 && !inputline.startsWith("<") && !inputline.startsWith("#")) { numberOfDataLines++; } else if (parsedline[0].toUpperCase().equals("<TRAIT>")) { traitName = processHeader(numberOfColumns, parsedline, inputFile); numberOfColumns = traitName.length; } else if (parsedline[0].toUpperCase().equals("<MARKER>")) { markerName = processHeader(numberOfColumns, parsedline, inputFile); numberOfColumns = markerName.length; } else if (parsedline[0].toUpperCase().equals("<HEADER")) { String[] parsedHeader = processHeader(numberOfColumns, parsedline, inputFile); headerList.add(parsedHeader); numberOfColumns = parsedHeader.length - 1; } else if (parsedline[0].toUpperCase().equals("<FORMAT>")) { format = processHeader(numberOfColumns, parsedline, inputFile); numberOfColumns = format.length; } else if (parsedline[0].toUpperCase().equals("<USE>")) { use = processHeader(numberOfColumns, parsedline, inputFile); numberOfColumns = use.length; } else if (parsedline[0].toUpperCase().equals("<CHROMOSOME>")) { chromosome = processHeader(numberOfColumns, parsedline, inputFile); numberOfColumns = chromosome.length; } else if (parsedline[0].toUpperCase().equals("<CHROMOSOME_POSITION>")) { chrpos = processHeader(numberOfColumns, parsedline, inputFile); numberOfColumns = chrpos.length; } else if (parsedline[0].toUpperCase().equals("<LOCUS>")) { locus = processHeader(numberOfColumns, parsedline, inputFile); numberOfColumns = locus.length; } else if (parsedline[0].toUpperCase().equals("<LOCUS_POSITION>")) { locuspos = processHeader(numberOfColumns, parsedline, inputFile); numberOfColumns = locuspos.length; } else if (parsedline[0].toUpperCase().equals("<NUMERIC>")) { isNumeric = true; } else if (parsedline[0].toUpperCase().equals("<CHARACTER>")) { isCharacter = true; } else if (parsedline[0].toUpperCase().equals("<DATA>")) { isData = true; } else if (parsedline[0].toUpperCase().equals("<COVARIATE>")) { isCovariate = true; } else if (parsedline[0].toUpperCase().equals("<FACTOR>")) { isFactor = true; } inputline = br.readLine(); } br.close(); //create Traits ArrayList<Trait> traitList = new ArrayList<Trait>(numberOfColumns); for (int c = 0; c < numberOfColumns; c++) { String name; boolean discrete; String type; if (traitName == null) { if (markerName == null) { throw new IllegalArgumentException("Error in " + inputFile + ": neither trait nor marker names are defined."); } else { name = markerName[c]; type = Trait.TYPE_MARKER; if (isCharacter) discrete = true; else if (isNumeric) discrete = false; else if (format == null) discrete = true; else if (format[c].toUpperCase().startsWith("N")) discrete = false; else discrete = true; } } else { name = traitName[c]; if (isData) { type = Trait.TYPE_DATA; discrete = false; } else if (isFactor) { type = Trait.TYPE_FACTOR; discrete = true; } else if (isCovariate) { type = Trait.TYPE_COVARIATE; discrete = false; } else if (use == null) { type = Trait.TYPE_DATA; discrete = false; } else if (use[c].toUpperCase().startsWith("D")) { type = Trait.TYPE_DATA; discrete = false; } else if (use[c].toUpperCase().startsWith("C")) { type = Trait.TYPE_COVARIATE; discrete = false; } else if (use[c].toUpperCase().startsWith("F")) { type = Trait.TYPE_FACTOR; discrete = true; } else if (use[c].toUpperCase().startsWith("M")) { type = Trait.TYPE_MARKER; if (isCharacter) discrete = true; else if (isNumeric) discrete = false; else if (format == null) discrete = true; else if (format[c].toUpperCase().startsWith("N")) discrete = false; else discrete = true; } else { type = Trait.TYPE_DATA; discrete = false; } } Trait trait = new Trait(name, discrete, type); traitList.add(trait); for (String[] header : headerList) { trait.addFactor(header[0], header[c + 1]); } if (chromosome != null) trait.setProperty(Trait.PROP_CHROMOSOME, chromosome[c]); if (chrpos != null) trait.setProperty(Trait.PROP_POSITION, Double.parseDouble(chrpos[c])); if (locus != null) trait.setProperty(Trait.PROP_LOCUS, locus[c]); if (locuspos != null) trait.setProperty(Trait.PROP_LOCUS_POSITION, Integer.parseInt(locuspos[c])); } //process body of data String[][] textdata = new String[numberOfColumns][numberOfDataLines]; String[] taxanames = new String[numberOfDataLines]; //br = new BufferedReader(new FileReader(inputFile)); br = Utils.getBufferedReader(inputFile); inputline = br.readLine(); int totallines = 0; int linecount = 0; while (inputline != null) { totallines++; inputline = inputline.trim(); String[] parsedline = sep.split(inputline); if (parsedline.length > 1 && !inputline.startsWith("<") && !inputline.startsWith("#")) { if (parsedline.length != numberOfColumns + 1) { StringBuilder msg = new StringBuilder("Error in "); msg.append(inputFile); msg.append(" line ").append(totallines); msg.append(": Incorrect number of data values."); throw new IllegalArgumentException(msg.toString()); } taxanames[linecount] = parsedline[0]; for (int c = 0; c < numberOfColumns; c++) { textdata[c][linecount] = parsedline[c + 1]; } linecount++; } inputline = br.readLine(); } br.close(); DoubleMatrix2D data = DoubleFactory2D.dense.make(numberOfDataLines, numberOfColumns); for (int c = 0; c < numberOfColumns; c++) { if (traitList.get(c).isDiscrete) { data.viewColumn(c).assign(doubleFromCharacterTrait(traitList.get(c), textdata[c])); } else { for (int r = 0; r < numberOfDataLines; r++) { String textval = textdata[c][r]; if (textval.equals("-999")) data.setQuick(r, c, Double.NaN); else { try {data.setQuick(r, c, Double.parseDouble(textdata[c][r]));} catch (Exception e) {data.setQuick(r, c, Double.NaN);} } } } } TaxaList tL=new TaxaListBuilder().addAll(taxanames).build(); return new SimplePhenotype(tL, traitList, data); } private static String[] processHeader(int numberOfColumns, String[] parsedline, String filename) { if (parsedline[0].equalsIgnoreCase("<Header")) { String headername = parsedline[1].split("[=>\\s]")[1]; if (!parsedline[1].contains("name=") || headername.length() == 0) { StringBuilder msg = new StringBuilder("Error in "); msg.append(filename); msg.append(": Improperly formatted <Header name=> line."); throw new IllegalArgumentException(msg.toString()); } int finalBracketPosition = 0; while(!parsedline[finalBracketPosition].contains(">")) finalBracketPosition++; if (numberOfColumns == 0) numberOfColumns = parsedline.length - finalBracketPosition - 1; else if (numberOfColumns != parsedline.length - finalBracketPosition - 1) { StringBuilder msg = new StringBuilder("Error in "); msg.append(filename); msg.append(": The number of "); msg.append(parsedline[0]).append(" ").append(parsedline[1]); msg.append(" columns does not match the number of columns in previous header rows"); throw new IllegalArgumentException(msg.toString()); } String[] contents = new String[numberOfColumns + 1]; contents[0] = headername; for (int i = 0; i < numberOfColumns; i++) { contents[i + 1] = parsedline[i + finalBracketPosition + 1]; } return contents; } else { if (numberOfColumns == 0) numberOfColumns = parsedline.length - 1; else if (numberOfColumns != parsedline.length - 1) { StringBuilder msg = new StringBuilder("Error in "); msg.append(filename); msg.append(": The number of "); msg.append(parsedline[0]); msg.append(" columns does not match the number of columns in previous header rows"); throw new IllegalArgumentException(msg.toString()); } String[] contents = new String[numberOfColumns]; for (int i = 0; i < numberOfColumns; i++) { contents[i] = parsedline[i + 1]; } return contents; } } }
package com.bucket.biz.shiro; import java.io.Serializable; import java.util.Collection; import org.apache.shiro.session.Session; import org.apache.shiro.session.UnknownSessionException; import org.apache.shiro.session.mgt.SimpleSession; import org.apache.shiro.session.mgt.eis.AbstractSessionDAO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ShiroSessionDao extends AbstractSessionDAO { private static Logger logger = LoggerFactory.getLogger(ShiroSessionDao.class); /** * 会话在redis中的前缀 */ private String sessionPrefix = "shiro_session_Id_"; //private final String REDIS_SES_KEY = "SessionKey"; public String getSessionPrefix() { return sessionPrefix; } public void setSessionPrefix(String sessionPrefix) { this.sessionPrefix = sessionPrefix; } @Override public void update(Session session) throws UnknownSessionException { saveSession(session); } /** * save session * * @param session * @throws UnknownSessionException */ private void saveSession(final Session session) throws UnknownSessionException { if (session == null || session.getId() == null) { logger.error("session or session id is null"); return; } if (session instanceof SimpleSession) { final String sesid = (String) session.getId(); final SimpleSessionSo sessionso = new SimpleSessionSo((SimpleSession) session); // RedisUtil.sadd(sessionPrefix, sesid); // 将ses.id存入redis集合,方便后面获取所有活动会话 //RedisDB.addObject(sessionPrefix + sesid, sessionso, (int) session.getTimeout() / 1000); } else { throw new UnknownSessionException("session类型只能为SimpleSession"); } } @Override public void delete(final Session session) { if (session == null || session.getId() == null) { logger.error("session or session id is null"); return; } // 将session.id从集合中移除 //RedisUtil.srem(sessionPrefix, (String) session.getId()); //RedisDB.remove(sessionPrefix + session.getId()); } @Override public Collection<Session> getActiveSessions() { /* Set<String> keys = RedisUtil.smember(sessionPrefix); if (keys == null || keys.isEmpty()) { return Collections.emptyList(); } List<Session> seslist = new ArrayList<Session>(keys.size()); for (String key : keys) { Session ses = (Session) RedisDB.getObject(key); if (ses == null) { RedisUtil.srem(sessionPrefix, key); continue; } seslist.add(ses); } return seslist;*/ return null; } @Override protected Serializable doCreate(Session session) { Serializable sessionId = this.generateSessionId(session); this.assignSessionId(session, sessionId); this.saveSession(session); return sessionId; } @Override protected Session doReadSession(Serializable sessionId) { if (sessionId == null) { logger.error("session id is null"); return null; } // SimpleSessionSo sesso = (SimpleSessionSo) RedisDB.getObject(sessionPrefix // + (String) sessionId); SimpleSessionSo sesso = null; if (sesso == null) { return null; } return sesso.convert2SimpleSession(); } }
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.limegroup.gnutella.gui; import java.awt.Font; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.limewire.util.FileUtils; import org.limewire.util.OSUtils; import com.limegroup.gnutella.settings.ApplicationSettings; /** * This class provides utility methods retrieving supported languages and * changing language settings. */ public class LanguageUtils { private static Log LOG = LogFactory.getLog(LanguageUtils.class); private static final String BUNDLE_PREFIX = "org/limewire/i18n/Messages_"; private static final String BUNDLE_POSTFIX = ".class"; private static final String BUNDLE_MARKER = "org/limewire/i18n/Messages.class"; /** * Applies this language code to be the new language of the program. */ public static void setLocale(Locale locale) { ApplicationSettings.LANGUAGE.setValue(locale.getLanguage()); ApplicationSettings.COUNTRY.setValue(locale.getCountry()); ApplicationSettings.LOCALE_VARIANT.setValue(locale.getVariant()); GUIMediator.resetLocale(); } /** * Returns an array of supported language as a LanguageInfo[], always having * the English language as the first element. * * This will only include languages that can be displayed using the given * font. If the font is null, all languages are returned. */ public static Locale[] getLocales(Font font) { final List<Locale> locales = new LinkedList<Locale>(); File jar = FileUtils.getJarFromClasspath(LanguageUtils.class.getClassLoader(), BUNDLE_MARKER); if (jar != null) { addLocalesFromJar(locales, jar); } else { LOG.warn("Could not find bundle jar to determine locales"); } Collections.sort(locales, new Comparator<Locale>() { public int compare(Locale o1, Locale o2) { return o1.getDisplayName(o1).compareToIgnoreCase( o2.getDisplayName(o2)); } }); locales.remove(Locale.ENGLISH); locales.add(0, Locale.ENGLISH); // remove languages that cannot be displayed using this font if (font != null && !OSUtils.isMacOSX()) { for (Iterator<Locale> it = locales.iterator(); it.hasNext();) { Locale locale = it.next(); if (!GUIUtils.canDisplay(font, locale.getDisplayName(locale))) { it.remove(); } } } return locales.toArray(new Locale[0]); } /** * Returns the languages as found from the classpath in messages.jar */ static void addLocalesFromJar(List<Locale> locales, File jar) { ZipFile zip = null; try { zip = new ZipFile(jar); Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { String name = entries.nextElement().getName(); if (!name.startsWith(BUNDLE_PREFIX) || !name.endsWith(BUNDLE_POSTFIX) || name.indexOf("$") != -1) { continue; } String iso = name.substring(BUNDLE_PREFIX.length(), name.length() - BUNDLE_POSTFIX.length()); List<String> tokens = new ArrayList<String>(Arrays.asList(iso.split("_", 3))); if (tokens.size() < 1) { continue; } while (tokens.size() < 3) { tokens.add(""); } Locale locale = new Locale(tokens.get(0), tokens.get(1), tokens.get(2)); locales.add(locale); } } catch (IOException e) { LOG.warn("Could not determine locales", e); } finally { if (zip != null) { try { zip.close(); } catch (IOException ioe) { } } } } /** * Returns true if the language of <code>locale</code> is English. */ public static boolean isEnglishLocale(Locale locale) { return Locale.ENGLISH.getLanguage().equals(locale.getLanguage()); } /** * Returns a score between -1 and 3 how well <code>specificLocale</code> * matches <code>genericLocale</code>. * * @return -1, if locales do not match, 3 if locales are equal */ public static int getMatchScore(Locale specificLocale, Locale genericLocale) { int i = 0; if (specificLocale.getLanguage().equals(genericLocale.getLanguage())) { i += 1; } else if (genericLocale.getLanguage().length() > 0) { return -1; } if (specificLocale.getCountry().equals(genericLocale.getCountry())) { i += 1; } else if (genericLocale.getCountry().length() > 0) { return -1; } if (specificLocale.getVariant().equals(genericLocale.getVariant())) { i += 1; } else if (genericLocale.getVariant().length() > 0) { return -1; } return i; } /** * Returns true, if <code>locale</code> is less specific than the system * default locale. * * @see Locale#getDefault() */ public static boolean matchesDefaultLocale(Locale locale) { Locale systemLocale = Locale.getDefault(); if (matchesOrIsMoreSpecific(systemLocale.getLanguage(), locale.getLanguage()) && matchesOrIsMoreSpecific(systemLocale.getCountry(), locale.getCountry()) && matchesOrIsMoreSpecific(systemLocale.getVariant(), locale.getVariant())) { return true; } return false; } private static boolean matchesOrIsMoreSpecific(String detailed, String generic) { return generic.length() == 0 || detailed.equals(generic); } public static String getLocaleString() { return ApplicationSettings.LANGUAGE.getValue() + "_" + ApplicationSettings.COUNTRY.getValue() + "_" + ApplicationSettings.LOCALE_VARIANT.getValue(); } }
import gov.nih.mipav.plugins.PlugInGeneric; /** * @author pandyan * * The plugin is used for sorting DICOM image slices based on the * patient location <0020,0037> * * New dirs are created using patientID info as well as studyID and series...as well as whether the initial images were * in a "pre" or "post" folder * */ public class PlugInDICOMReordering implements PlugInGeneric { /** * construcor * */ public PlugInDICOMReordering() { } /** * run */ public void run() { new PlugInDialogDICOMReordering(false); } }
package ui.android.app.studentclass.mode; import java.io.Serializable; /** * Created by Administrator on 2016/8/9. */ public class Student implements Serializable{ private String stuName; private int age; private String sex; public String getStuName() { return stuName; } public void setStuName(String stuName) { this.stuName = stuName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Student(String stuName,String sex,int age) { this.stuName = stuName; this.sex = sex; this.age = age; } public Student(){ } }
/** * */ package com.adobe.prj.client.ui; import java.util.List; import com.adobe.prj.client.Application; import com.adobe.prj.entity.Employee; import com.adobe.prj.entity.Project; /** * @author danchara * * Contains methods that handles user interaction from console for assigning a manager to a * project . * */ public class AssignProjectManagerUi { private List<Employee> managerList; private List<Project> projectsWithoutManagers; /** * @param managerList * @param projectsWithoutManagers */ public AssignProjectManagerUi(List<Employee> managerList, List<Project> projectsWithoutManagers) { this.managerList = managerList; this.projectsWithoutManagers = projectsWithoutManagers; } /* * Display managers from managerList on console. */ public void displayManagers(){ System.out.println("Employee ID\t\tManager Name\t\t"); for(Employee manager : this.managerList){ System.out.println(manager.getId()+"\t\t\t"+manager.getName()); } } /* * Get user choice about manager chosen for assignment to project . * @return employee id of manager chosen. */ public int getChosenManagerId(){ int enteredEmployeeIdOfManager; do{ System.out.println("Please enter id of manager you want to choose from the above shown :"); enteredEmployeeIdOfManager = Application.inputReader.nextInt(); if(isEnteredManagerIdValid(enteredEmployeeIdOfManager)){ break; }else{ System.out.println("Incorrect id entered!!"); } }while(true); return enteredEmployeeIdOfManager; } private boolean isEnteredManagerIdValid(int enteredEmployeeIdOfManager) { if(enteredEmployeeIdOfManager<= 0){ return false; } boolean isValidId = false; for(Employee manager : this.managerList){ if(manager.getId() == enteredEmployeeIdOfManager){ isValidId = true; } } return isValidId; } /* * Display projects from projectsWithoutManagers on console. */ public void displayProjects(){ System.out.println("Project ID\t\tProject Name\t\t"); for(Project project : this.projectsWithoutManagers){ System.out.println(project.getId()+"\t\t\t"+project.getName()); } } /* * Get id of project chosen for being assigned a manager from console . * @return id of project chosen */ public int getChosenProjectid(){ int enteredIdOfProject; do{ System.out.println("Please chose a project id from above shown :"); enteredIdOfProject = Application.inputReader.nextInt(); if(isValidProjectid(enteredIdOfProject)){ break; }else{ System.out.println("Incorrect project id !!"); } }while(true); return enteredIdOfProject; } private boolean isValidProjectid(int enteredIdOfProject) { if(enteredIdOfProject<=0){ return false; } boolean isValidId = false; for(Project project : this.projectsWithoutManagers){ if(project.getId() == enteredIdOfProject){ isValidId = true; } } return isValidId; } }
public class TimeObserver { IWindow windowToObserve; ITime time; public void RegisterObserver(IWindow window) { windowToObserve = window; } public void OnChange() { windowToObserve.Callback(); } }
package com.example.myapplication1; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ListView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private ListView mListView; private String URL="http://www.imooc.com/api/teacher?type=4&&num=30"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mListView = (ListView) findViewById(R.id.lv_main); new startNewsAsyncTask().execute(URL); } private List<NewsBean> getJasonData(String url) { List<NewsBean> newsBeanList=new ArrayList<>(); try { String jsonString=readStream(new URL(url).openStream()); JSONObject jsonObject; NewsBean newsBean; try { jsonObject=new JSONObject(jsonString); JSONArray jsonArray=jsonObject.getJSONArray("data"); for(int i=0;i<jsonArray.length();i++){ jsonObject=jsonArray.getJSONObject(i); newsBean=new NewsBean(); newsBean.newsIconUrl=jsonObject.getString("picSmall"); newsBean.newsTitle=jsonObject.getString("name"); newsBean.newsContent=jsonObject.getString("description"); newsBeanList.add(newsBean); } } catch (JSONException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } return newsBeanList; } private String readStream(InputStream is){ InputStreamReader isr; String result=""; try { String line=""; isr=new InputStreamReader(is,"utf-8"); BufferedReader br=new BufferedReader(isr); while((line=br.readLine())!=null){ result+=line; } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } class startNewsAsyncTask extends AsyncTask<String,Void,List<NewsBean>>{ @Override protected List<NewsBean> doInBackground(String... params) { return getJasonData(params[0]); } @Override protected void onPostExecute(List<NewsBean> newsBeans) { super.onPostExecute(newsBeans); NewsAdapter newsAdapter=new NewsAdapter(MainActivity.this,newsBeans,mListView); mListView.setAdapter(newsAdapter); } } }
package com.notthemostcommon.creditcardpayoff.User; public class UserBuilder { Long id; String firstName; String lastName; String password; String username; public UserBuilder withId(Long id){ this.id = id; return this; } public UserBuilder withFirstName(String f_name){ this.firstName = f_name; return this; } public UserBuilder withLastName(String l_name){ this.lastName = l_name; return this; } public UserBuilder withPassword(String password){ this.password = password; return this; } public UserBuilder withUsername(String username){ this.username = username; return this; } public AppUser build() { return new AppUser(id, firstName,lastName, password, username); }; }
package com.nextLevel.hero.mnghumanResource.model.dto; public class JobDTO { private int jobNo; private String jobName; public JobDTO() {} public JobDTO(int jobNo, String jobName) { super(); this.jobNo = jobNo; this.jobName = jobName; } public int getJobNo() { return jobNo; } public void setJobNo(int jobNo) { this.jobNo = jobNo; } public String getJobName() { return jobName; } public void setJobName(String jobName) { this.jobName = jobName; } @Override public String toString() { return "JobDTO [jobNo=" + jobNo + ", jobName=" + jobName + "]"; } }
package files; public class FileBlock { private long servID; private long blockID; public FileBlock(long servID, long blockID) { this.servID = servID; this.blockID = blockID; } public long getServID() { return servID; } public void setServID(long servID) { this.servID = servID; } public long getBlockID() { return blockID; } public void setBlockID(long blockID) { this.blockID = blockID; } }
package com.gaoshin.coupon.android; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.protocol.ClientContext; import org.apache.http.cookie.Cookie; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.cookie.BasicClientCookie; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; public class WebClient { private DefaultHttpClient httpClient = null; private BasicHttpContext localContext; private BasicCookieStore cookieStore; private synchronized DefaultHttpClient getHttpClient() { if(httpClient == null) { httpClient = new DefaultHttpClient(); cookieStore = new BasicCookieStore(); localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); } return httpClient; } public void httpPost(String resourcePath) throws BusinessException { httpPost(resourcePath, String.class, null); } public <T> T httpPost(String fullUrl, Class<T> resultType, Object request) throws BusinessException { HttpResponse response = null; try { StringWriter sw = new StringWriter(); if(request == null) sw.append(" "); else if(request instanceof String) sw.append(request.toString()); else sw.append(JsonUtil.toJsonString(request)); String jsonStr = sw.toString(); HttpPost httppost = new HttpPost(fullUrl); httppost.setHeader("Accept", "application/json;charset=utf-8"); httppost.setHeader(HTTP.CONTENT_TYPE, "application/json;charset=utf-8"); httppost.setHeader("Accept-Encoding", "deflate, gzip"); StringEntity se = new StringEntity(jsonStr, "UTF-8"); httppost.setEntity(se); response = getHttpClient().execute(httppost, localContext); return processHttpResponse(response, resultType); } catch (BusinessException e) { throw e; } catch (Throwable t) { StringWriter sw = new StringWriter(); t.printStackTrace(new PrintWriter(sw)); throw new BusinessException(ServiceError.Unknown, sw.toString()); } finally { if(response != null) { try { response.getEntity().consumeContent(); } catch (Throwable e) { } } } } public <T> T httpGet(String path, Class<T> resultType) throws BusinessException { return httpGet(path, resultType, "application/json"); } public String httpGetHtml(String fullUrl) { return httpGet(fullUrl, String.class, "text/html"); } public <T> T httpGet(String fullUrl, Class<T> resultType, String accept) throws BusinessException { HttpResponse response = null; try { HttpGet httpget = new HttpGet(fullUrl); httpget.setHeader("Accept", accept); httpget.setHeader(HTTP.CONTENT_TYPE, "application/json"); response = getHttpClient().execute(httpget, localContext); return processHttpResponse(response, resultType); } catch (BusinessException e) { throw e; } catch (Throwable t) { throw new BusinessException(ServiceError.Unknown, getStackTrace(t)); } finally { if(response != null && !resultType.isAssignableFrom(InputStream.class)) { try { response.getEntity().consumeContent(); } catch (Throwable e) { } } } } private <T> T processHttpResponse(HttpResponse response, Class<T> resultType) throws Exception { int statusCode = response.getStatusLine().getStatusCode(); T bean = null; if (statusCode == 200) { if(resultType.equals(InputStream.class)){ bean = (T) response.getEntity().getContent(); }else{ String content = EntityUtils.toString(response.getEntity(),"UTF-8"); if(content != null && content.length()>0){ if (resultType.equals(String.class)) { bean = (T) content; } else if(content.equals("null")) { bean = resultType.newInstance(); } else { bean = (T)JsonUtil.toJavaObject(content, resultType); } } } } else { ServiceError err = ServiceError.getErrorByCode(statusCode); String errMsg = null; if(response.getEntity()!=null){ long preunziplen = response.getEntity().getContentLength(); errMsg = EntityUtils.toString(response.getEntity(), "UTF-8"); } throw new BusinessException((err!=null ? err : ServiceError.Unknown), errMsg); } return bean; } public WebClient setCookie(String name, String value) { Cookie cookie = new BasicClientCookie(name, value); cookieStore.addCookie(cookie); return this; } public static String getStackTrace(Throwable t) { StringWriter sw = new StringWriter(); t.printStackTrace(new PrintWriter(sw)); return sw.toString(); } public static String getCurrentThreadStackTrace() { StringBuilder sb = new StringBuilder(); StackTraceElement[] elements = Thread.currentThread().getStackTrace(); for (StackTraceElement element : elements) { sb.append(element.toString()); sb.append("\n"); } return sb.toString(); } }
package com.machao.base.ffmpeg.utils; public class PlatformUtils { private static final String OS_NAME_MAC = "mac os"; private static final String OS_NAME_LINUX = "linux"; private static final String OS_NAME_WINDOWS = "windows"; public enum Platform { macos, linux, windows } public enum Arch { x86, x86_64 } public static class UnsupportedPlatformException extends Exception { private static final long serialVersionUID = 1L; public UnsupportedPlatformException(String platform) { super("unsupport platform: " + platform); } } public static class UnsupportedArchException extends Exception { private static final long serialVersionUID = 1L; public UnsupportedArchException(String arch) { super("unsupport arch: " + arch); } } public static Arch getArch() throws UnsupportedArchException { String osArch = System.getProperty("os.arch"); if(osArch.equals(Arch.x86.toString())) { return Arch.x86; } else if(osArch.equals(Arch.x86_64.toString())) { return Arch.x86_64; } throw new UnsupportedArchException(osArch); } public static Platform getPlatform() throws UnsupportedPlatformException { String osName = System.getProperty("os.name").toLowerCase(); if(osName.startsWith(OS_NAME_MAC)) { return Platform.macos; } else if(osName.startsWith(OS_NAME_LINUX)) { return Platform.macos; } else if (osName.startsWith(OS_NAME_WINDOWS)) { return Platform.windows; } throw new UnsupportedPlatformException(osName); } }
package com.example.lenovoidea.mis_2019_exercise_2_maps_polygons; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Resources; import android.graphics.Color; import android.location.Location; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.Polygon; import com.google.android.gms.maps.model.PolygonOptions; import org.w3c.dom.Text; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.google.maps.android.SphericalUtil; import static java.lang.StrictMath.abs; import static java.lang.StrictMath.pow; import static java.lang.StrictMath.sqrt; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMapLongClickListener { private GoogleMap mMap; private EditText inputEditText; private Button startPolygonButton; private SharedPreferences mapPreferences; private boolean polygonDrawMode = false; private List<LatLng> latLngs; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); inputEditText = (EditText) findViewById(R.id.inputEditText); startPolygonButton = (Button) findViewById(R.id.startPolygonButton); mapPreferences = this.getPreferences(Context.MODE_PRIVATE); startPolygonButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { polygonDrawMode = !polygonDrawMode; if(polygonDrawMode){ startPolygonButton.setText("End polygon"); latLngs = new ArrayList<>(); }else{ startPolygonButton.setText("Start polygon"); if(!latLngs.isEmpty()) { renderPolygon(); //calculateArea(); // my failed area calculation LatLng areaMarker = calculateCentroid(); mMap.addMarker(new MarkerOptions().position(areaMarker).title(calculateArea_2()+" sq. km")); mMap.moveCamera(CameraUpdateFactory.newLatLng(areaMarker)); } } } }); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; mMap.setOnMapLongClickListener(this); // Add a marker in Sydney and move the camera LatLng germany = new LatLng(50, 10); mMap.addMarker(new MarkerOptions().position(germany).title("Marker in Germany")); mMap.moveCamera(CameraUpdateFactory.newLatLng(germany)); //removeSavedData(); // to clean all saved marks getSavedData(); } @Override public void onMapLongClick(LatLng latLng){ if(!polygonDrawMode){ // ref https://developer.android.com/training/data-storage/shared-preferences mMap.addMarker(new MarkerOptions().position(latLng).title(inputEditText.getText().toString())); SharedPreferences.Editor editor = mapPreferences.edit(); editor.putString(latLng.longitude + ":" + latLng.latitude, inputEditText.getText().toString()); editor.apply(); } else{ mMap.addMarker(new MarkerOptions().position(latLng)); latLngs.add(latLng); } } public void getSavedData(){ Map<String, ?> allMapData = mapPreferences.getAll(); for (Map.Entry<String, ?> mapData : allMapData.entrySet()) { double lon = Double.parseDouble(mapData.getKey().split(":")[0]); double lat = Double.parseDouble(mapData.getKey().split(":")[1]); LatLng latLng = new LatLng(lat, lon); mMap.addMarker(new MarkerOptions().position(latLng).title(mapData.getValue().toString())); } } private void removeSavedData(){ SharedPreferences.Editor editor = mapPreferences.edit(); editor.clear(); editor.apply(); } public void renderPolygon(){ PolygonOptions rectOptions = new PolygonOptions().addAll(latLngs); Polygon polygon = mMap.addPolygon(rectOptions); polygon.setFillColor(0x5500FF00); polygon.setStrokeColor(Color.BLUE); polygon.setStrokeWidth(3.0f); } // calculates the area of the polygon // ref https://www.wikihow.com/Calculate-the-Area-of-a-Polygon public double calculateArea(){ double sumX = 0, sumY = 0, difference, areaRaw, areaKm2; for(int i = 0; i < latLngs.size(); i++){ //Log.d("All LatLng :",latLngs.get(i).latitude + " : " + latLngs.get(i).longitude); if(i == latLngs.size()-1){ sumX += latLngs.get(i).latitude * latLngs.get(0).longitude; sumY += latLngs.get(0).latitude * latLngs.get(i).longitude; }else{ sumX += latLngs.get(i).latitude * latLngs.get(i + 1).longitude; sumY += latLngs.get(i + 1).latitude * latLngs.get(i).longitude; } } Log.d("All Summ :",sumX + " : " + sumY); //difference = abs (sumX - sumY); difference = sumX - sumY; Log.d("All Difference :",difference + ""); areaRaw = difference/2; // polygon area is ok // i could not convert the polygon area into the geographic area :( /************** Test to compute the area of geography **************/ //areaKm2 = areaRaw * 1.609344d * 1.609344d; areaKm2 = abs(areaRaw * 6371 * 6371); Log.d("All area :",areaKm2 + ""); testDist(); // more test to find a ratio /************** Test to compute the area of geography **************/ return areaRaw; } // after failing to calculate the geographic area i used this library // ref https://stackoverflow.com/questions/28838287/calculate-the-area-of-a-polygon-drawn-on-google-maps-in-an-android-application // ref http://googlemaps.github.io/android-maps-utils/ public double calculateArea_2(){ double area = SphericalUtil.computeArea(latLngs)/1000000; // converts m2 to km2 //Log.d("All area :",area + ""); return area; } // calculation of the centroid // used the polygon area which i calculated before calculateArea() // ref https://www.seas.upenn.edu/~sys502/extra_materials/Polygon%20Area%20and%20Centroid.pdf public LatLng calculateCentroid(){ LatLng centroid; double sumX = 0, sumY = 0; for(int i = 0; i < latLngs.size(); i++){ double xi,xi1,yi,yi1; xi = latLngs.get(i).latitude; yi = latLngs.get(i).longitude; if(i == latLngs.size()-1){ xi1 = latLngs.get(0).latitude; yi1 = latLngs.get(0).longitude; }else{ xi1 = latLngs.get(i+1).latitude; yi1 = latLngs.get(i+1).longitude; } sumX += (xi+xi1) * (xi*yi1 - xi1*yi); sumY += (yi+yi1) * (xi*yi1 - xi1*yi); Log.d("All sumX", sumX + ""); Log.d("All sumY", sumY + ""); } sumX = sumX/(6 * calculateArea()); sumY = sumY/(6 * calculateArea()); Log.d("All sumX", sumX + ""); Log.d("All sumY", sumY + ""); centroid = centroid = new LatLng(sumX, sumY); return centroid; } // more tests to find a ratio to convert polygon area to geographic area // no luck // inconsistent ratio private void testDist(){ Location locA = new Location("Point A"); Location locB = new Location("Point B"); locA.setLatitude(latLngs.get(0).latitude); locA.setLatitude(latLngs.get(0).longitude); locB.setLatitude(latLngs.get(1).latitude); locB.setLatitude(latLngs.get(1).longitude); double distance = locA.distanceTo(locB)/1000; double cartesianDistance = sqrt(pow((latLngs.get(0).latitude - latLngs.get(1).latitude), 2) + pow((latLngs.get(0).longitude - latLngs.get(1).longitude), 2)); double ratio = distance / cartesianDistance; Log.d("All distance ", distance+""); Log.d("All cartesian ", cartesianDistance+""); Log.d("All ratio ", ratio+""); } }
package com.apress.prospring4.ch13; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.ui.ExtendedModelMap; public class ContactControllerTest { private final List<Contact> contacts = new ArrayList<Contact>(); @Before // JUnit annotation public void initContacts() { Contact contact = new Contact(); contact.setId(11); contact.setFirstName("Bender"); contact.setLastName("Rodriguez"); contacts.add(contact); } @Test public void testList() { ContactService contactService = mock(ContactService.class); // imitation! when(contactService.findAll()).thenReturn(contacts); ContactController contactController = new ContactController(); // Reflection! ReflectionTestUtils.setField(contactController, "contactService", contactService); ExtendedModelMap uiModel = new ExtendedModelMap(); uiModel.addAttribute("contacts", contactController.listData()); } }
package userdaoimp; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.criterion.Restrictions; import userdao.RolesDAO; import bean.users.RolesBean; public class RoleDaoImpl implements RolesDAO { private SessionFactory factory = utils.HConnection.getSessionFactory(); private Session session = null; private Transaction tr = null; private List<RolesBean> list = null; public RoleDaoImpl() { list = new ArrayList<>(); } @Override public int insert(RolesBean c) throws ClassNotFoundException, SQLException { session = factory.openSession(); tr = session.beginTransaction(); int id = (Integer) session.save(c); tr.commit(); session.close(); return id; } @Override public List<RolesBean> getAll() throws ClassNotFoundException, SQLException { list = new ArrayList<>(); session = factory.openSession(); tr = session.beginTransaction(); list = session.createQuery("FROM RolesBean").list(); tr.commit(); session.close(); factory.close(); return list; } @Override public RolesBean getById(int id) throws ClassNotFoundException, SQLException { session = factory.openSession(); tr = session.beginTransaction(); Criteria criteria = session.createCriteria(RolesBean.class); criteria.add(Restrictions.eq("id", id)); RolesBean bean = (RolesBean) criteria.uniqueResult(); tr.commit(); session.close(); factory.close(); return bean; } @Override public int update(int id, RolesBean c) throws ClassNotFoundException, SQLException { session = factory.openSession(); tr = session.beginTransaction(); RolesBean b = (RolesBean) session.get(RolesBean.class, id); b.setRole(c.getRole()); session.update(b); session.getTransaction().commit(); session.close(); return id; } @Override public int delete(int id) throws ClassNotFoundException, SQLException { session = factory.openSession(); tr = session.beginTransaction(); RolesBean b = (RolesBean) session.get(RolesBean.class, id); session.delete(b); tr.commit(); session.close(); return id; } @Override public int softDelete(int id) throws ClassNotFoundException, SQLException { // TODO Auto-generated method stub return 0; } }
package pepoker.practicasJava; import java.util.ArrayList; import java.util.Calendar; import java.util.List; public class LargestPalindrome { static int count = 0; public LargestPalindrome() { super(); } public static int getLargestPalindrome(int digitos) { int resp = 0; int min = getNumMinimoParaDigitos(digitos); int max = getNumMaximoParaDigitos(digitos); int temp = 0; List<String> palindromos = new ArrayList<String>(); for (int i = min; i <= max; i++) { for (int j = min; j <= max; j++) { temp = i * j; if (temp > resp && isPalindrome(temp)) { palindromos.add(i + "*" + j); resp = temp; } } } System.out.println(palindromos); return resp; } public static int getLargestPalindromeReverse(int digitos) { int resp = 0; int min = getNumMinimoParaDigitos(digitos); int max = getNumMaximoParaDigitos(digitos); int temp = 0; List<String> palindromos = new ArrayList<String>(); for (int i = max; i >= min; i--) { for (int j = max; j >= min; j--) { temp = i * j; if (temp > resp && isPalindrome(temp)) { palindromos.add(i + "*" + j); resp = temp; } } } return resp; } private static boolean isPalindrome(Integer num) { count++; StringBuilder i = new StringBuilder(num.toString()); return i.toString().equals(i.reverse().toString()); } private static int getNumMaximoParaDigitos(Integer digitos) { String max = "0"; for (int i = 1; i <= digitos; i++) { max += "9"; } return new Integer(max); } private static int getNumMinimoParaDigitos(Integer digitos) { String min = "1"; for (int i = 1; i < digitos; i++) { min += "0"; } return new Integer(min); } public static void main(String[] args) { Calendar c = Calendar.getInstance(); System.out.println(c.getTimeInMillis()); System.out.println(getLargestPalindrome(3)); System.out.println(count); System.out.println(c.getInstance().getTimeInMillis()); System.out.println(getLargestPalindromeReverse(3)); System.out.println(count); System.out.println(c.getInstance().getTimeInMillis()); } }
package com.MicHon.factory; public enum UnitType { TANK, CANNON }
package codility; import static codility.tools.Rand.*; import static org.assertj.core.api.StrictAssertions.assertThat; import org.apache.commons.lang3.ArrayUtils; import org.junit.contrib.theories.Theories; import org.junit.contrib.theories.Theory; import org.junit.runner.RunWith; import com.pholser.junit.quickcheck.ForAll; import com.pholser.junit.quickcheck.From; import com.pholser.junit.quickcheck.generator.GenerationStatus; import com.pholser.junit.quickcheck.random.SourceOfRandomness; import codility.tools.AbstractIntArrayGenerator; //@RunWith(Theories.class) public class QuickCheckTest { Solution1 solution = new Solution1(); @Theory public void solution0(@ForAll(sampleSize=2000) @From(IntArrayGenerator.class) int[] a) { assertThat(a.length) .as("result of %s", ArrayUtils.toString(a)) .isEqualTo(20); } public static class IntArrayGenerator extends AbstractIntArrayGenerator { @Override public int[] generate(SourceOfRandomness random, GenerationStatus status) { return arrayOfSize(1, 6, 31, 37).of(-8, 8); } } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.validation.beanvalidation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Optional; import java.util.Set; import jakarta.validation.Constraint; import jakarta.validation.ConstraintValidator; import jakarta.validation.ConstraintValidatorContext; import jakarta.validation.ConstraintValidatorFactory; import jakarta.validation.ConstraintViolation; import jakarta.validation.Payload; import jakarta.validation.Valid; import jakarta.validation.Validator; import jakarta.validation.ValidatorFactory; import jakarta.validation.constraints.NotNull; import org.hibernate.validator.HibernateValidator; import org.hibernate.validator.HibernateValidatorFactory; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.core.env.Environment; import org.springframework.validation.BeanPropertyBindingResult; import org.springframework.validation.Errors; import org.springframework.validation.FieldError; import org.springframework.validation.ObjectError; import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller */ class ValidatorFactoryTests { @Test void simpleValidation() { @SuppressWarnings("resource") LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.afterPropertiesSet(); ValidPerson person = new ValidPerson(); Set<ConstraintViolation<ValidPerson>> result = validator.validate(person); assertThat(result).hasSize(2); for (ConstraintViolation<ValidPerson> cv : result) { String path = cv.getPropertyPath().toString(); assertThat(path).matches(actual -> "name".equals(actual) || "address.street".equals(actual)); assertThat(cv.getConstraintDescriptor().getAnnotation()).isInstanceOf(NotNull.class); } Validator nativeValidator = validator.unwrap(Validator.class); assertThat(nativeValidator.getClass().getName()).startsWith("org.hibernate"); assertThat(validator.unwrap(ValidatorFactory.class)).isInstanceOf(HibernateValidatorFactory.class); assertThat(validator.unwrap(HibernateValidatorFactory.class)).isInstanceOf(HibernateValidatorFactory.class); validator.destroy(); } @Test void simpleValidationWithCustomProvider() { @SuppressWarnings("resource") LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.setProviderClass(HibernateValidator.class); validator.afterPropertiesSet(); ValidPerson person = new ValidPerson(); Set<ConstraintViolation<ValidPerson>> result = validator.validate(person); assertThat(result).hasSize(2); for (ConstraintViolation<ValidPerson> cv : result) { String path = cv.getPropertyPath().toString(); assertThat(path).matches(actual -> "name".equals(actual) || "address.street".equals(actual)); assertThat(cv.getConstraintDescriptor().getAnnotation()).isInstanceOf(NotNull.class); } Validator nativeValidator = validator.unwrap(Validator.class); assertThat(nativeValidator.getClass().getName()).startsWith("org.hibernate"); assertThat(validator.unwrap(ValidatorFactory.class)).isInstanceOf(HibernateValidatorFactory.class); assertThat(validator.unwrap(HibernateValidatorFactory.class)).isInstanceOf(HibernateValidatorFactory.class); validator.destroy(); } @Test void simpleValidationWithClassLevel() { @SuppressWarnings("resource") LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.afterPropertiesSet(); ValidPerson person = new ValidPerson(); person.setName("Juergen"); person.getAddress().setStreet("Juergen's Street"); Set<ConstraintViolation<ValidPerson>> result = validator.validate(person); assertThat(result).hasSize(1); Iterator<ConstraintViolation<ValidPerson>> iterator = result.iterator(); ConstraintViolation<?> cv = iterator.next(); assertThat(cv.getPropertyPath().toString()).isEmpty(); assertThat(cv.getConstraintDescriptor().getAnnotation()).isInstanceOf(NameAddressValid.class); validator.destroy(); } @Test void springValidationFieldType() { @SuppressWarnings("resource") LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.afterPropertiesSet(); ValidPerson person = new ValidPerson(); person.setName("Phil"); person.getAddress().setStreet("Phil's Street"); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(person, "person"); validator.validate(person, errors); assertThat(errors.getErrorCount()).isEqualTo(1); assertThat(errors.getFieldError("address").getRejectedValue()) .as("Field/Value type mismatch") .isInstanceOf(ValidAddress.class); validator.destroy(); } @Test void springValidation() { @SuppressWarnings("resource") LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.afterPropertiesSet(); ValidPerson person = new ValidPerson(); BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person"); validator.validate(person, result); assertThat(result.getErrorCount()).isEqualTo(2); FieldError fieldError = result.getFieldError("name"); assertThat(fieldError.getField()).isEqualTo("name"); List<String> errorCodes = Arrays.asList(fieldError.getCodes()); assertThat(errorCodes).hasSize(4); assertThat(errorCodes.contains("NotNull.person.name")).isTrue(); assertThat(errorCodes.contains("NotNull.name")).isTrue(); assertThat(errorCodes.contains("NotNull.java.lang.String")).isTrue(); assertThat(errorCodes.contains("NotNull")).isTrue(); fieldError = result.getFieldError("address.street"); assertThat(fieldError.getField()).isEqualTo("address.street"); errorCodes = Arrays.asList(fieldError.getCodes()); assertThat(errorCodes).hasSize(5); assertThat(errorCodes.contains("NotNull.person.address.street")).isTrue(); assertThat(errorCodes.contains("NotNull.address.street")).isTrue(); assertThat(errorCodes.contains("NotNull.street")).isTrue(); assertThat(errorCodes.contains("NotNull.java.lang.String")).isTrue(); assertThat(errorCodes.contains("NotNull")).isTrue(); validator.destroy(); } @Test void springValidationWithClassLevel() { @SuppressWarnings("resource") LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.afterPropertiesSet(); ValidPerson person = new ValidPerson(); person.setName("Juergen"); person.getAddress().setStreet("Juergen's Street"); BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person"); validator.validate(person, result); assertThat(result.getErrorCount()).isEqualTo(1); ObjectError globalError = result.getGlobalError(); List<String> errorCodes = Arrays.asList(globalError.getCodes()); assertThat(errorCodes).hasSize(2); assertThat(errorCodes.contains("NameAddressValid.person")).isTrue(); assertThat(errorCodes.contains("NameAddressValid")).isTrue(); validator.destroy(); } @Test void springValidationWithAutowiredValidator() { ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext( LocalValidatorFactoryBean.class); LocalValidatorFactoryBean validator = ctx.getBean(LocalValidatorFactoryBean.class); ValidPerson person = new ValidPerson(); person.expectsAutowiredValidator = true; person.setName("Juergen"); person.getAddress().setStreet("Juergen's Street"); BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person"); validator.validate(person, result); assertThat(result.getErrorCount()).isEqualTo(1); ObjectError globalError = result.getGlobalError(); List<String> errorCodes = Arrays.asList(globalError.getCodes()); assertThat(errorCodes).hasSize(2); assertThat(errorCodes.contains("NameAddressValid.person")).isTrue(); assertThat(errorCodes.contains("NameAddressValid")).isTrue(); validator.destroy(); ctx.close(); } @Test void springValidationWithErrorInListElement() { @SuppressWarnings("resource") LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.afterPropertiesSet(); ValidPerson person = new ValidPerson(); person.getAddressList().add(new ValidAddress()); BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person"); validator.validate(person, result); assertThat(result.getErrorCount()).isEqualTo(3); FieldError fieldError = result.getFieldError("name"); assertThat(fieldError.getField()).isEqualTo("name"); fieldError = result.getFieldError("address.street"); assertThat(fieldError.getField()).isEqualTo("address.street"); fieldError = result.getFieldError("addressList[0].street"); assertThat(fieldError.getField()).isEqualTo("addressList[0].street"); validator.destroy(); } @Test void springValidationWithErrorInSetElement() { @SuppressWarnings("resource") LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.afterPropertiesSet(); ValidPerson person = new ValidPerson(); person.getAddressSet().add(new ValidAddress()); BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person"); validator.validate(person, result); assertThat(result.getErrorCount()).isEqualTo(3); FieldError fieldError = result.getFieldError("name"); assertThat(fieldError.getField()).isEqualTo("name"); fieldError = result.getFieldError("address.street"); assertThat(fieldError.getField()).isEqualTo("address.street"); fieldError = result.getFieldError("addressSet[].street"); assertThat(fieldError.getField()).isEqualTo("addressSet[].street"); validator.destroy(); } @Test void innerBeanValidation() { @SuppressWarnings("resource") LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.afterPropertiesSet(); MainBean mainBean = new MainBean(); Errors errors = new BeanPropertyBindingResult(mainBean, "mainBean"); validator.validate(mainBean, errors); Object rejected = errors.getFieldValue("inner.value"); assertThat(rejected).isNull(); validator.destroy(); } @Test void validationWithOptionalField() { @SuppressWarnings("resource") LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.afterPropertiesSet(); MainBeanWithOptional mainBean = new MainBeanWithOptional(); Errors errors = new BeanPropertyBindingResult(mainBean, "mainBean"); validator.validate(mainBean, errors); Object rejected = errors.getFieldValue("inner.value"); assertThat(rejected).isNull(); validator.destroy(); } @Test void listValidation() { @SuppressWarnings("resource") LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.afterPropertiesSet(); ListContainer listContainer = new ListContainer(); listContainer.addString("A"); listContainer.addString("X"); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(listContainer, "listContainer"); errors.initConversion(new DefaultConversionService()); validator.validate(listContainer, errors); FieldError fieldError = errors.getFieldError("list[1]"); assertThat(fieldError).isNotNull(); assertThat(fieldError.getRejectedValue()).isEqualTo("X"); assertThat(errors.getFieldValue("list[1]")).isEqualTo("X"); validator.destroy(); } @Test void withConstraintValidatorFactory() { ConstraintValidatorFactory cvf = new SpringConstraintValidatorFactory(new DefaultListableBeanFactory()); @SuppressWarnings("resource") LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.setConstraintValidatorFactory(cvf); validator.afterPropertiesSet(); assertThat(validator.getConstraintValidatorFactory()).isSameAs(cvf); validator.destroy(); } @Test void withCustomInitializer() { ConstraintValidatorFactory cvf = new SpringConstraintValidatorFactory(new DefaultListableBeanFactory()); @SuppressWarnings("resource") LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.setConfigurationInitializer(configuration -> configuration.constraintValidatorFactory(cvf)); validator.afterPropertiesSet(); assertThat(validator.getConstraintValidatorFactory()).isSameAs(cvf); validator.destroy(); } @NameAddressValid public static class ValidPerson { @NotNull private String name; @Valid private ValidAddress address = new ValidAddress(); @Valid private List<ValidAddress> addressList = new ArrayList<>(); @Valid private Set<ValidAddress> addressSet = new LinkedHashSet<>(); public boolean expectsAutowiredValidator = false; public String getName() { return name; } public void setName(String name) { this.name = name; } public ValidAddress getAddress() { return address; } public void setAddress(ValidAddress address) { this.address = address; } public List<ValidAddress> getAddressList() { return addressList; } public void setAddressList(List<ValidAddress> addressList) { this.addressList = addressList; } public Set<ValidAddress> getAddressSet() { return addressSet; } public void setAddressSet(Set<ValidAddress> addressSet) { this.addressSet = addressSet; } } public static class ValidAddress { @NotNull private String street; public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } } @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = NameAddressValidator.class) public @interface NameAddressValid { String message() default "Street must not contain name"; Class<?>[] groups() default {}; Class<?>[] pa