code
stringlengths
10
174k
nl
stringlengths
3
129k
@Override public String toString(){ StringBuffer text=new StringBuffer(); if (m_trainInstances == null) { text.append("CFS subset evaluator has not been built yet\n"); } else { text.append("\tCFS Subset Evaluator\n"); if (m_missingSeparate) { text.append("\tTreating missing values as a separate value\n"); } if (m_locallyPredictive) { text.append("\tIncluding locally predictive attributes\n"); } } return text.toString(); }
returns a string describing CFS
private void unwrapData() throws IgniteCheckedException, SSLException { if (log.isDebugEnabled()) log.debug("Unwrapping received data: " + ses); inNetBuf.flip(); SSLEngineResult res=unwrap0(); inNetBuf.compact(); checkStatus(res); renegotiateIfNeeded(res); }
Unwraps user data to the application buffer.
public static ceylon.language.meta.declaration.Module findLoadedModule(String name,String version){ com.redhat.ceylon.model.typechecker.model.Module module=moduleManager.findLoadedModule(name,version); return module != null ? getOrCreateMetamodel(null,module,null,true) : null; }
Used by c.l.meta.modules.find, which accepts null
public void endBoolean(boolean value){ }
Indicates the end of a boolean literal (<code>true</code> or <code>false</code>) in the JSON input. This method will be called after reading the last character of the literal.
public static Organization toVendor(VOOrganization voOrganization) throws ValidationException { validateVendorMandatoryFields(voOrganization); return toCustomer(voOrganization); }
Updates the fields in the Supplier or Technology Provider Organization object to reflect the changes performed in the value object. Creates a new Vendor Organization (Supplier or Technology Provider) object and fills the fields with the corresponding fields from the given value object. For vendors, email contact, phone, url, name and address are mandatory; for customers not.
public UnaryOperator createUnaryOperatorFromString(EDataType eDataType,String initialValue){ UnaryOperator result=UnaryOperator.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '"+ eDataType.getName()+ "'"); return result; }
<!-- begin-user-doc --> <!-- end-user-doc -->
@Override public final void updateCursorBoxOnScreen(final int[] rectParams,final int outlineColor){ if (options.getDisplayView() != Display.SINGLE_PAGE) { return; } pages.updateCursorBoxOnScreen(rectParams,outlineColor,getPageNumber(),x_size,y_size); }
update rectangle we draw to highlight an area - See Viewer example for example code showing current usage. This method takes an int array containing the x,y,w,h params of the rectangle we wish to update. It also takes an int outLineColor which is the rgb value of a Color object.
public boolean isCritical(){ return criticality; }
Determines the control's criticality.
public JCTree.JCCompilationUnit parse(JavaFileObject filename){ JavaFileObject prev=log.useSource(filename); try { JCTree.JCCompilationUnit t=parse(filename,readSource(filename)); if (t.endPositions != null) log.setEndPosTable(filename,t.endPositions); return t; } finally { log.useSource(prev); } }
Parse contents of file.
public static double[] toDoubleArray(final long[] array){ double[] values=new double[array.length]; for (int i=0; i < array.length; i++) values[i]=array[i]; return values; }
Converts an array of long primitives to an array of doubles.
@Override public String convertToString(EDataType eDataType,Object instanceValue){ switch (eDataType.getClassifierID()) { case DomPackage.TAG_DEFINITION: return convertTagDefinitionToString(eDataType,instanceValue); default : throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier"); } }
<!-- begin-user-doc --> <!-- end-user-doc -->
public CSVWriter(Writer writer,char separator,char quotechar){ this(writer,separator,quotechar,DEFAULT_ESCAPE_CHARACTER); }
Constructs CSVWriter with supplied separator and quote char.
String formatRomanDigit(int level,int digit){ String result=""; if (digit == 9) { result=result + romanChars[level][0]; result=result + romanChars[level + 1][0]; return result; } else if (digit == 4) { result=result + romanChars[level][0]; result=result + romanChars[level][1]; return result; } else if (digit >= 5) { result=result + romanChars[level][1]; digit-=5; } for (int i=0; i < digit; i++) { result=result + romanChars[level][0]; } return result; }
Converts the item number into a roman numeral
public CProjectContainer(final IDatabase database,final INaviProject project){ m_database=Preconditions.checkNotNull(database,"IE01785: database argument can not be null"); m_project=Preconditions.checkNotNull(project,"IE01786: project argument can not be null"); m_addressSpace=null; m_provider=new ProjectTraceProvider(m_project); m_debuggerProvider=new DebuggerProvider(new ProjectTargetSettings(m_project)); if (m_project.isLoaded()) { updateProjectDebuggers(); } m_project.addListener(m_listener); if (m_project.isLoaded()) { for ( final INaviAddressSpace addressSpace : m_project.getContent().getAddressSpaces()) { initializeAddressSpaceListeners(addressSpace); } } }
Creates a new project container object.
public VNXeCommandResult createConsistencyGroup(ConsistencyGroupCreateParam createParam){ _url=URL_CREATE; return postRequestSync(createParam); }
Create consistency group
public static String doThrustCheck(MovePath md,Client client){ StringBuffer nagReport=new StringBuffer(); List<TargetRoll> psrList=new ArrayList<TargetRoll>(); if (client.getGame().useVectorMove()) { return nagReport.toString(); } final Entity entity=md.getEntity(); if (!(entity instanceof Aero)) { return nagReport.toString(); } EntityMovementType overallMoveType=EntityMovementType.MOVE_NONE; Aero a=(Aero)entity; PilotingRollData rollTarget; overallMoveType=md.getLastStepMovementType(); int thrustUsed=0; int j=0; for (final Enumeration<MoveStep> i=md.getSteps(); i.hasMoreElements(); ) { final MoveStep step=i.nextElement(); j++; if ((step.getDistance() == 0) && (md.length() != j)) { thrustUsed+=step.getMp(); } else { if ((step.getDistance() == 0) && (md.length() == j)) { thrustUsed+=step.getMp(); } rollTarget=a.checkThrustSI(thrustUsed,overallMoveType); checkNag(rollTarget,nagReport,psrList); int hits=entity.getCrew().getHits(); int health=6 - hits; if (thrustUsed > (2 * health)) { int targetroll=2 + (thrustUsed - (2 * health)) + (2 * hits); nagReport.append(Messages.getString("MovementDisplay.addNag",new Object[]{Integer.toString(targetroll),"Thrust exceeded twice pilot's health in single hex"})); } thrustUsed=0; } } return nagReport.toString(); }
Checks to see if piloting skill rolls are needed for excessive use of thrust.
public IterationWrapper(Iteration<? extends E,? extends X> iter){ assert iter != null; wrappedIter=iter; }
Creates a new IterationWrapper that operates on the supplied Iteration.
public void testReservePassiveAvailabilityChange() throws Throwable { createServers(3); CopycatServer passive=createServer(nextMember(Member.Type.PASSIVE)); passive.join(members.stream().map(null).collect(Collectors.toList())).thenRun(null); CopycatServer reserve=createServer(nextMember(Member.Type.RESERVE)); reserve.join(members.stream().map(null).collect(Collectors.toList())).thenRun(null); await(10000,2); reserve.cluster().member(passive.cluster().member().address()).onStatusChange(null); passive.shutdown().thenRun(null); await(10000,2); }
Tests detecting an availability change of a passive member on a reserve member.
public void stop(){ if (isRunning()) { unscheduleSelf(this); } }
<p>Stops the animation. This method has no effect if the animation is not running.</p>
public double slopeStdErr(){ return Math.sqrt(svar1); }
Returns the standard error of the estimate for the slope.
private static XYDataset createDataset(){ TimeSeries s1=new TimeSeries("L&G European Index Trust"); s1.add(new Month(2,2001),181.8); s1.add(new Month(3,2001),167.3); s1.add(new Month(4,2001),153.8); s1.add(new Month(5,2001),167.6); s1.add(new Month(6,2001),158.8); s1.add(new Month(7,2001),148.3); s1.add(new Month(8,2001),153.9); s1.add(new Month(9,2001),142.7); s1.add(new Month(10,2001),123.2); s1.add(new Month(11,2001),131.8); s1.add(new Month(12,2001),139.6); s1.add(new Month(1,2002),142.9); s1.add(new Month(2,2002),138.7); s1.add(new Month(3,2002),137.3); s1.add(new Month(4,2002),143.9); s1.add(new Month(5,2002),139.8); s1.add(new Month(6,2002),137.0); s1.add(new Month(7,2002),132.8); TimeSeries s2=new TimeSeries("L&G UK Index Trust"); s2.add(new Month(2,2001),129.6); s2.add(new Month(3,2001),123.2); s2.add(new Month(4,2001),117.2); s2.add(new Month(5,2001),124.1); s2.add(new Month(6,2001),122.6); s2.add(new Month(7,2001),119.2); s2.add(new Month(8,2001),116.5); s2.add(new Month(9,2001),112.7); s2.add(new Month(10,2001),101.5); s2.add(new Month(11,2001),106.1); s2.add(new Month(12,2001),110.3); s2.add(new Month(1,2002),111.7); s2.add(new Month(2,2002),111.0); s2.add(new Month(3,2002),109.6); s2.add(new Month(4,2002),113.2); s2.add(new Month(5,2002),111.6); s2.add(new Month(6,2002),108.8); s2.add(new Month(7,2002),101.6); TimeSeriesCollection dataset=new TimeSeriesCollection(); dataset.addSeries(s1); dataset.addSeries(s2); return dataset; }
Creates a dataset, consisting of two series of monthly data.
public void globalInit() throws Exception { computeRotationTime(); InterProcessLock lock=null; try { lock=_coordinator.getLock(DISTRIBUTED_KEY_TOKEN_LOCK); lock.acquire(); if (!doesConfigExist()) { TokenKeysBundle bundle=TokenKeysBundle.createNewTokenKeysBundle(); createOrUpdateBundle(bundle); updateCachedTokenKeys(bundle); } else { updateCachedKeys(); _log.debug("Token keys configuration exists, loaded keys"); _log.debug("Current token key {}",_cachedTokenKeysBundle.getCurrentKeyEntry()); } keyRotationExecutor.scheduleWithFixedDelay(new KeyRotationThread(),0,_keyRotationIntervalInMsecs,TimeUnit.MILLISECONDS); } catch ( Exception ex) { _log.error("Exception during initialization of TokenKeyGenerator",ex); } finally { try { if (lock != null) { lock.release(); } } catch ( Exception ex) { _log.error("Could not release the lock during TokenKeyGenerator.init()"); throw ex; } } }
Initialization method to be called by authsvc. It will create the key configuration if it doesn't exist on first startup. Else it will just load the cache.
public Builder addInClause(String fieldName,Collection<String> itemNames,Occurance occurance){ if (itemNames.size() == 1) { return addFieldClause(fieldName,itemNames.iterator().next(),occurance); } Query.Builder inClause=Query.Builder.create(occurance); for ( String itemName : itemNames) { inClause.addFieldClause(fieldName,itemName,Occurance.SHOULD_OCCUR); } return addClause(inClause.build()); }
Add a clause with the given occurance which matches a property with at least one of several specified values (analogous to a SQL "IN" or "NOT IN" statements).
private void injectForBroadcastReceiver(SootField brField,SootField intentField){ SootMethod onReceive=Scene.v().getMethod("<android.content.BroadcastReceiver: void onReceive(android.content.Context,android.content.Intent)>"); logger.info("Adding onReceive call in Harness for Field {}",brField); Local compLocal=Jimple.v().newLocal("_$injectinterapp_comp_local_" + localID++,brField.getType()); Harness.v().addLocalToMain(compLocal); Local intentLocal=Jimple.v().newLocal("_$injectinterapp_intent_local_" + localID++,intentField.getType()); Harness.v().addLocalToMain(intentLocal); Stmt compLocalAssign=Jimple.v().newAssignStmt(compLocal,Jimple.v().newStaticFieldRef(brField.makeRef())); Harness.v().addStmtToEndOfMainLoop(compLocalAssign); Stmt intentAssign=Jimple.v().newAssignStmt(intentLocal,Jimple.v().newStaticFieldRef(intentField.makeRef())); Harness.v().addStmtToEndOfMainLoop(intentAssign); Local contextLocal=Jimple.v().newLocal("_$injectinterapp_content_local_" + localID++,intentField.getType()); Harness.v().addLocalToMain(contextLocal); SootField contextField=Scene.v().getSootClass("droidsafe.runtime.DroidSafeAndroidRuntime").getFieldByName("context"); Stmt contextAssign=Jimple.v().newAssignStmt(contextLocal,Jimple.v().newStaticFieldRef(contextField.makeRef())); Harness.v().addStmtToEndOfMainLoop(contextAssign); List<Value> args=new LinkedList<Value>(); args.add(contextLocal); args.add(intentLocal); Stmt onReceiveCall=Jimple.v().newInvokeStmt(Jimple.v().newVirtualInvokeExpr(compLocal,onReceive.makeRef(),args)); Harness.v().addStmtToEndOfMainLoop(onReceiveCall); RCFG.v().ignoreInvokeForOutputEvents(onReceiveCall); }
Inject source flow into broadcast receiver field by injecting a call to onReceiver with the created Intent.
public boolean hasActiveEvent(){ return activeEvent; }
Returns true if there is an active event
private static boolean caselessCompare(char a,char b){ return Character.toLowerCase(a) == Character.toLowerCase(b); }
Compares two characters whilst ignoring case.
public static void clickToolbarCollapseButton(){ onView(withContentDescription("Collapse")).perform(click()); }
Clicks the arrow button in the toolbar when its function is collapsing a view. For instance, collapse the search view in the toolbar.
public static JsonValue parse(Reader reader) throws IOException { if (reader == null) { throw new NullPointerException("reader is null"); } return new JsonParser(reader).parse(); }
Reads the entire input stream from the given reader and parses it as JSON. The input must contain a valid JSON value, optionally padded with whitespace. <p> Characters are read in chunks and buffered internally, therefore wrapping an existing reader in an additional <code>BufferedReader</code> does <strong>not</strong> improve reading performance. </p>
public static Map<String,Object> sendMail(DispatchContext ctx,Map<String,? extends Object> context){ Delegator delegator=ctx.getDelegator(); String communicationEventId=(String)context.get("communicationEventId"); String orderId=(String)context.get("orderId"); Locale locale=(Locale)context.get("locale"); if (communicationEventId != null) { Debug.logInfo("SendMail Running, for communicationEventId : " + communicationEventId,module); } Map<String,Object> results=ServiceUtil.returnSuccess(); String subject=(String)context.get("subject"); subject=FlexibleStringExpander.expandString(subject,context); String partyId=(String)context.get("partyId"); String body=(String)context.get("body"); List<Map<String,Object>> bodyParts=UtilGenerics.checkList(context.get("bodyParts")); GenericValue userLogin=(GenericValue)context.get("userLogin"); results.put("communicationEventId",communicationEventId); results.put("partyId",partyId); results.put("subject",subject); if (UtilValidate.isNotEmpty(orderId)) { results.put("orderId",orderId); } if (UtilValidate.isNotEmpty(body)) { body=FlexibleStringExpander.expandString(body,context); results.put("body",body); } if (UtilValidate.isNotEmpty(bodyParts)) { results.put("bodyParts",bodyParts); } results.put("userLogin",userLogin); String sendTo=(String)context.get("sendTo"); String sendCc=(String)context.get("sendCc"); String sendBcc=(String)context.get("sendBcc"); String redirectAddress=EntityUtilProperties.getPropertyValue("general.properties","mail.notifications.redirectTo",delegator); if (UtilValidate.isNotEmpty(redirectAddress)) { String originalRecipients=" [To: " + sendTo + ", Cc: "+ sendCc+ ", Bcc: "+ sendBcc+ "]"; subject+=originalRecipients; sendTo=redirectAddress; sendCc=null; sendBcc=null; if (subject.length() > 255) { subject=subject.substring(0,255); } } String sendFrom=(String)context.get("sendFrom"); String sendType=(String)context.get("sendType"); String port=(String)context.get("port"); String socketFactoryClass=(String)context.get("socketFactoryClass"); String socketFactoryPort=(String)context.get("socketFactoryPort"); String socketFactoryFallback=(String)context.get("socketFactoryFallback"); String sendVia=(String)context.get("sendVia"); String authUser=(String)context.get("authUser"); String authPass=(String)context.get("authPass"); String messageId=(String)context.get("messageId"); String contentType=(String)context.get("contentType"); Boolean sendPartial=(Boolean)context.get("sendPartial"); Boolean isStartTLSEnabled=(Boolean)context.get("startTLSEnabled"); boolean useSmtpAuth=false; if (sendType == null || sendType.equals("mail.smtp.host")) { sendType="mail.smtp.host"; if (UtilValidate.isEmpty(sendVia)) { sendVia=EntityUtilProperties.getPropertyValue("general.properties","mail.smtp.relay.host","localhost",delegator); } if (UtilValidate.isEmpty(authUser)) { authUser=EntityUtilProperties.getPropertyValue("general.properties","mail.smtp.auth.user",delegator); } if (UtilValidate.isEmpty(authPass)) { authPass=EntityUtilProperties.getPropertyValue("general.properties","mail.smtp.auth.password",delegator); } if (UtilValidate.isNotEmpty(authUser)) { useSmtpAuth=true; } if (UtilValidate.isEmpty(port)) { port=EntityUtilProperties.getPropertyValue("general.properties","mail.smtp.port",delegator); } if (UtilValidate.isEmpty(socketFactoryPort)) { socketFactoryPort=EntityUtilProperties.getPropertyValue("general.properties","mail.smtp.socketFactory.port",delegator); } if (UtilValidate.isEmpty(socketFactoryClass)) { socketFactoryClass=EntityUtilProperties.getPropertyValue("general.properties","mail.smtp.socketFactory.class",delegator); } if (UtilValidate.isEmpty(socketFactoryFallback)) { socketFactoryFallback=EntityUtilProperties.getPropertyValue("general.properties","mail.smtp.socketFactory.fallback","false",delegator); } if (sendPartial == null) { sendPartial=EntityUtilProperties.propertyValueEqualsIgnoreCase("general.properties","mail.smtp.sendpartial","true",delegator) ? true : false; } if (isStartTLSEnabled == null) { isStartTLSEnabled=EntityUtilProperties.propertyValueEqualsIgnoreCase("general.properties","mail.smtp.starttls.enable","true",delegator); } } else if (sendVia == null) { return ServiceUtil.returnError(UtilProperties.getMessage(resource,"CommonEmailSendMissingParameterSendVia",locale)); } if (contentType == null) { contentType="text/html"; } if (UtilValidate.isNotEmpty(bodyParts)) { contentType="multipart/mixed"; } results.put("contentType",contentType); Session session; MimeMessage mail; try { Properties props=System.getProperties(); props.put(sendType,sendVia); if (UtilValidate.isNotEmpty(port)) { props.put("mail.smtp.port",port); } if (UtilValidate.isNotEmpty(socketFactoryPort)) { props.put("mail.smtp.socketFactory.port",socketFactoryPort); } if (UtilValidate.isNotEmpty(socketFactoryClass)) { props.put("mail.smtp.socketFactory.class",socketFactoryClass); Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); } if (UtilValidate.isNotEmpty(socketFactoryFallback)) { props.put("mail.smtp.socketFactory.fallback",socketFactoryFallback); } if (useSmtpAuth) { props.put("mail.smtp.auth","true"); } if (sendPartial != null) { props.put("mail.smtp.sendpartial",sendPartial ? "true" : "false"); } if (isStartTLSEnabled) { props.put("mail.smtp.starttls.enable","true"); } session=Session.getInstance(props); boolean debug=EntityUtilProperties.propertyValueEqualsIgnoreCase("general.properties","mail.debug.on","Y",delegator); session.setDebug(debug); mail=new MimeMessage(session); if (messageId != null) { mail.setHeader("In-Reply-To",messageId); mail.setHeader("References",messageId); } mail.setFrom(new InternetAddress(sendFrom)); mail.setSubject(subject,"UTF-8"); mail.setHeader("X-Mailer","Apache OFBiz, The Apache Open For Business Project"); mail.setSentDate(new Date()); mail.addRecipients(Message.RecipientType.TO,sendTo); if (UtilValidate.isNotEmpty(sendCc)) { mail.addRecipients(Message.RecipientType.CC,sendCc); } if (UtilValidate.isNotEmpty(sendBcc)) { mail.addRecipients(Message.RecipientType.BCC,sendBcc); } if (UtilValidate.isNotEmpty(bodyParts)) { MimeMultipart mp=new MimeMultipart(); Debug.logInfo(bodyParts.size() + " multiparts found",module); for ( Map<String,Object> bodyPart : bodyParts) { Object bodyPartContent=bodyPart.get("content"); MimeBodyPart mbp=new MimeBodyPart(); if (bodyPartContent instanceof String) { Debug.logInfo("part of type: " + bodyPart.get("type") + " and size: "+ bodyPart.get("content").toString().length(),module); mbp.setText((String)bodyPartContent,"UTF-8",((String)bodyPart.get("type")).substring(5)); } else if (bodyPartContent instanceof byte[]) { ByteArrayDataSource bads=new ByteArrayDataSource((byte[])bodyPartContent,(String)bodyPart.get("type")); Debug.logInfo("part of type: " + bodyPart.get("type") + " and size: "+ ((byte[])bodyPartContent).length,module); mbp.setDataHandler(new DataHandler(bads)); } else if (bodyPartContent instanceof DataHandler) { mbp.setDataHandler((DataHandler)bodyPartContent); } else { mbp.setDataHandler(new DataHandler(bodyPartContent,(String)bodyPart.get("type"))); } String fileName=(String)bodyPart.get("filename"); if (fileName != null) { mbp.setFileName(fileName); } mp.addBodyPart(mbp); } mail.setContent(mp); mail.saveChanges(); } else { if (contentType.startsWith("text")) { mail.setText(body,"UTF-8",contentType.substring(5)); } else { mail.setContent(body,contentType); } mail.saveChanges(); } } catch ( MessagingException e) { Debug.logError(e,"MessagingException when creating message to [" + sendTo + "] from ["+ sendFrom+ "] cc ["+ sendCc+ "] bcc ["+ sendBcc+ "] subject ["+ subject+ "]",module); Debug.logError("Email message that could not be created to [" + sendTo + "] had context: "+ context,module); return ServiceUtil.returnError(UtilProperties.getMessage(resource,"CommonEmailSendMessagingException",UtilMisc.toMap("sendTo",sendTo,"sendFrom",sendFrom,"sendCc",sendCc,"sendBcc",sendBcc,"subject",subject),locale)); } catch ( IOException e) { Debug.logError(e,"IOExcepton when creating message to [" + sendTo + "] from ["+ sendFrom+ "] cc ["+ sendCc+ "] bcc ["+ sendBcc+ "] subject ["+ subject+ "]",module); Debug.logError("Email message that could not be created to [" + sendTo + "] had context: "+ context,module); return ServiceUtil.returnError(UtilProperties.getMessage(resource,"CommonEmailSendIOException",UtilMisc.toMap("sendTo",sendTo,"sendFrom",sendFrom,"sendCc",sendCc,"sendBcc",sendBcc,"subject",subject),locale)); } String mailEnabled=EntityUtilProperties.getPropertyValue("general.properties","mail.notifications.enabled","N",delegator); if (!"Y".equalsIgnoreCase(mailEnabled)) { Debug.logImportant("Mail notifications disabled in general.properties; mail with subject [" + subject + "] not sent to addressee ["+ sendTo+ "]",module); Debug.logVerbose("What would have been sent, the addressee: " + sendTo + " subject: "+ subject+ " context: "+ context,module); results.put("messageWrapper",new MimeMessageWrapper(session,mail)); return results; } Transport trans=null; try { trans=session.getTransport("smtp"); if (!useSmtpAuth) { trans.connect(); } else { trans.connect(sendVia,authUser,authPass); } trans.sendMessage(mail,mail.getAllRecipients()); results.put("messageWrapper",new MimeMessageWrapper(session,mail)); results.put("messageId",mail.getMessageID()); trans.close(); } catch ( SendFailedException e) { Debug.logError(e,"[ADDRERR] Address error when sending message to [" + sendTo + "] from ["+ sendFrom+ "] cc ["+ sendCc+ "] bcc ["+ sendBcc+ "] subject ["+ subject+ "]",module); List<SMTPAddressFailedException> failedAddresses=new LinkedList<SMTPAddressFailedException>(); Exception nestedException=null; while ((nestedException=e.getNextException()) != null && nestedException instanceof MessagingException) { if (nestedException instanceof SMTPAddressFailedException) { SMTPAddressFailedException safe=(SMTPAddressFailedException)nestedException; Debug.logError("Failed to send message to [" + safe.getAddress() + "], return code ["+ safe.getReturnCode()+ "], return message ["+ safe.getMessage()+ "]",module); failedAddresses.add(safe); break; } } Boolean sendFailureNotification=(Boolean)context.get("sendFailureNotification"); if (sendFailureNotification == null || sendFailureNotification) { sendFailureNotification(ctx,context,mail,failedAddresses); results.put("messageWrapper",new MimeMessageWrapper(session,mail)); try { results.put("messageId",mail.getMessageID()); trans.close(); } catch ( MessagingException e1) { Debug.logError(e1,module); } } else { return ServiceUtil.returnError(UtilProperties.getMessage(resource,"CommonEmailSendAddressError",UtilMisc.toMap("sendTo",sendTo,"sendFrom",sendFrom,"sendCc",sendCc,"sendBcc",sendBcc,"subject",subject),locale)); } } catch ( MessagingException e) { Debug.logError(e,"[CON] Connection error when sending message to [" + sendTo + "] from ["+ sendFrom+ "] cc ["+ sendCc+ "] bcc ["+ sendBcc+ "] subject ["+ subject+ "]",module); Debug.logError("Email message that could not be sent to [" + sendTo + "] had context: "+ context,module); return ServiceUtil.returnError(UtilProperties.getMessage(resource,"CommonEmailSendConnectionError",UtilMisc.toMap("sendTo",sendTo,"sendFrom",sendFrom,"sendCc",sendCc,"sendBcc",sendBcc,"subject",subject),locale)); } return results; }
Basic JavaMail Service
public void appendBytes(byte[] bs,int start,int len){ elems=ArrayUtils.ensureCapacity(elems,length + len); System.arraycopy(bs,start,elems,length,len); length+=len; }
Append `len' bytes from byte array, starting at given `start' offset.
private void startScrolling(){ if (!isScrollingPerformed) { isScrollingPerformed=true; notifyScrollingListenersAboutStart(); } }
Starts scrolling
public void onProgressData(byte[] responseBody){ Log.d(LOG_TAG,"onProgressData(byte[]) was not overriden, but callback was received"); }
Fired when the request progress, override to handle in your own code
public void writeAttribute(String name,String value,String prefix) throws Exception { if (last != Tag.START) { throw new NodeException("Start element required"); } write(' '); write(name,prefix); write('='); write('"'); escape(value); write('"'); }
This is used to write a name value attribute pair. If the last tag written was not a start tag then this throws an exception. All attribute values written are enclosed in double quotes.
private Border createNonRolloverToggleBorder(){ UIDefaults table=UIManager.getLookAndFeelDefaults(); return new CompoundBorder(new BasicBorders.RadioButtonBorder(table.getColor("ToggleButton.shadow"),table.getColor("ToggleButton.darkShadow"),table.getColor("ToggleButton.light"),table.getColor("ToggleButton.highlight")),new BasicBorders.RolloverMarginBorder()); }
Creates a non rollover border for Toggle buttons in the toolbar.
public int toReal(){ return _real; }
Returns the real value.
private void addParsedAsAnnotations(final JCas jCas,final int offset,final Parse parsed){ final String type=parsed.getType(); if (OpenNLPParser.PHRASE_TYPES.contains(type)) { final Span span=parsed.getSpan(); final PhraseChunk phraseChunk=new PhraseChunk(jCas); phraseChunk.setBegin(offset + span.getStart()); phraseChunk.setEnd(offset + span.getEnd()); phraseChunk.setChunkType(parsed.getType()); addToJCasIndex(phraseChunk); } Arrays.stream(parsed.getChildren()).forEach(null); }
Adds the parsed as annotations.
public static boolean isLocalContentUri(Uri uri){ final String scheme=getSchemeOrNull(uri); return FrescoUri.LOCAL_CONTENT_SCHEME.equals(scheme); }
Check if uri represents local content
public XPathSubsetContentSelector(ContentManager cm,XBLOMContentElement content,Element bound,String selector){ super(cm,content,bound); parseSelector(selector); }
Creates a new XPathSubsetContentSelector object.
protected RestClient newPortalClient(){ URI baseUri=URI.create(String.format("%s://%s:%s",protocol,host,portalPort)); return new RestClient(baseUri,this); }
Creates the RestClient for the portal. This is provided here so Testcases are able to override the base implementation.
public int mainInit(final String[] args,final OutputStream out,final PrintStream err){ if (mCli == null) { throw new RuntimeException("Incorrectly configured module"); } return mCli.mainInit(args,out,err); }
Main init for running this module
public Matrix sample_X(Matrix Z){ Matrix P_X=prob_X(Z); return MatrixUtils.sample(P_X,m_R); }
Sample Visible - returns X ~ P(X|Z). A bias column is assumed to be included.
public void reportTable(HSSFWorkbook book,LinkedList<ReportTO> data,HSSFSheet sheet,int fila){ HSSFRow row; HSSFFont font=book.createFont(); font.setFontHeightInPoints((short)10); font.setFontName(HSSFFont.FONT_ARIAL); HSSFRichTextString text; Iterator<ReportTO> itRep=data.iterator(); Boolean newRow=false; sheet.setColumnWidth((short)0,(short)(13 * 256)); sheet.setColumnWidth((short)1,(short)(60 * 256)); for (int i=2; i < (cols); i++) { sheet.setColumnWidth((short)i,(short)(15 * 256)); } HSSFCellStyle cellStyle=book.createCellStyle(); HSSFCellStyle cellStyleD=book.createCellStyle(); HSSFCellStyle cellStyleN=book.createCellStyle(); while (itRep.hasNext()) { short col=0; ReportTO rpt=itRep.next(); if (!newRow) { cellStyle=book.createCellStyle(); cellStyleD=book.createCellStyle(); cellStyleN=book.createCellStyle(); } newRow=false; if (rpt.getReportlinestyle() != null && rpt.getReportlinestyle().equals("T")) { row=sheet.createRow(fila++); HSSFFont fontT=book.createFont(); fontT.setFontHeightInPoints((short)12); fontT.setFontName(HSSFFont.FONT_ARIAL); fontT.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); HSSFCellStyle cellStyleT=book.createCellStyle(); cellStyleT.setWrapText(true); cellStyleT.setAlignment(HSSFCellStyle.ALIGN_CENTER); cellStyleT.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP); cellStyleT.setFont(fontT); Region region=new Region(fila - 1,(short)0,fila - 1,endRegion); sheet.addMergedRegion(region); text=new HSSFRichTextString(rpt.getDescription()); HSSFCell cellT=row.createCell(col); cellT.setCellStyle(cellStyleT); cellT.setCellValue(text); newRow=true; } else if (rpt.getReportlinestyle() != null && rpt.getReportlinestyle().equals("L")) { cellStyle.setWrapText(true); cellStyle.setBorderTop(HSSFCellStyle.BORDER_MEDIUM); cellStyle.setBottomBorderColor((short)8); cellStyleD.setWrapText(true); cellStyleD.setBorderTop(HSSFCellStyle.BORDER_MEDIUM); cellStyleD.setBottomBorderColor((short)8); cellStyleN.setWrapText(true); cellStyleN.setBorderTop(HSSFCellStyle.BORDER_MEDIUM); cellStyleN.setBottomBorderColor((short)8); newRow=true; } else if (rpt.getReportlinestyle() != null && rpt.getReportlinestyle().equals("X")) { cellStyle.setWrapText(true); cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP); cellStyle.setBorderTop(HSSFCellStyle.BORDER_MEDIUM); cellStyle.setBottomBorderColor((short)8); newRow=true; } else if (rpt.getReportlinestyle() != null && rpt.getReportlinestyle().equals("Z")) { cellStyle.setWrapText(true); cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP); cellStyle.setBorderTop(HSSFCellStyle.BORDER_DOUBLE); cellStyle.setBottomBorderColor((short)8); row=sheet.createRow(fila++); ReportTO rptD=new ReportTO(); putRow(cellStyle,cellStyleD,cellStyleN,sheet,row,fila,rptD); cellStyle=book.createCellStyle(); newRow=true; } else if (rpt.getReportlinestyle() != null && rpt.getReportlinestyle().equals("D")) { cellStyleD.setWrapText(true); cellStyleD.setVerticalAlignment(HSSFCellStyle.VERTICAL_TOP); cellStyleD.setBorderTop(HSSFCellStyle.BORDER_MEDIUM); cellStyleD.setBottomBorderColor((short)8); newRow=true; } else if (rpt.getReportlinestyle() != null && rpt.getReportlinestyle().equals("S")) { row=sheet.createRow(fila++); newRow=true; } else if (rpt.getTablevel() != null && rpt.getTablevel() > 0) { row=sheet.createRow(fila++); String jerarchy=""; for (int i=1; i <= rpt.getTablevel(); i++) { jerarchy=jerarchy + " "; } Region region=new Region(fila - 1,(short)0,fila - 1,endRegion); sheet.addMergedRegion(region); text=new HSSFRichTextString(jerarchy + rpt.getDescription()); HSSFCell cellJ=row.createCell(col); cellJ.setCellValue(text); newRow=true; } else { row=sheet.createRow(fila++); putRow(cellStyle,cellStyleD,cellStyleN,sheet,row,fila,rpt); } } }
llena los datos del reporte - fill report data
public static Bitmap drawableToBitmap(Drawable drawable){ int width=drawable.getIntrinsicWidth(); int height=drawable.getIntrinsicHeight(); Bitmap bitmap=Bitmap.createBitmap(width,height,drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565); Canvas canvas=new Canvas(bitmap); drawable.setBounds(0,0,width,height); drawable.draw(canvas); return bitmap; }
convert drawable to bitmap
public XObject operate(XObject left,XObject right) throws javax.xml.transform.TransformerException { return new XNumber(left.num() % right.num()); }
Apply the operation to two operands, and return the result.
public static void isTrue(boolean val){ if (!val) throw new IllegalArgumentException("Must be true"); }
Validates that the value is true
private String pad(int n){ return n < 10 ? "0" + n : n + ""; }
Return n as padded string
public static String toJSONString(Collection collection){ final StringWriter writer=new StringWriter(); try { writeJSONString(collection,writer); return writer.toString(); } catch ( IOException e) { throw new RuntimeException(e); } }
Convert a list to JSON text. The result is a JSON array. If this list is also a JSONAware, JSONAware specific behaviours will be omitted at this top level.
protected Map<String,Object> itemToEntityResponse(String root_url){ return super.toEntityResponse(root_url); }
Calls the superclass entity response not aggregated to this response.
private void drawDiscete(DiscreteUncertainObject uo,MarkerLibrary ml,int cnum,double size){ final int e=uo.getNumberSamples(); final double ssize=size * Math.sqrt(e); for (int i=0; i < e; i++) { final NumberVector s=uo.getSample(i); if (s == null) { continue; } double[] v=proj.fastProjectDataToRenderSpace(s); if (v[0] != v[0] || v[1] != v[1]) { continue; } ml.useMarker(svgp,layer,v[0],v[1],cnum,uo.getWeight(i) * ssize); } }
Visualize a discrete uncertain object
private void checkSetup(){ synchronized (TransactionManagerImp.class) { txmgr_=TransactionManagerImp.getTransactionManager(); if (txmgr_ == null) { UserTransactionService uts=new UserTransactionServiceImp(); uts.init(); txmgr_=TransactionManagerImp.getTransactionManager(); } } }
Referenceable mechanism requires later setup of txmgr_, otherwise binding into JNDI already requires that TM is running.
public void writeExif(Bitmap bmap,String exifOutFileName) throws FileNotFoundException, IOException { if (bmap == null || exifOutFileName == null) { throw new IllegalArgumentException(NULL_ARGUMENT_STRING); } OutputStream s=null; try { s=getExifWriterStream(exifOutFileName); bmap.compress(Bitmap.CompressFormat.JPEG,90,s); s.flush(); } catch ( IOException e) { closeSilently(s); throw e; } s.close(); }
Writes the tags from this ExifInterface object into a jpeg compressed bitmap, removing prior exif tags.
protected void sendPrepare(final String statementText) throws SQLException, IOException { final XdrOutputStream xdrOut=getXdrOut(); xdrOut.writeInt(WireProtocolConstants.op_prepare_statement); xdrOut.writeInt(getTransaction().getHandle()); xdrOut.writeInt(getHandle()); xdrOut.writeInt(getDatabase().getConnectionDialect()); xdrOut.writeString(statementText,getDatabase().getEncoding()); xdrOut.writeBuffer(getStatementInfoRequestItems()); xdrOut.writeInt(getDefaultSqlInfoSize()); }
Sends the statement prepare to the connection.
private void writeNetBuffer() throws IgniteCheckedException { try { ch.write(outNetBuf); } catch ( IOException e) { throw new IgniteCheckedException("Failed to write byte to socket.",e); } }
Copies data from out net buffer and passes it to the underlying chain.
public Vector2f interpolate(Vector2f finalVec,float changeAmnt){ this.x=(1 - changeAmnt) * this.x + changeAmnt * finalVec.x; this.y=(1 - changeAmnt) * this.y + changeAmnt * finalVec.y; return this; }
Sets this vector to the interpolation by changeAmnt from this to the finalVec this=(1-changeAmnt)*this + changeAmnt * finalVec
public Compactor minorIndex(long index){ this.minorIndex=Math.max(this.minorIndex,index); Segment segment=segments.segment(minorIndex); if (segment != null) { compactIndex=segment.firstIndex(); } return this; }
Sets the maximum compaction index for minor compaction.
public static BatchStatus createCreatedStatus(){ BatchStatus retval=new BatchStatus(); retval.setCode(HttpURLConnection.HTTP_CREATED); retval.setReason("Created"); return retval; }
Creates a Success status object.
public final static NameValuePair parseNameValuePair(final String value,HeaderValueParser parser) throws ParseException { if (value == null) { throw new IllegalArgumentException("Value to parse may not be null"); } if (parser == null) parser=BasicHeaderValueParser.DEFAULT; CharArrayBuffer buffer=new CharArrayBuffer(value.length()); buffer.append(value); ParserCursor cursor=new ParserCursor(0,value.length()); return parser.parseNameValuePair(buffer,cursor); }
Parses a name-value-pair with the given parser.
public void dismissSuggestions(){ if (mSuggestionsListView.getVisibility() == VISIBLE) { mSuggestionsListView.setVisibility(GONE); } }
Dismiss the suggestions list.
private static boolean tagExists(final String tagTitle,final List<JSONObject> tags) throws JSONException { for ( final JSONObject tag : tags) { if (tag.getString(Tag.TAG_TITLE).equals(tagTitle)) { return true; } } return false; }
Determines whether the specified tag title exists in the specified tags.
public Second(){ this(new Date()); }
Constructs a new Second, based on the system date/time.
private void launchReport(KeyNamePair pp){ MPrintFormat pf=MPrintFormat.get(Env.getCtx(),pp.getKey(),false); launchReport(pf); }
Launch Report
public static Class<?> loadClassWithout(ClassLoader loader,String className) throws ClassNotFoundException { MBEANSERVER_LOGGER.logp(Level.FINEST,DefaultLoaderRepository.class.getName(),"loadClassWithout",className); return load(loader,className); }
Go through the list of class loaders but exclude the given class loader, then try to load the requested class. The method will stop as soon as the class is found. If the class is not found the method will throw a <CODE>ClassNotFoundException</CODE> exception.
@Override public void mark(int readlimit){ }
Marks the current position in this stream. Setting a mark is not supported in this class; this implementation does nothing.
public void removeGenClass(SootClass clz){ genClasses.remove(clz.getName()); }
Remove a class from the list of gen classes.
public boolean isMultipleAssignmentDeclaration(){ return getLeftExpression() instanceof TupleExpression; }
This method tells you if this declaration is a multiple assignment declaration, which has the form "def (x, y) = ..." in Groovy. If this method returns true, then the left hand side is an ArgumentListExpression. Do not call "getVariableExpression()" on this object if this method returns true, instead use "getLeftExpression()".
public Bindings addOptComponent(String property,Class<? extends IValidatable> clazz,JToggleButton c){ return addOptComponent(property,clazz,c,false); }
Add an optional (nullable) Java Bean component of type clazz.
public LUDecomposition lu(){ return new LUDecomposition(this); }
LU Decomposition
public static void addCombinerRecipe(ItemStack input,ItemStack output){ try { Class recipeClass=Class.forName("mekanism.common.recipe.RecipeHandler"); Method m=recipeClass.getMethod("addCombinerRecipe",ItemStack.class,ItemStack.class); m.invoke(null,input,output); } catch ( Exception e) { System.err.println("Error while adding recipe: " + e.getMessage()); } }
Add a Combiner recipe.
static void forceSetFactory2(LayoutInflater inflater,LayoutInflater.Factory2 factory){ if (!sCheckedField) { try { sLayoutInflaterFactory2Field=LayoutInflater.class.getDeclaredField("mFactory2"); sLayoutInflaterFactory2Field.setAccessible(true); } catch ( NoSuchFieldException e) { Log.e(TAG,"forceSetFactory2 Could not find field 'mFactory2' on class " + LayoutInflater.class.getName() + "; inflation may have unexpected results.",e); } sCheckedField=true; } if (sLayoutInflaterFactory2Field != null) { try { sLayoutInflaterFactory2Field.set(inflater,factory); } catch ( IllegalAccessException e) { Log.e(TAG,"forceSetFactory2 could not set the Factory2 on LayoutInflater " + inflater + "; inflation may have unexpected results.",e); } } }
For APIs >= 11 && < 21, there was a framework bug that prevented a LayoutInflater's Factory2 from being merged properly if set after a cloneInContext from a LayoutInflater that already had a Factory2 registered. We work around that bug here. If we can't we log an error.
public static XmlJmapper readAtRuntime(String xmlPath) throws MalformedURLException, IOException { return toXmlJmapper(xmlPath,loadResource(xmlPath)); }
This method loads the xml file relative to xmlPath parameter. Read method is used for the xml manipulation at runtime.
protected double computeEyeDistance(DrawContext dc,ShapeData shapeData){ double minDistance=Double.MAX_VALUE; Vec4 eyePoint=dc.getView().getEyePoint(); for ( Vec4 point : shapeData.getOuterBoundaryInfo().capVertices) { double d=point.add3(shapeData.getReferencePoint()).distanceTo3(eyePoint); if (d < minDistance) minDistance=d; } return minDistance; }
Computes the minimum distance between this shape and the eye point.
private <T extends DataObject>void updateInactiveField(Class<T> clazz,List<URI> keyList){ DbClient dbClient=getDbClient(); log.info("update inactive field for class: {}",clazz.getSimpleName()); T object; for ( URI key : keyList) { try { object=clazz.newInstance(); object.setId(key); object.setInactive(false); } catch ( Exception e) { log.error("create new object of class({}) failed. e=",clazz.getSimpleName(),e); throw new IllegalStateException(e); } dbClient.updateAndReindexObject(object); log.info("Update the inactive field of object(cf={}, id={}) to false",object.getClass().getName(),object.getId()); } }
Update the missed setting of "inactive field" for all data object
public int compareTo(Object other){ if (!(other instanceof Resource)) { throw new SwcException.NotAResource(other.getClass().getName()); } Resource r=(Resource)other; return getName().compareTo(r.getName()); }
delegates to a comparison of names.
public static void main(String[] args) throws InterruptedException { Counter counter; final int total=10000; Thread[] threads=new Thread[total]; for ( Method method : Method.values()) { counter=new Counter(); for (int i=0; i < threads.length; i++) { threads[i]=new Thread(new Incrementer(counter,method)); threads[i].start(); } for (int i=0; i < threads.length; i++) { threads[i].join(); } switch (method) { case TwoStatements: case OneStatement: if (counter.total >= total) { System.out.format("unlikely event: method %s: total: %d%n",method,counter.total); } break; case SynchronizedMethod: case SynchronizedBlock: case Semaphore: case SemaphoreTry: case Lock: assert counter.total == total; break; case AtomicInteger: assert counter.atomicTotal.get() == total; break; } } Counter.reentrantOuter(); Counter.reentrantOuterBlock(); Counter.reentrantOuterLock(); }
Increments a counter `total` times with different methods in multiple threads and checks if the result is correct (shoul equal `total`).
public void reset(ActionMapping mapping,HttpServletRequest request){ puid=null; op=null; name=null; canLookup=false; }
Method reset
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:58:53.642 -0500",hash_original_method="8F0255C2E086694196AF7CFC36B7EF43",hash_generated_method="7E35C8E7189C135682BC48CACE7EFA68") public boolean isMinInfoReady(){ return mIsMinInfoReady; }
Check if subscription data has been assigned to mMin return true if MIN info is ready; false otherwise.
public Name(byte[] encoding) throws IOException { DerInputStream in=new DerInputStream(encoding); if (in.getEndOffset() != encoding.length) { throw new IOException("Wrong content length"); } ASN1.decode(in); this.rdn=(List<List<AttributeTypeAndValue>>)in.content; }
Creates new <code>Name</code> instance from its DER encoding
public double[][] distributionsForInstances(Instances insts) throws Exception { if (getClassifier() instanceof BatchPredictor) { Instances filteredInsts=Filter.useFilter(insts,m_Filter); if (filteredInsts.numInstances() != insts.numInstances()) { throw new WekaException("FilteredClassifier: filter has returned more/less instances than required."); } return ((BatchPredictor)getClassifier()).distributionsForInstances(filteredInsts); } else { double[][] result=new double[insts.numInstances()][insts.numClasses()]; for (int i=0; i < insts.numInstances(); i++) { result[i]=distributionForInstance(insts.instance(i)); } return result; } }
Batch scoring method. Calls the appropriate method for the base learner if it implements BatchPredictor. Otherwise it simply calls the distributionForInstance() method repeatedly.
@Override public UserProjectObject copy(){ return new UserProjectObject(this); }
This method was generated by MyBatis Generator. This method corresponds to the database table user_project
public void addLogListener(LogListener l){ super.addLogListener(l); for ( DatasetProvider provider : m_Providers) provider.addLogListener(l); }
Adds the log listener to use.
public static void closeSilently(Closeable out){ if (out != null) { try { trace("closeSilently",null,out); out.close(); } catch ( Exception e) { } } }
Close an output stream without throwing an exception.
BitMatrix buildFunctionPattern(){ int dimension=getDimensionForVersion(); BitMatrix bitMatrix=new BitMatrix(dimension); bitMatrix.setRegion(0,0,9,9); bitMatrix.setRegion(dimension - 8,0,8,9); bitMatrix.setRegion(0,dimension - 8,9,8); int max=alignmentPatternCenters.length; for (int x=0; x < max; x++) { int i=alignmentPatternCenters[x] - 2; for (int y=0; y < max; y++) { if ((x == 0 && (y == 0 || y == max - 1)) || (x == max - 1 && y == 0)) { continue; } bitMatrix.setRegion(alignmentPatternCenters[y] - 2,i,5,5); } } bitMatrix.setRegion(6,9,1,dimension - 17); bitMatrix.setRegion(9,6,dimension - 17,1); if (versionNumber > 6) { bitMatrix.setRegion(dimension - 11,0,3,6); bitMatrix.setRegion(0,dimension - 11,6,3); } return bitMatrix; }
See ISO 18004:2006 Annex E
public boolean equals(Object obj){ if (obj == this) { return true; } if (!(obj instanceof VolumeDataset)) { return false; } VolumeDataset that=(VolumeDataset)obj; if (!this.xPosition.equals(that.xPosition)) { return false; } return ObjectUtilities.equal(this.data,that.data); }
Tests this instance for equality with an arbitrary object.
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { doGet(request,response); }
Process the HTTP Post request to simplify we reuse the doGet functionality
public static <U extends Key<?>>KeyMatcher<U> keyEquals(U compareTo){ return new KeyMatcher<U>(compareTo); }
Create a KeyMatcher that matches Keys that equal the given key.
public OverScroller(Context context,Interpolator interpolator,float bounceCoefficientX,float bounceCoefficientY){ this(context,interpolator,true); }
Creates an OverScroller with flywheel enabled.
@Override public void execute() throws MojoExecutionException { getLog().debug("Creating output directory \"" + outputDirectory + "\"."); java.nio.file.Path outputDirectoryPath=Paths.get(outputDirectory.toURI()); if (!Files.exists(outputDirectoryPath)) { try { Files.createDirectories(outputDirectoryPath); } catch ( IOException e) { throw new MojoExecutionException("Unable to create directory for output path \"" + outputDirectoryPath + "\".",e); } } Swagger swagger=getSwagger(); ModelClassFinder modelClassFinder=new ModelClassFinder(getLog(),modelJavaPackage,modelErrorClassName); RestControllerProcessor restControllerProcessor=new RestControllerProcessor(getLog(),swagger,restJavaPackage,tagPatternParameter,modelClassFinder.getModelErrorClass()); XsdParser xsdParser=null; if (xsdName != null) { xsdParser=new XsdParser(xsdName); } new DefinitionGenerator(getLog(),swagger,restControllerProcessor.getExampleClassNames(),modelClassFinder.getModelClasses(),xsdParser); createYamlFile(swagger); }
The main execution method for this Mojo.
public ActionErrors validate(ActionMapping mapping,HttpServletRequest request){ ActionErrors errors=new ActionErrors(); if (nivelAcceso < 0) { errors.add(ActionErrors.GLOBAL_MESSAGE,new ActionError(Constants.ERROR_REQUIRED,Messages.getString(Constants.ETIQUETA_NIVEL_ACCESO,request.getLocale()))); } if ((nivelAcceso == NivelAcceso.RESTRINGIDO) && StringUtils.isBlank(idLCA)) { errors.add(ActionErrors.GLOBAL_MESSAGE,new ActionError(Constants.ERROR_REQUIRED,Messages.getString(Constants.ETIQUETA_LISTA_CONTROL_ACCESO,request.getLocale()))); } return errors; }
Valida el formulario
@Override public Object readReply(Class expectedClass) throws Throwable { int tag=read(); if (tag == 'R') return readObject(expectedClass); else if (tag == 'F') { HashMap map=(HashMap)readObject(HashMap.class); throw prepareFault(map); } else { StringBuilder sb=new StringBuilder(); sb.append((char)tag); try { int ch; while ((ch=read()) >= 0) { sb.append((char)ch); } } catch ( IOException e) { log.log(Level.FINE,e.toString(),e); } throw error("expected hessian reply at " + codeName(tag) + "\n"+ sb); } }
Reads a reply as an object. If the reply has a fault, throws the exception.
@POST @Path("send") @Consumes(MediaType.APPLICATION_JSON) public Response sendMail(EmailBeanDto emailBean){ File tempDir=null; try { MimeMessage message=new MimeMessage(sessionHolder.getMailSession()); Multipart contentPart=new MimeMultipart(); MimeBodyPart bodyPart=new MimeBodyPart(); bodyPart.setText(emailBean.getBody(),"UTF-8",getSubType(emailBean.getMimeType())); contentPart.addBodyPart(bodyPart); if (emailBean.getAttachments() != null) { tempDir=Files.createTempDir(); for ( AttachmentDto attachmentDto : emailBean.getAttachments()) { byte[] attachmentContent=Base64.getDecoder().decode(attachmentDto.getContent()); File attachmentFile=new File(tempDir,attachmentDto.getFileName()); Files.write(attachmentContent,attachmentFile); MimeBodyPart attachmentPart=new MimeBodyPart(); attachmentPart.attachFile(attachmentFile); attachmentPart.setContentID("<" + attachmentDto.getContentId() + ">"); contentPart.addBodyPart(attachmentPart); } } message.setContent(contentPart); message.setSubject(emailBean.getSubject(),"UTF-8"); message.setFrom(new InternetAddress(emailBean.getFrom(),true)); message.addRecipients(Message.RecipientType.TO,InternetAddress.parse(emailBean.getTo())); if (emailBean.getReplyTo() != null) { message.setReplyTo(InternetAddress.parse(emailBean.getReplyTo())); } LOG.info("Sending from {} to {} with subject {}",emailBean.getFrom(),emailBean.getTo(),emailBean.getSubject()); Transport.send(message); LOG.debug("Mail send"); } catch ( MessagingException|IOException e) { LOG.error(e.getLocalizedMessage()); throw new WebApplicationException(e); } finally { if (tempDir != null) { try { FileUtils.deleteDirectory(tempDir); } catch ( IOException exception) { LOG.error(exception.getMessage()); } } } return Response.ok().build(); }
Send mail message. If you need to send more than one copy of email, then write needed receivers to EmailBean using setTo() method.
@Override public boolean isActive(){ return amIActive; }
Used by the Whitebox GUI to tell if this plugin is still running.
static String checkNotNullOrBlank(String value,String errorMessage,Object... args){ checkNotNull(value,errorMessage,args); String trimmed=value.trim(); if (trimmed.isEmpty()) { throw new IllegalArgumentException(String.format(errorMessage,args)); } return trimmed; }
Ensures that a String is not null and contains at least one non-whitespace char.
public boolean hasTrait(String ns,String ln){ return false; }
Returns whether the given trait is available on this element.
@Override public synchronized void acceptTrainingSet(TrainingSetEvent e){ try { m_Saver=makeCopy(); } catch ( Exception ex) { if (m_logger != null) { m_logger.statusMessage(statusMessagePrefix() + "ERROR (See log for details)"); m_logger.logMessage("[Saver] " + statusMessagePrefix() + " unable to copy saver. "+ ex.getMessage()); } } passEnvOnToSaver(); m_fileName=sanitizeFilename(e.getTrainingSet().relationName()); m_dataSet=e.getTrainingSet(); if (e.isStructureOnly() && m_isDBSaver && ((DatabaseSaver)m_SaverTemplate).getRelationForTableName()) { ((DatabaseSaver)m_Saver).setTableName(m_fileName); } if (!e.isStructureOnly()) { if (!m_isDBSaver) { try { m_Saver.setDirAndPrefix(m_fileName,"_training_" + e.getSetNumber() + "_of_"+ e.getMaxSetNumber()); } catch ( Exception ex) { System.out.println(ex); } } else { ((DatabaseSaver)m_Saver).setRelationForTableName(false); String setName=((DatabaseSaver)m_Saver).getTableName(); setName=setName.replaceFirst("_[tT][rR][aA][iI][nN][iI][nN][gG]_[0-9]+_[oO][fF]_[0-9]+",""); ((DatabaseSaver)m_Saver).setTableName(setName + "_training_" + e.getSetNumber()+ "_of_"+ e.getMaxSetNumber()); } saveBatch(); System.out.println("... training set " + e.getSetNumber() + " of "+ e.getMaxSetNumber()+ " for relation "+ m_fileName+ " saved."); } }
Method reacts to a training set event and starts the writing process in batch mode
public boolean contains(final short[] a){ int i=d, l=a.length; long bits[]=this.bits; while (i-- != 0) if (!get(bits,hash(a,l,i))) return false; return true; }
Checks whether the given short array is in this filter.
public int hashCode(){ return 83 + start + 7 * end + (negated ? 1 : 0); }
<p>Gets a hashCode compatible with the equals method.</p>
@BeforeClass public static void beforeClass(){ PlayerTestHelper.generateNPCRPClasses(); MockStendlRPWorld.get(); }
Setup before running tests in this test class
public void requestDestroyed(ServletRequestEvent event){ try { ServletRequest request=event.getServletRequest(); for (Enumeration e=request.getAttributeNames(); e.hasMoreElements(); ) { String beanName=(String)e.nextElement(); handleAttributeEvent(beanName,request.getAttribute(beanName),ELUtils.Scope.REQUEST); } WebConfiguration config=WebConfiguration.getInstance(event.getServletContext()); if (config.isOptionEnabled(WebConfiguration.BooleanWebContextInitParameter.EnableAgressiveSessionDirtying)) { syncSessionScopedBeans(request); } boolean distributable=config.isOptionEnabled(EnableDistributable); if (distributable) { HttpSession session=((HttpServletRequest)request).getSession(false); if (session != null && session.getAttribute(ACTIVE_VIEW_MAPS) != null) { session.setAttribute(ACTIVE_VIEW_MAPS,session.getAttribute(ACTIVE_VIEW_MAPS)); } } } catch ( Throwable t) { FacesContext context=new InitFacesContext(event.getServletContext()); ExceptionQueuedEventContext eventContext=new ExceptionQueuedEventContext(context,t); context.getApplication().publishEvent(context,ExceptionQueuedEvent.class,eventContext); context.getExceptionHandler().handle(); } finally { ApplicationAssociate.setCurrentInstance(null); } }
The request is about to go out of scope of the web application.
public void testFailoverAutoFallBack() throws Exception { Set<String> downedHosts=new HashSet<String>(); downedHosts.add(HOST_1); downedHosts.add(HOST_3); Properties props=new Properties(); props.setProperty("retriesAllDown","2"); props.setProperty("queriesBeforeRetryMaster","10"); props.setProperty("secondsBeforeRetryMaster","1"); for ( boolean autoCommit : new boolean[]{true,false}) { Connection testConn=getUnreliableFailoverConnection(new String[]{HOST_1,HOST_2,HOST_3},props,downedHosts); Statement testStmt=null; try { testConn.setAutoCommit(autoCommit); assertEquals(HOST_2_OK,UnreliableSocketFactory.getHostFromLastConnection()); testStmt=testConn.createStatement(); assertSingleValueQuery(testStmt,"SELECT 1",1L); UnreliableSocketFactory.dontDownHost(HOST_1); UnreliableSocketFactory.dontDownHost(HOST_3); long startTime=System.currentTimeMillis(); boolean hostSwitched=false; do { assertSingleValueQuery(testStmt,"SELECT 1",1L); if (autoCommit) { if (!hostSwitched && UnreliableSocketFactory.getHostFromLastConnection().equals(HOST_1_OK)) { hostSwitched=true; } if (hostSwitched) { assertEquals(HOST_1_OK,UnreliableSocketFactory.getHostFromLastConnection()); } else { assertEquals(HOST_2_OK,UnreliableSocketFactory.getHostFromLastConnection()); } } else { assertEquals(HOST_2_OK,UnreliableSocketFactory.getHostFromLastConnection()); } try { Thread.sleep(100); } catch ( InterruptedException e) { } } while (System.currentTimeMillis() - startTime < 2000); UnreliableSocketFactory.downHost(HOST_2); if (autoCommit) { assertEquals(HOST_1_OK,UnreliableSocketFactory.getHostFromLastConnection()); } else { assertEquals(HOST_2_OK,UnreliableSocketFactory.getHostFromLastConnection()); assertSQLException(testStmt,"SELECT 1",COMM_LINK_ERR_PATTERN); assertEquals(HOST_1_OK,UnreliableSocketFactory.getHostFromLastConnection()); } assertConnectionsHistory(HOST_2_OK,HOST_1_OK); } finally { if (testStmt != null) { testStmt.close(); } if (testConn != null) { testConn.close(); } } } props.setProperty("queriesBeforeRetryMaster","0"); props.setProperty("secondsBeforeRetryMaster","0"); for ( boolean autoCommit : new boolean[]{true,false}) { Connection testConn=getUnreliableFailoverConnection(new String[]{HOST_1,HOST_2,HOST_3},props,downedHosts); Statement testStmt=null; try { testConn.setAutoCommit(autoCommit); assertEquals(HOST_2_OK,UnreliableSocketFactory.getHostFromLastConnection()); testStmt=testConn.createStatement(); assertSingleValueQuery(testStmt,"SELECT 1",1L); UnreliableSocketFactory.dontDownHost(HOST_1); UnreliableSocketFactory.dontDownHost(HOST_3); for (int i=0; i < 55; i++) { assertSingleValueQuery(testStmt,"SELECT 1",1L); assertEquals(HOST_2_OK,UnreliableSocketFactory.getHostFromLastConnection()); } UnreliableSocketFactory.downHost(HOST_2); assertEquals(HOST_2_OK,UnreliableSocketFactory.getHostFromLastConnection()); assertSQLException(testStmt,"SELECT 1",COMM_LINK_ERR_PATTERN); assertEquals(HOST_3_OK,UnreliableSocketFactory.getHostFromLastConnection()); testStmt=testConn.createStatement(); assertSingleValueQuery(testStmt,"SELECT 1",1L); UnreliableSocketFactory.dontDownHost(HOST_2); UnreliableSocketFactory.downHost(HOST_3); assertEquals(HOST_3_OK,UnreliableSocketFactory.getHostFromLastConnection()); assertSQLException(testStmt,"SELECT 1",COMM_LINK_ERR_PATTERN); assertEquals(HOST_1_OK,UnreliableSocketFactory.getHostFromLastConnection()); assertConnectionsHistory(HOST_2_OK,HOST_3_OK,HOST_1_OK); } finally { if (testStmt != null) { testStmt.close(); } if (testConn != null) { testConn.close(); } } } }
Tests the automatic fall back to primary host in a failover connection using three hosts and the following sequence of events: + 1.st part: - [\HOST_1 : /HOST_2 : \HOST_3] --> HOST_2 - [/HOST_1 : /HOST_2 : /HOST_3] --> no_change vs HOST_1 (auto fall back) - [/HOST_1 : \HOST_2 : /HOST_3] --> HOST_1 vs no_change + 2.nd part: - [\HOST_1 : /HOST_2 : \HOST_3] --> HOST_2 - [/HOST_1 : /HOST_2 : /HOST_3] --> no_change - [/HOST_1 : \HOST_2 : /HOST_3] --> HOST_3 - [/HOST_1 : /HOST_2 : \HOST_3] --> HOST_1 - /HOST_2 & \HOST_3 The automatic fall back only happens at transaction boundaries and at least 'queriesBeforeRetryMaster' or 'secondsBeforeRetryMaster' is greater than 0. [Legend: "/HOST_n" --> HOST_n up; "\HOST_n" --> HOST_n down]
@Deprecated public static GamaRuntimeException error(final String s){ return error(s,GAMA.getRuntimeScope()); }
This method is deprecated. Use the equivalent method that passes the scope