code
stringlengths
10
174k
nl
stringlengths
3
129k
private static synchronized boolean checkFolderPermissions(StringBuilder aStringBuilder,String aDirectory){ File directory=new File(aDirectory); if (!directory.exists()) { directory.mkdirs(); } if (!directory.canRead()) { aStringBuilder.append("The directory [" + directory + "] is not readable. "+ "Please check your permissions rights.\n"); return false; } if (!directory.canWrite()) { aStringBuilder.append("The directory [" + directory + "] is not writable. "+ "Please check your permissions rights.\n"); return false; } return true; }
Checks if a directory already exists. If it does not exist it is created. If it already exists then, its permissions are ok.
private void sendBroadcastNewSyncFolder(Account account,String remotePath){ Intent added=new Intent(FileDownloader.getDownloadAddedMessage()); added.putExtra(FileDownloader.ACCOUNT_NAME,account.name); added.putExtra(FileDownloader.EXTRA_REMOTE_PATH,remotePath); added.putExtra(FileDownloader.EXTRA_FILE_PATH,FileStorageUtils.getSavePath(account.name) + remotePath); mService.sendStickyBroadcast(added); }
TODO review this method when "folder synchronization" replaces "folder download"; this is a fast and ugly patch.
public Vector direction(){ if (this.magnitude() == 0.0) throw new ArithmeticException("Zero-vector has no direction"); return this.times(1.0 / this.magnitude()); }
Returns a unit vector in the direction of this vector.
@Override public boolean equals(Object obj){ if (obj instanceof Client) { Client other=(Client)obj; return this.getEndpoint().equals(other.getEndpoint()); } else { return false; } }
Compares this Client to another object.
private void paintBackgroundHover(Graphics2D g,JComponent c,int width,int height){ paintBackground(g,c,width,height,hover); }
Paint the background mouse-over state.
public void testDrawBug() throws ChessParseError { Game game=new Game(null,new TimeControlData()); assertEquals(false,game.haveDrawOffer()); game.processString("e4"); game.processString("c5"); assertEquals(Game.GameState.ALIVE,game.getGameState()); game.processString("draw accept"); assertEquals(Game.GameState.ALIVE,game.getGameState()); game.processString("draw rep"); assertEquals(Game.GameState.ALIVE,game.getGameState()); game.processString("draw 50"); assertEquals(Game.GameState.ALIVE,game.getGameState()); assertEquals(Piece.EMPTY,game.tree.currentPos.getPiece(TextIO.getSquare("e5"))); }
Test of draw offer/accept/request command.
private EncodingFactory(Iterator<EncodingSet> encodingSets){ while (encodingSets.hasNext()) { processEncodingSet(encodingSets.next()); } final EncodingDefinition candidateDefinition=javaCharsetToDefinition.get(DEFAULT_CHARSET); if (candidateDefinition != null && !candidateDefinition.isInformationOnly()) { defaultEncoding=candidateDefinition.getEncoding(); defaultEncodingDefinition=candidateDefinition; } else { defaultEncoding=new EncodingGeneric(DEFAULT_CHARSET); defaultEncodingDefinition=new DefaultEncodingDefinition(ENCODING_NAME_NONE,DEFAULT_CHARSET,1,ISCConstants.CS_NONE,false); } }
Initializes EncodingFactory by processing the encodingSets using the provided iterator.
public static boolean isWhitespaceStr(String str){ if (str == null) { return false; } str=str.trim(); for (int i=0; i < str.length(); i++) { if (!Character.isWhitespace(str.charAt(i))) { return false; } } return true; }
Checks if the input String is Whitespace only.
@NotNull public OptionalInt findOptionalInt(@NotNull SqlQuery query){ Optional<Integer> value=findOptional(Integer.class,query); return value.isPresent() ? OptionalInt.of(value.get()) : OptionalInt.empty(); }
Finds a unique result from database, converting the database row to int using default mechanisms. Returns empty if there are no results or if single null result is returned.
public int findColumn(String columnName){ for (int i=0; i < m_fields.size(); i++) { GridField field=(GridField)m_fields.get(i); if (columnName.equals(field.getColumnName())) return i; } return -1; }
Returns a column given its name.
public boolean removeFields(String name){ return this.remove(name) != null; }
Remove all fields with the name
public void publish(Record record,Handler<AsyncResult<Record>> resultHandler){ delegate.publish(record,resultHandler); }
Publishes a record.
private boolean zzRefill(){ return zzCurrentPos >= s.offset + s.count; }
Refills the input buffer.
private void createPackageDir(File packageFile,String treePath){ packageNode=createPackage(packageFile); packageDir=new DirectoryElement(treePath); builder.newDep(packageDir,packageNode,JavaRelation.PACKAGEDIR); }
Create both a package and directory, and the container dependency between them.
public static void main(final String[] args){ DOMTestCase.doMain(nodeattributenodename.class,args); }
Runs this test from the command line.
public int lastIndexOf(String subString,int start){ int subCount=subString.count; if (subCount <= count && start >= 0) { if (subCount > 0) { if (start > count - subCount) { start=count - subCount; } char[] target=subString.value; int subOffset=subString.offset; char firstChar=target[subOffset]; int end=subOffset + subCount; while (true) { int i=lastIndexOf(firstChar,start); if (i == -1) { return -1; } int o1=offset + i, o2=subOffset; while (++o2 < end && value[++o1] == target[o2]) { } if (o2 == end) { return i; } start=i - 1; } } return start < count ? start : count; } return -1; }
Searches in this String for the index of the specified string. The search for the string starts at the specified offset and moves towards the beginning of this String.
private static boolean isViewDescendantOf(View child,View parent){ if (child == parent) { return true; } final ViewParent theParent=child.getParent(); return (theParent instanceof ViewGroup) && isViewDescendantOf((View)theParent,parent); }
Return true if child is a descendant of parent, (or equal to the parent).
void store(ASTNode newNode,org.eclipse.che.ide.ext.java.jdt.internal.compiler.ast.ASTNode oldASTNode){ }
Allows the user to store information about the given old/new pair of AST nodes. <p> The default implementation of this method does nothing. Subclasses may reimplement. </p>
public int size(){ if (mGarbage) { gc(); } return mSize; }
Returns the number of key-value mappings that this FieldArray currently stores.
private static synchronized void cleanup(Statement S,ResultSet R){ logger.trace("cleanup() -->entry"); Connection C=null; if (R != null) { logger.trace("cleanup() --> ResultSet.close()"); try { R.close(); } catch ( Throwable t) { surfaceThrowable("cleanup() called ResultSet.close()",t); } } if (S != null) { try { C=S.getConnection(); } catch ( Throwable t) { surfaceThrowable("cleanup() called Statement.getConnection()",t); } logger.trace("cleanup() --> Statement.close()"); try { S.close(); } catch ( Throwable t) { surfaceThrowable("cleanup() called Statement.close()",t); } } if (C != null) { logger.trace("cleanup() --> Connection.close()"); try { C.close(); } catch ( Throwable t) { surfaceThrowable("cleanup() called Connection.close()",t); } } logger.trace("cleanup() <--exit"); }
Close the input JDBC ResultSet, Statement, and Connection objects, as appropriate. Any error(s) in close processing is surfaced, but this seems to be about all that can be done. (?)
public void append(StringBuffer buffer,String fieldName,int[] array,Boolean fullDetail){ appendFieldStart(buffer,fieldName); if (array == null) { appendNullText(buffer,fieldName); } else if (isFullDetail(fullDetail)) { appendDetail(buffer,fieldName,array); } else { appendSummary(buffer,fieldName,array); } appendFieldEnd(buffer,fieldName); }
<p>Append to the <code>toString</code> an <code>int</code> array.</p>
public AdvancedStateMap.Builder withSuffix(String builderSuffixIn){ this.suffix=builderSuffixIn; return this; }
Sets the suffix
public static Animation inFromRightAnimation(long duration,Interpolator interpolator){ Animation inFromRight=new TranslateAnimation(Animation.RELATIVE_TO_PARENT,+1.0f,Animation.RELATIVE_TO_PARENT,0.0f,Animation.RELATIVE_TO_PARENT,0.0f,Animation.RELATIVE_TO_PARENT,0.0f); inFromRight.setDuration(duration); inFromRight.setInterpolator(interpolator == null ? new AccelerateInterpolator() : interpolator); return inFromRight; }
Slide animations to enter a view from right.
public LongLazyValue(LongSupplier supplier){ Validate.notNull(supplier,"supplier can't be null!"); this.supplier=supplier; }
Construct new LongLazyValue with given supplier for value.
public void runTest() throws Throwable { Document doc; NodeList genderList; Node gender; NodeList genList; Node gen; NodeList gList; Element genElement; Attr newAttr; Attr setAttr1; doc=(Document)load("staffNS",true); if (!isExpandEntityReferences()) { genderList=doc.getElementsByTagName("gender"); gender=genderList.item(2); genList=gender.getChildNodes(); gen=genList.item(0); } else { gen=doc.createEntityReference("ent4"); } gList=gen.getChildNodes(); genElement=(Element)gList.item(0); assertNotNull("notnull",genElement); newAttr=doc.createAttributeNS("www.xyz.com","emp:local1"); { boolean success=false; try { setAttr1=genElement.setAttributeNodeNS(newAttr); } catch ( DOMException ex) { success=(ex.code == DOMException.NO_MODIFICATION_ALLOWED_ERR); } assertTrue("throw_NO_MODIFICATION_ALLOWED_ERR",success); } }
Runs the test case.
private List<String> assertNotBlankAndTrim(List<String> list,String displayName){ List<String> trimmed=null; if (list != null) { for ( String string : list) { Assert.hasText(string,displayName + " must not be blank"); } trimmed=new ArrayList<>(); for ( String string : list) { trimmed.add(string.trim()); } } return trimmed; }
Asserts that the given list of string contains no blank string and returns a copy of the list with all the values trimmed. If the given list is null, a null is returned.
public void updateData(float heightCoefficient,float amplitude){ for ( GLWave wave : waves) { wave.setCoefficient(Utils.randomize(heightCoefficient,random)); } if (amplitude > this.amplitude) { this.amplitude=amplitude; if (heightCoefficient > 0.25f) { produceBubbles(); } } else { this.amplitude=Utils.smooth(this.amplitude,amplitude,0.8f); } }
Update waves data.
public static Ignite start(IgniteConfiguration cfg,boolean failIfStarted) throws IgniteCheckedException { return start(cfg,null,failIfStarted); }
Starts a grid with given configuration. If the grid is already started and failIfStarted set to TRUE an exception will be thrown.
@Autowired public DeleteCashierAllocationCommandHandler(final TellerWritePlatformService writePlatformService){ super(); this.writePlatformService=writePlatformService; }
Creates a new instance.
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-02-25 10:37:55.947 -0500",hash_original_method="468639083877010DF76F28D2CCF3941F",hash_generated_method="0C793579C53BAAFB5D1C7FE4CB20EEA9") public void send(byte[] data,int length,InetAddress host,int port) throws IOException { _sendPacket.setData(data); _sendPacket.setLength(length); _sendPacket.setAddress(host); _sendPacket.setPort(port); _socket_.send(_sendPacket); }
Sends the specified data to the specified server at the specified port. <p>
public double[] dataVector(V p){ return project(minusEquals(p.toArray(),centroid),strongEigenvectors); }
Returns the data vectors after projection.
public static int[][] loadPNMFile(InputStream str,boolean flipY) throws IOException { int[][] vals=loadPNMFile(str); if (flipY) { for (int i=0; i < vals.length; i++) { int height=vals[i].length; for (int j=0; j < height / 2; j++) { int temp=vals[i][j]; vals[i][j]=vals[i][height - j + 1]; vals[i][height - j + 1]=temp; } } } return vals; }
Loads plain or raw PGM files or plain or raw PBM files and return the result as an int[][]. If flipY is true, then the Y dimension is flipped.
protected SequenceContext(JsonNode json){ children=null != json ? json.elements() : null; }
Create an iterator over the children. May be constructed with a null JsonArray if we only use it for writing.
public static int modifierFlags(boolean altP,boolean ctrlP,boolean metaP,boolean shiftP){ int flags=0; if (altP) flags|=F_ALT_DOWN; if (ctrlP) flags|=F_CTRL_DOWN; if (metaP) flags|=F_META_DOWN; if (shiftP) flags|=F_SHIFT_DOWN; return flags; }
A helper function used by platform input code to compose modifier flags.
public boolean areTablesSet(){ return (qTables != null); }
Returns <code>true</code> if tables are currently set.
public void testGeneratedColumns() throws Exception { if (!versionMeetsMinimum(5,7,6)) { return; } createTable("pythagorean_triple","(side_a DOUBLE NULL, side_b DOUBLE NULL, " + "side_c_vir DOUBLE AS (SQRT(side_a * side_a + side_b * side_b)) VIRTUAL UNIQUE KEY COMMENT 'hypotenuse - virtual', " + "side_c_sto DOUBLE GENERATED ALWAYS AS (SQRT(POW(side_a, 2) + POW(side_b, 2))) STORED UNIQUE KEY COMMENT 'hypotenuse - stored' NOT NULL "+ "PRIMARY KEY)"); assertEquals(1,this.stmt.executeUpdate("INSERT INTO pythagorean_triple (side_a, side_b) VALUES (3, 4)")); this.rs=this.stmt.executeQuery("SELECT * FROM pythagorean_triple"); assertTrue(this.rs.next()); assertEquals(3d,this.rs.getDouble(1)); assertEquals(4d,this.rs.getDouble(2)); assertEquals(5d,this.rs.getDouble(3)); assertEquals(5d,this.rs.getDouble(4)); assertEquals(3d,this.rs.getDouble("side_a")); assertEquals(4d,this.rs.getDouble("side_b")); assertEquals(5d,this.rs.getDouble("side_c_sto")); assertEquals(5d,this.rs.getDouble("side_c_vir")); assertFalse(this.rs.next()); for ( String connProps : new String[]{"useInformationSchema=false","useInformationSchema=true"}) { Connection testConn=null; testConn=getConnectionWithProps(connProps); DatabaseMetaData dbmd=testConn.getMetaData(); String test="Case [" + connProps + "]"; this.rs=dbmd.getColumns(null,null,"pythagorean_triple","%"); assertTrue(test,this.rs.next()); assertEquals(test,"side_a",this.rs.getString("COLUMN_NAME")); assertEquals(test,"YES",this.rs.getString("IS_NULLABLE")); assertEquals(test,"NO",this.rs.getString("IS_AUTOINCREMENT")); assertEquals(test,"NO",this.rs.getString("IS_GENERATEDCOLUMN")); assertTrue(test,this.rs.next()); assertEquals(test,"side_b",this.rs.getString("COLUMN_NAME")); assertEquals(test,"YES",this.rs.getString("IS_NULLABLE")); assertEquals(test,"NO",this.rs.getString("IS_AUTOINCREMENT")); assertEquals(test,"NO",this.rs.getString("IS_GENERATEDCOLUMN")); assertTrue(test,this.rs.next()); assertEquals(test,"side_c_vir",this.rs.getString("COLUMN_NAME")); assertEquals(test,"YES",this.rs.getString("IS_NULLABLE")); assertEquals(test,"NO",this.rs.getString("IS_AUTOINCREMENT")); assertEquals(test,"YES",this.rs.getString("IS_GENERATEDCOLUMN")); assertTrue(test,this.rs.next()); assertEquals(test,"side_c_sto",this.rs.getString("COLUMN_NAME")); assertEquals(test,"NO",this.rs.getString("IS_NULLABLE")); assertEquals(test,"NO",this.rs.getString("IS_AUTOINCREMENT")); assertEquals(test,"YES",this.rs.getString("IS_GENERATEDCOLUMN")); assertFalse(test,this.rs.next()); this.rs=dbmd.getPrimaryKeys(null,null,"pythagorean_triple"); assertTrue(test,this.rs.next()); assertEquals(test,"side_c_sto",this.rs.getString("COLUMN_NAME")); assertEquals(test,"PRIMARY",this.rs.getString("PK_NAME")); assertFalse(test,this.rs.next()); this.rs=dbmd.getIndexInfo(null,null,"pythagorean_triple",false,true); assertTrue(test,this.rs.next()); assertEquals(test,"PRIMARY",this.rs.getString("INDEX_NAME")); assertEquals(test,"side_c_sto",this.rs.getString("COLUMN_NAME")); assertTrue(test,this.rs.next()); assertEquals(test,"side_c_sto",this.rs.getString("INDEX_NAME")); assertEquals(test,"side_c_sto",this.rs.getString("COLUMN_NAME")); assertTrue(test,this.rs.next()); assertEquals(test,"side_c_vir",this.rs.getString("INDEX_NAME")); assertEquals(test,"side_c_vir",this.rs.getString("COLUMN_NAME")); assertFalse(test,this.rs.next()); testConn.close(); } }
WL#411 - Generated columns. Test for new syntax and support in DatabaseMetaData.getColumns(). New syntax for CREATE TABLE, introduced in MySQL 5.7.6: -col_name data_type [GENERATED ALWAYS] AS (expression) [VIRTUAL | STORED] [UNIQUE [KEY]] [COMMENT comment] [[NOT] NULL] [[PRIMARY] KEY]
public final String toString(){ return image; }
Returns the image.
public OrientationProvider(SensorManager sensorManager){ this.sensorManager=sensorManager; currentOrientationRotationMatrix=new Matrixf4x4(); currentOrientationQuaternion=new Quaternion(); }
Initialises a new OrientationProvider
public static String substring(String str,int start,int end){ if (str == null) { return null; } if (end < 0) { end=str.length() + end; } if (start < 0) { start=str.length() + start; } if (end > str.length()) { end=str.length(); } if (start > end) { return ""; } if (start < 0) { start=0; } if (end < 0) { end=0; } return str.substring(start,end); }
<p> Gets a substring from the specified String avoiding exceptions. </p> <p/> <p> A negative start position can be used to start/end <code>n</code> characters from the end of the String. </p>
public WalkDistanceEstimator(String root,String studyArea,String version,String percentage){ this.studyArea=studyArea; this.sb=new M2UStringbuilder(root,studyArea,version,percentage); }
Estimates the walk distance to public transport.
protected void invalidateGeometryCache(){ super.invalidateGeometryCache(); geometryBounds=null; primitiveBounds=null; sensitiveBounds=null; outline=null; }
Invalidates the cached geometric bounds. This method is called each time an attribute that affects the bounds of this node changed.
private int mergeMovementsAvailable(){ final AtomicInteger pairsOfMergeableTiles=new AtomicInteger(); int cont=0; Direction direction=Direction.UP; do { for ( Integer x : gridOperator.getTraverseX()) { for ( Integer y : gridOperator.getTraverseY()) { Location thisloc=new Location(x,y); Tile tile=gameGrid.get(thisloc); if (tile != null) { Tile offsetTile=gameGrid.get(thisloc.offset(direction)); if (offsetTile != null && tile.isMergeable(offsetTile)) { pairsOfMergeableTiles.incrementAndGet(); } } } } direction=Direction.LEFT; cont++; } while (cont < 2); return pairsOfMergeableTiles.get(); }
Finds the number of pairs of tiles that can be merged This method is called only when the grid is full of tiles, what makes the use of Optional unnecessary, but it could be used when the board is not full to find the number of pairs of mergeable tiles and provide a hint for the user, for instance
public ChatResponse chat(ChatConfig config){ config.addCredentials(this); String xml=POST(this.url + "/post-chat",config.toXML()); Element root=parse(xml); if (root == null) { return null; } try { ChatResponse response=new ChatResponse(); response.parseXML(root); return response; } catch ( Exception exception) { this.exception=SDKException.parseFailure(exception); throw this.exception; } }
Process the bot chat message and return the bot's response. The ChatConfig should contain the conversation id if part of a conversation. If a new conversation the conversation id is returned in the response.
void calculateCounters(){ if (!isDBAvailable()) return; long time=System.currentTimeMillis(); int total=0; write.lock(); try { countResetFeedsAndCategories(); total+=countFeedsWithUnread(); countCategoriesWithUnread(); countSpecialCategories(total); } finally { write.unlock(); } Log.i(TAG,String.format("Recalculated counters, total unread: %s (took %sms)",total,(System.currentTimeMillis() - time))); }
Set unread counters for feeds and categories according to real amount of unread articles. Split up the tasks in single transactions so we can do other work in between.
private Set<UserDTO> searchPersonUsers(String tenantName,SearchCriteria criteria,int limit) throws Exception { Set<PersonUser> idmPersonUsers=getIDMClient().findPersonUsersByName(tenantName,criteria,limit); return UserMapper.getUserDTOs(idmPersonUsers,false); }
Search person users only with matching criteria
private StatisticsType extractType(Element typeNode,StatisticsTypeFactory statFactory){ Assert.assertTrue(typeNode.getTagName().equals("type")); Assert.assertTrue(typeNode.hasAttribute("name")); final String typeName=typeNode.getAttribute("name"); ArrayList stats=new ArrayList(); NodeList statNodes=typeNode.getElementsByTagName("stat"); for (int i=0; i < statNodes.getLength(); i++) { Element statNode=(Element)statNodes.item(i); stats.add(extractStat(statNode,statFactory)); } StatisticDescriptor[] descriptors=(StatisticDescriptor[])stats.toArray(new StatisticDescriptor[stats.size()]); String description=""; { NodeList descriptionNodes=typeNode.getElementsByTagName("description"); if (descriptionNodes.getLength() > 0) { Element descriptionNode=(Element)descriptionNodes.item(0); if (descriptionNode.getParentNode().getNodeName().equals(typeNode.getNodeName())) { description=extractDescription(descriptionNode); } } } return statFactory.createType(typeName,description,descriptors); }
<!ELEMENT type (description?, (stat)+)> <!ATTLIST type name CDATA #REQUIRED>
@Override public void attributeReplaced(ServletContextAttributeEvent event){ log("attributeReplaced('" + event.getName() + "', '"+ event.getValue()+ "')"); }
Record the fact that a servlet context attribute was replaced.
protected Object convertArray(Object arr){ final int size=Array.getLength(arr); ArrayList list=new ArrayList(size); for (int i=0; i < size; i++) { list.add(Array.get(arr,i)); } return list; }
Converts an array to a java.util.List.
public void addPages(){ page=new UmpleMainClassWizardPage(this,possibilities); addPage(page); }
Adding the page to the wizard.
private MInOut createShipment(MDocType dt,Timestamp movementDate){ log.info("For " + dt); MInOut shipment=new MInOut(this,dt.getC_DocTypeShipment_ID(),movementDate); if (!shipment.save(get_TrxName())) { m_processMsg="Could not create Shipment"; return null; } MOrderLine[] oLines=getLines(true,null); for (int i=0; i < oLines.length; i++) { MOrderLine oLine=oLines[i]; MInOutLine ioLine=new MInOutLine(shipment); BigDecimal MovementQty=oLine.getQtyOrdered().subtract(oLine.getQtyDelivered()); int M_Locator_ID=MStorage.getM_Locator_ID(oLine.getM_Warehouse_ID(),oLine.getM_Product_ID(),oLine.getM_AttributeSetInstance_ID(),MovementQty,get_TrxName()); if (M_Locator_ID == 0) { MWarehouse wh=MWarehouse.get(getCtx(),oLine.getM_Warehouse_ID()); M_Locator_ID=wh.getDefaultLocator().getM_Locator_ID(); } ioLine.setOrderLine(oLine,M_Locator_ID,MovementQty); ioLine.setQty(MovementQty); if (oLine.getQtyEntered().compareTo(oLine.getQtyOrdered()) != 0) ioLine.setQtyEntered(MovementQty.multiply(oLine.getQtyEntered()).divide(oLine.getQtyOrdered(),6,BigDecimal.ROUND_HALF_UP)); if (!ioLine.save(get_TrxName())) { m_processMsg="Could not create Shipment Line"; return null; } } shipment.processIt(DocAction.ACTION_Complete); shipment.saveEx(get_TrxName()); if (!DOCSTATUS_Completed.equals(shipment.getDocStatus())) { m_processMsg="@M_InOut_ID@: " + shipment.getProcessMsg(); return null; } return shipment; }
Create Shipment
private void validateInitiatorsInExportGroup(ExportGroup exportGroup){ if (exportGroup != null && exportGroup.getInitiators() != null) { Initiator initiator=null; boolean isCluster=exportGroup.forCluster(); Map<String,Set<URI>> initiatorMap=new HashMap<>(); Iterator<String> existingInitiatorsIterator=exportGroup.getInitiators().iterator(); List<URI> staleInitiatorList=new ArrayList<>(); URI initiatorURI=null; while (existingInitiatorsIterator.hasNext()) { initiatorURI=URI.create(existingInitiatorsIterator.next()); initiator=_dbClient.queryObject(Initiator.class,initiatorURI); String name=null; if (initiator != null && !initiator.getInactive()) { if (!VPlexControllerUtils.isVplexInitiator(initiator,_dbClient) && !ExportUtils.checkIfInitiatorsForRP(Arrays.asList(initiator))) { if (isCluster && StringUtils.hasText(initiator.getClusterName()) && StringUtils.hasText(initiator.getHostName())) { name=initiator.getClusterName(); } else if (!StringUtils.hasText(initiator.getHostName()) || (isCluster && !StringUtils.hasText(initiator.getClusterName()))) { _log.error("Initiator {} does not have host/cluster name",initiator.getId()); throw APIException.badRequests.invalidInitiatorName(initiator.getId(),exportGroup.getId()); } Set<URI> set=null; if (initiatorMap.get(name) == null) { set=new HashSet<URI>(); initiatorMap.put(name,set); } else { set=initiatorMap.get(name); } set.add(initiator.getId()); } } else { _log.error("Stale initiator URI {} is in ExportGroup and can be removed from ExportGroup{}",initiatorURI,exportGroup.getId()); staleInitiatorList.add(initiatorURI); } } if (!staleInitiatorList.isEmpty()) { exportGroup.removeInitiators(staleInitiatorList); _dbClient.updateObject(exportGroup); _log.info("Stale initiator URIs {} has been removed from from ExportGroup {}",staleInitiatorList,exportGroup.getId()); } _log.info("{}",initiatorMap); if (exportGroup.getType().equals(ExportGroupType.Cluster.name()) && initiatorMap.size() > 1) { _log.error("Export Group {} is having initiators from multiple cluster/host. List of cluster/host names :{}",exportGroup.getId(),Joiner.on(",").join(initiatorMap.keySet())); throw APIException.badRequests.invalidGroupOfInitiators(exportGroup.getId(),Joiner.on(",").join(initiatorMap.keySet())); } } }
Validates the ExportGroup initaitor's identity to avoid DU case. Export Group should not have initiators from multiple Host or clusters.
private void savePhotoIcon(PhotoIcon photoIcon,ContactId contact) throws FileAccessException { byte photoContent[]=photoIcon.getContent(); if (photoContent == null) { return; } Uri photoUri=Uri.withAppendedPath(CONTENT_URI,contact.toString()); OutputStream outstream=null; try { outstream=mLocalContentResolver.openContentOutputStream(photoUri); outstream.write(photoContent); outstream.flush(); } catch ( IOException e) { throw new FileAccessException("Failed to save photo icon for contact : " + contact,e); } finally { CloseableUtils.tryToClose(outstream); } }
Save photo icon
private void checkChildCount(){ if (getChildCount() != 1) { throw new IllegalStateException(getResources().getString(R.string.child_count_error)); } }
FABProgressCircle will get its dimensions depending on its child dimensions. It will be easier to force proper graphic standards for the button if we can get sure that only one child is present. Every FAB library around has a single root layout, so it should not be an issue.
public boolean isControlledBy(Control control){ Assert.isNotNull(control); boolean contains=controls.contains(control); if (!contains && control instanceof Composite) { Control[] children=((Composite)control).getChildren(); for (int i=0; i < children.length; i++) { contains=isControlledBy(children[i]); if (contains) { return true; } } } return contains; }
Tests if the control belongs to the part, providing a deep search for SWT composites
public String toString(){ return super.toString() + ":" + getObject(); }
Generates the string representation of this binding. The string representation consists of the string representation of the name/class pair and the string representation of this binding's object, separated by ':'. The contents of this string is useful for debugging and is not meant to be interpreted programmatically.
public void testInOutParams() throws Exception { if (versionMeetsMinimum(5,0)) { CallableStatement storedProc=null; createProcedure("testInOutParam","(IN p1 VARCHAR(255), INOUT p2 INT)\nbegin\n DECLARE z INT;\nSET z = p2 + 1;\nSET p2 = z;\n" + "SELECT p1;\nSELECT CONCAT('zyxw', p1);\nend\n"); storedProc=this.conn.prepareCall("{call testInOutParam(?, ?)}"); storedProc.setString(1,"abcd"); storedProc.setInt(2,4); storedProc.registerOutParameter(2,Types.INTEGER); storedProc.execute(); assertEquals(5,storedProc.getInt(2)); } }
Tests functioning of inout parameters
public <AE extends LayoutType>GenPrimArray1D(Class<?> elementInterfaceClass,Class<AE> userDefinedArrayClass){ arrayImplClassName=ImplHelper.getImplClassName(userDefinedArrayClass); arrayInterfaceClassName=userDefinedArrayClass.getName().replace('.','/'); this.elementInterfaceClass=elementInterfaceClass; dbgPrintNames(); }
Instantiate GenPrimArray1D for user defined array class
private void layoutForm(){ m_columnCount=0; if (m_data == null) return; for (int row=0; row < m_data.getRowCount(); row++) { log.info("Row=" + row); m_data.setRowIndex(row); boolean somethingPrinted=true; for (int i=0; i < m_format.getItemCount(); i++) { MPrintFormatItem item=m_format.getItem(i); if (!item.isPrinted()) continue; m_columnCount++; if (row > 0 && (item.isHeader() || item.isFooter())) continue; if (item.isHeader()) setArea(AREA_HEADER); else if (item.isFooter()) setArea(AREA_FOOTER); else setArea(AREA_CONTENT); if (item.isSetNLPosition() && item.isRelativePosition()) m_tempNLPositon=0; if (item.isNextLine() && somethingPrinted) { newLine(); somethingPrinted=false; } else { addX(m_lastWidth[m_area]); } if (item.isNextPage()) { newPage(false,false); } if (item.isRelativePosition()) { addX(item.getXSpace()); addY(item.getYSpace()); } else setRelativePosition(item.getXPosition(),item.getYPosition()); if (item.isSetNLPosition() && !item.isRelativePosition()) m_tempNLPositon=(int)getPosition().getX(); String alignment=item.getFieldAlignmentType(); int maxWidth=item.getMaxWidth(); boolean lineAligned=false; if (item.isRelativePosition()) { if (item.isLineAlignLeading()) { alignment=MPrintFormatItem.FIELDALIGNMENTTYPE_LeadingLeft; maxWidth=getAreaBounds().width; lineAligned=true; } else if (item.isLineAlignCenter()) { alignment=MPrintFormatItem.FIELDALIGNMENTTYPE_Center; maxWidth=getAreaBounds().width; lineAligned=true; } else if (item.isLineAlignTrailing()) { alignment=MPrintFormatItem.FIELDALIGNMENTTYPE_TrailingRight; maxWidth=getAreaBounds().width; lineAligned=true; } } PrintElement element=null; if (item.isTypePrintFormat()) { element=includeFormat(item,m_data); } else if (item.isBarcode()) { element=createBarcodeElement(item); if (element != null) { element.layout(maxWidth,item.getMaxHeight(),false,alignment); } } else if (item.isTypeImage()) { if (item.isImageField()) element=createImageElement(item); else if (item.isImageIsAttached()) element=ImageElement.get(item.get_ID()); else element=ImageElement.get(item.getImageURL()); if (element != null) element.layout(maxWidth,item.getMaxHeight(),false,alignment); } else if (item.isTypeField()) { if (maxWidth == 0 && item.isFieldAlignBlock()) maxWidth=getAreaBounds().width; element=createFieldElement(item,maxWidth,alignment,m_format.isForm()); } else if (item.isTypeBox()) { if (m_format.isForm()) element=createBoxElement(item); if (element != null && maxWidth == 0) { maxWidth=getAreaBounds().width; element.setMaxWidth(maxWidth); } } else { if (maxWidth == 0 && item.isFieldAlignBlock()) maxWidth=getAreaBounds().width; element=createStringElement(item.getPrintName(m_format.getLanguage()),item.getAD_PrintColor_ID(),item.getAD_PrintFont_ID(),maxWidth,item.getMaxHeight(),item.isHeightOneLine(),alignment,true); } if (element != null) { somethingPrinted=true; if (!lineAligned) m_lastWidth[m_area]=element.getWidth(); m_lastHeight[m_area]=element.getHeight(); } else { somethingPrinted=false; m_lastWidth[m_area]=0f; m_lastHeight[m_area]=0f; if (item.isRelativePosition()) { addX(-item.getXSpace()); addY(-item.getYSpace()); } } if (item.isRelativePosition() && !lineAligned) { if (!isXspaceFor(m_lastWidth[m_area])) { log.finest("Not enough X space for " + m_lastWidth[m_area] + " - remaining "+ getXspace()+ " - Area="+ m_area); newLine(); } if (m_area == AREA_CONTENT && !isYspaceFor(m_lastHeight[m_area])) { log.finest("Not enough Y space " + m_lastHeight[m_area] + " - remaining "+ getYspace()+ " - Area="+ m_area); newPage(true,true); } } if (element != null) element.setLocation(m_position[m_area]); if (m_area == AREA_CONTENT) m_currPage.addElement(element); else m_headerFooter.addElement(element); if (m_lastHeight[m_area] > m_maxHeightSinceNewLine[m_area]) m_maxHeightSinceNewLine[m_area]=m_lastHeight[m_area]; if (!item.isRelativePosition()) m_maxHeightSinceNewLine[m_area]=m_lastHeight[m_area]; } } }
Layout Form. For every Row, loop through the Format and calculate element size and position.
@Override public Object eGet(int featureID,boolean resolve,boolean coreType){ switch (featureID) { case ExpressionsPackage.LOGICAL_AND_EXPRESSION__LEFT_OPERAND: return getLeftOperand(); case ExpressionsPackage.LOGICAL_AND_EXPRESSION__RIGHT_OPERAND: return getRightOperand(); } return super.eGet(featureID,resolve,coreType); }
<!-- begin-user-doc --> <!-- end-user-doc -->
public static int compareTo(Vector2 a,Vector2 b){ return (int)a.lengthSquared() - (int)b.lengthSquared(); }
Compares two Vector3s
protected void clearConstraints(){ this.constraints=new ConstraintSet(); }
Remove all constraints from this type application, to be used only after all are satisfied.
public EventExpressionConfigAttribute(Expression authorizeExpression){ Assert.notNull(authorizeExpression,"authorizeExpression cannot be null"); this.authorizeExpression=authorizeExpression; }
Creates a new instance
public Builder add(String line){ int index=line.indexOf(":"); if (index == -1) { throw new IllegalArgumentException("Unexpected header: " + line); } return add(line.substring(0,index).trim(),line.substring(index + 1)); }
Add an header line containing a field name, a literal colon, and a value.
static public void assertNull(String message,Object object){ assertTrue(message,object == null); }
Asserts that an object is null. If it is not an AssertionFailedError is thrown with the given message.
@Override public void onDestroy(){ super.onDestroy(); mActiveListItemAdapter.cleanup(); mCurrentListRef.removeEventListener(mCurrentListRefListener); mCurrentUserRef.removeEventListener(mCurrentUserRefListener); mSharedWithRef.removeEventListener(mSharedWithListener); }
Cleanup when the activity is destroyed.
public static String map2TypeForDBMS(String type){ if (type.contains("DATABASE LINK")) return "DB_LINK"; if (type.equals("JOB")) return "PROCOBJ"; if (type.equals("SCHEDULE")) return "PROCOBJ"; if (type.equals("PROGRAM")) return "PROCOBJ"; if (type.equals("PACKAGE")) return "PACKAGE_SPEC"; return type.replace(" ","_"); }
Oracle types in user_table without underscore, for example PACKAGE BODY but in DBMS_METADATA with underscore PACKAGE_BODY
public Object[] values(){ Object[] values=new Object[this.size()]; Entry[] table=this.table; int i=0; for (int bucket=0; bucket < table.length; bucket++) { for (Entry e=table[bucket]; e != null; e=e.next) { values[i++]=e.value; } } return values; }
Returns all of the objects in the map
@SuppressWarnings("deprecation") public static Position limitCenterPosition(Position position,OrbitViewLimits viewLimits){ if (position == null) { String message=Logging.getMessage("nullValue.PositionIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } if (viewLimits == null) { String message=Logging.getMessage("nullValue.ViewLimitsIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } return new Position(limitCenterLocation(position.getLatitude(),position.getLongitude(),viewLimits),limitCenterElevation(position.getElevation(),viewLimits)); }
Clamp center location angles and elevation to the range specified in a limit object.
public PassportDecoder(DecodeConfiguration config,AliasList aliasList){ mPassportFSKDecoder=new LTRFSKDecoder(); mPassportMessageFramer=new MessageFramer(SyncPattern.PASSPORT.getPattern(),PASSPORT_MESSAGE_LENGTH); mPassportFSKDecoder.addListener(mPassportMessageFramer); mPassportMessageProcessor=new PassportMessageProcessor(aliasList); mPassportMessageFramer.addMessageListener(mPassportMessageProcessor); mPassportMessageProcessor.setMessageListener(this); }
Passport Decoder. Decodes unfiltered (e.g. demodulated but with no DC or audio filtering) samples and produces Passport messages.
public PropertyMutation transitionWorkFlow(final PropertyMutation propertyMutation){ final DateTime currentDate=new DateTime(); final String approverComments="Property has been successfully forwarded."; final Assignment assignment=propertyService.getAssignmentsForDesignation(PropertyTaxConstants.COMMISSIONER_DESGN).get(0); final Position pos=assignment.getPosition(); propertyMutation.transition().start().withSenderName("anonymous user").withComments(approverComments).withStateValue(PropertyTaxConstants.WF_STATE_REVENUE_OFFICER_APPROVED).withDateInfo(currentDate.toDate()).withOwner(pos).withNextAction(PropertyTaxConstants.WF_STATE_COMMISSIONER_APPROVAL_PENDING).withNatureOfTask(NATURE_TITLE_TRANSFER); return propertyMutation; }
Used in REST API for initiating property transfer
public static void populatePkcs10UnstructuredName(Attribute[] attributes,JTextField textField){ ASN1ObjectIdentifier pkcs9UnstructureName=PKCSObjectIdentifiers.pkcs_9_at_unstructuredName; populateTextField(attributes,textField,pkcs9UnstructureName); }
Populates a JTextField with PKCS#10/#9 unstructuredName
private String buildCreateStatement(String tableName,String[] columnNames,String[] columnTypes){ String createStatement=""; if (columnNames.length == columnTypes.length) { createStatement+="CREATE TABLE IF NOT EXISTS " + tableName + "("+ _ID+ " INTEGER PRIMARY KEY, "; for (int i=0; i < columnNames.length; i++) { if (i == columnNames.length - 1) { createStatement+=columnNames[i] + " " + columnTypes[i]+ ")"; } else { createStatement+=columnNames[i] + " " + columnTypes[i]+ ", "; } } } return createStatement; }
Constructs a fully formed CREATE statement using the input parameters.
private static void link(final ITreeNode<CTag> parent,final ITreeNode<CTag> child){ child.setParent(parent); parent.addChild(child); }
Connects a parent node with a child node.
private void detach(){ if (prevTakeIndex >= 0) { prevTakeIndex=DETACHED; itrs.doSomeSweeping(true); } }
Called when itrs should stop tracking this iterator, either because there are no more indices to update (cursor < 0 && nextIndex < 0 && lastRet < 0) or as a special exception, when lastRet >= 0, because hasNext() is about to return false for the first time. Call only from iterating thread.
public LocVars(LuaString varname,int startpc,int endpc){ this.varname=varname; this.startpc=startpc; this.endpc=endpc; }
Construct a LocVars instance.
public void testMinGreaterThanMax(){ Document doc=new Document(); IllegalArgumentException expected; expected=expectThrows(IllegalArgumentException.class,null); assertTrue(expected.getMessage().contains("is greater than max value")); }
min cannot be greater than max
public EGLSurface createWindowSurface(Object surface){ if (!(surface instanceof Surface) && !(surface instanceof SurfaceTexture)) { throw new RuntimeException("invalid surface: " + surface); } int[] surfaceAttribs={EGL14.EGL_NONE}; EGLSurface eglSurface=EGL14.eglCreateWindowSurface(mEGLDisplay,mEGLConfig,surface,surfaceAttribs,0); checkEglError("eglCreateWindowSurface"); if (eglSurface == null) { throw new RuntimeException("surface was null"); } return eglSurface; }
Creates an EGL surface associated with a Surface. <p> If this is destined for MediaCodec, the EGLConfig should have the "recordable" attribute.
protected Block createLegendItemBlock(LegendItem item){ BlockContainer result; LegendGraphic lg=new LegendGraphic(item.getShape(),item.getFillPaint()); lg.setFillPaintTransformer(item.getFillPaintTransformer()); lg.setShapeFilled(item.isShapeFilled()); lg.setLine(item.getLine()); lg.setLineStroke(item.getLineStroke()); lg.setLinePaint(item.getLinePaint()); lg.setLineVisible(item.isLineVisible()); lg.setShapeVisible(item.isShapeVisible()); lg.setShapeOutlineVisible(item.isShapeOutlineVisible()); lg.setOutlinePaint(item.getOutlinePaint()); lg.setOutlineStroke(item.getOutlineStroke()); lg.setPadding(this.legendItemGraphicPadding); LegendItemBlockContainer legendItem=new LegendItemBlockContainer(new BorderArrangement(),item.getDataset(),item.getSeriesKey()); lg.setShapeAnchor(getLegendItemGraphicAnchor()); lg.setShapeLocation(getLegendItemGraphicLocation()); legendItem.add(lg,this.legendItemGraphicEdge); Font textFont=item.getLabelFont(); if (textFont == null) { textFont=this.itemFont; } Paint textPaint=item.getLabelPaint(); if (textPaint == null) { textPaint=this.itemPaint; } LabelBlock labelBlock=new LabelBlock(item.getLabel(),textFont,textPaint); labelBlock.setPadding(this.itemLabelPadding); legendItem.add(labelBlock); legendItem.setToolTipText(item.getToolTipText()); legendItem.setURLText(item.getURLText()); result=new BlockContainer(new CenterArrangement()); result.add(legendItem); return result; }
Creates a legend item block.
public boolean isSendInstallEvent(){ return mSendInstallEvent; }
Whether or not we are telling the server about a new install. False indicates a ping/updatecheck.
public AbstractWildFlyScriptCommand(Configuration configuration,String resourcePath){ super(configuration,resourcePath); }
Sets configuration containing all needed information for building configuration scripts.
public void mSelectedDateInfo(int position){ RWeekCalendar.getInstance().getSelectedDate(dateInWeekArray.get(position)); mSelectedDate=dateInWeekArray.get(position); AppController.getInstance().setSelected(mSelectedDate); }
Passing the selected date info
@Deprecated protected final Class<?> defineClass(byte[] classRep,int offset,int length) throws ClassFormatError { throw new UnsupportedOperationException("can't load this type of class file"); }
Constructs a new class from an array of bytes containing a class definition in class file format.
public void start(){ _log.info("WorkflowService starting up"); _instance=this; try { _dataManager=_coordinator.getWorkflowDataManager(); _dataManager.setConnectionStateListener(_connectionStateListener); } catch ( Exception ex) { _log.error("Can't get a DistributedDataManager",ex); } if (!scrubberStarted) { getScrubber().start(); scrubberStarted=true; } }
Start the service.
public static GdsTypeRule excludesNativeOnly(){ return excludes(NativeGDSFactoryPlugin.NATIVE_TYPE_NAME,EmbeddedGDSFactoryPlugin.EMBEDDED_TYPE_NAME,LocalGDSFactoryPlugin.LOCAL_TYPE_NAME); }
Creates an instance that excludes all (known) native test types.
private void validateBusinessObjectDefinitionUpdateRequest(BusinessObjectDefinitionUpdateRequest request){ if (request.getDisplayName() != null) { request.setDisplayName(request.getDisplayName().trim()); } attributeHelper.validateAttributes(request.getAttributes()); }
Validates the business object definition update request. This method also trims request parameters.
private static Object unwrap(Object object){ if (object instanceof SuperReflect) { return ((SuperReflect)object).get(); } return object; }
Unwrap an object
void notifySlaveAvailability(SlaveConnection slave,final Job job,EvolutionState state){ synchronized (allSlaves) { notifyMonitor(allSlaves); } if (slave.numJobs() < maxJobsPerSlave) { synchronized (availableSlaves) { if (!availableSlaves.contains(slave)) availableSlaves.addLast(slave); notifyMonitor(availableSlaves); } } debug("Notify the monitor that the slave is available."); if (state instanceof ec.steadystate.SteadyStateEvolutionState) { synchronized (evaluatedIndividuals) { for (int x=0; x < job.inds.length; x++) evaluatedIndividuals.addLast(new QueueIndividual(job.inds[x],job.subPops[x])); notifyMonitor(evaluatedIndividuals); } } }
Notifies the monitor that the particular slave has finished performing a job, and it (probably) is available for other jobs.
public static MonoReilSolverResult<RegisterSetLatticeElement> track(final ReilFunction function,final IInstruction startInstruction,final String trackedRegister,final RegisterTrackingOptions options){ Preconditions.checkNotNull(function,"Error: function argument can not be null"); Preconditions.checkNotNull(startInstruction,"Error: startInstruction argument can not be null"); Preconditions.checkNotNull(trackedRegister,"Error: trackedRegister argument can not be null"); Preconditions.checkNotNull(options,"Error: options argument can not be null"); final CReilInstructionGraph instructionGraph=new CReilInstructionGraph(function.getGraph()); final RegisterSetLatticeElement registerSetLatticeElement=new RegisterSetLatticeElement(trackedRegister); final MonoReilSolver<RegisterSetLatticeElement> monoReilSolver=new MonoReilSolver<RegisterSetLatticeElement>(instructionGraph,options.getAnalysisDirection(),new RegisterSetLattice()); final Iterable<IInstructionGraphEdge> relevantEdges=options.trackIncoming() ? instructionGraph.getIncomingEdgesForAddress(startInstruction.getAddress()) : instructionGraph.getOutgoingEdgesForAddress(startInstruction.getAddress()); final List<Pair<IInstructionGraphEdge,RegisterSetLatticeElement>> initialState=new ArrayList<Pair<IInstructionGraphEdge,RegisterSetLatticeElement>>(); for ( final IInstructionGraphEdge currentRelevantEdge : relevantEdges) { initialState.add(new Pair<IInstructionGraphEdge,RegisterSetLatticeElement>(currentRelevantEdge,registerSetLatticeElement)); } final ITransformationProvider<RegisterSetLatticeElement> transformationProvider=new RegisterTrackingTransformationProvider(options); final MonoReilSolverResult<RegisterSetLatticeElement> solverResult=monoReilSolver.solve(transformationProvider,initialState,Integer.MAX_VALUE); return solverResult; }
Function to do register tracking.
private void snapVertices(CoordinateList srcCoords,Coordinate[] snapPts){ int end=isClosed ? srcCoords.size() - 1 : srcCoords.size(); for (int i=0; i < end; i++) { Coordinate srcPt=(Coordinate)srcCoords.get(i); Coordinate snapVert=findSnapForVertex(srcPt,snapPts); if (snapVert != null) { srcCoords.set(i,new Coordinate(snapVert)); if (i == 0 && isClosed) srcCoords.set(srcCoords.size() - 1,new Coordinate(snapVert)); } } }
Snap source vertices to vertices in the target.
public Encoding(String name){ this.name=name; }
Constructs a new encoding.
protected void appendContentStart(final StringBuffer buffer){ buffer.append(contentStart); }
<p>Append to the <code>toString</code> the content start.</p>
public boolean isOKpressed(){ return m_okPressed; }
Did the user press OK
public Tween targetRelative(float... targetValues){ if (targetValues.length > combinedAttrsLimit) throwCombinedAttrsLimitReached(); for (int i=0; i < targetValues.length; i++) { this.targetValues[i]=isInitialized() ? targetValues[i] + startValues[i] : targetValues[i]; } isRelative=true; return this; }
Sets the target values of the interpolation, relatively to the <b>values at start time (after the delay, if any)</b>. <p/> To sum-up:<br/> - start values: values at start time, after delay<br/> - end values: params + values at start time, after delay
private Explanation(boolean match,float value,String description,Collection<Explanation> details){ this.match=match; this.value=value; this.description=Objects.requireNonNull(description); this.details=Collections.unmodifiableList(new ArrayList<>(details)); for ( Explanation detail : details) { Objects.requireNonNull(detail); } }
Create a new explanation
public void animate(float progress){ if (mPathMeasure == null) { return; } mProgress=progress; int stopD=(int)(mLength * mProgress); mSegmentPath.reset(); mPathMeasure.getSegment(0,stopD,mSegmentPath,true); mSegmentPath.rLineTo(0.0f,0.0f); mPathMeasure.getPosTan(stopD,mPlaneCoordinate,mPlaneAngle); invalidate(); }
Update path segment and the position/angle of the paper plane based on the progress given.
public static List<NameValuePair> parseQueryOrdered(String query) throws URISyntaxException { List<NameValuePair> parameters=new ArrayList<NameValuePair>(); if (query == null) { return parameters; } URIQueryTokenizer uqt=new URIQueryTokenizer(query); while (uqt.hasMoreTokens()) { String token=uqt.nextToken(); int index=token.indexOf(URI.PARAMETER_SEPARATOR); String name; String value; if (index != -1) { name=token.substring(0,index); value=token.substring(index + 1); } else { name=token; value=null; } parameters.add(new NameValuePair(name,value)); } return parameters; }
Parse a URI query string, returning a list of Name/Value pairs in the order they occur in the query and keeping duplicates.
public static Object[] buildValueArray(ParsedSql parsedSql,Map<String,?> paramSource){ List<Object> paramArray=new ArrayList<Object>(); if (parsedSql.getNamedParameterCount() > 0 && parsedSql.getUnnamedParameterCount() > 0) { throw new IllegalStateException("You can't mix named and traditional ? placeholders. You have " + parsedSql.getNamedParameterCount() + " named parameter(s) and "+ parsedSql.getUnnamedParameterCount()+ " traditonal placeholder(s) in ["+ parsedSql.getOriginalSql()+ "]"); } List<String> paramNames=parsedSql.getParameterNames(); for (int i=0; i < paramNames.size(); i++) { String paramName=paramNames.get(i); Object value=paramSource.get(paramName); if (value instanceof Collection<?>) { Collection<?> collection=(Collection<?>)value; for ( Object object : collection) { paramArray.add(object); } } else { paramArray.add(value); } } return paramArray.toArray(new Object[paramArray.size()]); }
Convert a Map of named parameter values to a corresponding array.
protected void assertNoRecordsToConsume(){ assertThat(consumedLines.isEmpty()).isTrue(); }
Assert that there are no records to consume.
public void assertEqual(Object expected,Object actual,String errorMessage){ TestUtils.assertEqual(expected,actual,errorMessage); }
This method just invokes the test utils method, it is here for convenience
public static boolean isPacked(TextEdit edit){ if (!(edit instanceof MultiTextEdit)) return true; if (!edit.hasChildren()) return true; TextEdit[] children=edit.getChildren(); if (edit.getOffset() != children[0].getOffset()) return false; if (edit.getExclusiveEnd() != children[children.length - 1].getExclusiveEnd()) return false; for (int i=0; i < children.length; i++) { if (!isPacked(children[i])) return false; } return true; }
Returns true if the given <code>edit</code> is minimal. <p> That is if: <ul> <li><b>true</b> if <code>edit</code> is a leaf</li> <li>if <code>edit</code> is a inner node then <b>true</b> if <ul> <li><code>edit</code> has same size as all its children</li> <li><code>isPacked</code> is <b>true</b> for all children</li> </ul> </li> </ul> </p>