List of usage examples for java.io ByteArrayOutputStream reset
public synchronized void reset()
From source file:com.geoxp.oss.client.OSSClient.java
private static void changeACL(boolean remove, String ossURL, String sshKeyFingerprint, String secretname, List<String> keyfpr) throws OSSException { SSHAgentClient agent = null;/*w w w .ja v a 2s. c o m*/ HttpClient httpclient = null; try { agent = new SSHAgentClient(); List<SSHKey> sshkeys = agent.requestIdentities(); // // If no SSH Key fingerprint was provided, try all SSH keys available in the agent // List<String> fingerprints = new ArrayList<String>(); if (null == sshKeyFingerprint) { for (SSHKey key : sshkeys) { fingerprints.add(key.fingerprint); } } else { fingerprints.add(sshKeyFingerprint.toLowerCase().replaceAll("[^0-9a-f]", "")); } int idx = 0; for (String fingerprint : fingerprints) { idx++; // // Ask the SSH agent for the SSH key blob // byte[] keyblob = null; for (SSHKey key : sshkeys) { if (key.fingerprint.equals(fingerprint)) { keyblob = key.blob; break; } } // // Throw an exception if this condition is encountered as it can only happen if // there was a provided fingerprint which is not in the agent. // if (null == keyblob) { throw new OSSException("SSH Key " + sshKeyFingerprint + " was not found by your SSH agent."); } // // Retrieve OSS RSA key // RSAPublicKey pubkey = getOSSRSA(ossURL); // // Build the token // // <TS> <<SECRET_NAME><FINGERPRINT1>....<FINGERPRINTN>> <SSH Signing Key Blob> <SSH Signature Blob> // ByteArrayOutputStream token = new ByteArrayOutputStream(); byte[] tsdata = nowBytes(); token.write(CryptoHelper.encodeNetworkString(tsdata)); ByteArrayOutputStream subtoken = new ByteArrayOutputStream(); subtoken.write(CryptoHelper.encodeNetworkString(secretname.getBytes("UTF-8"))); for (String fpr : keyfpr) { subtoken.write(CryptoHelper .encodeNetworkString(fpr.toLowerCase().replaceAll("[^a-f0-9]", "").getBytes("UTF-8"))); } token.write(CryptoHelper.encodeNetworkString(subtoken.toByteArray())); token.write(CryptoHelper.encodeNetworkString(keyblob)); byte[] sigblob = agent.sign(keyblob, token.toByteArray()); token.write(CryptoHelper.encodeNetworkString(sigblob)); // // Encrypt the token with a random AES256 key // byte[] aeskey = new byte[32]; CryptoHelper.getSecureRandom().nextBytes(aeskey); byte[] wrappedtoken = CryptoHelper.wrapAES(aeskey, token.toByteArray()); // // Encrypt the random key with OSS' RSA key // byte[] sealedaeskey = CryptoHelper.encryptRSA(pubkey, aeskey); // // Create the token // token.reset(); token.write(CryptoHelper.encodeNetworkString(wrappedtoken)); token.write(CryptoHelper.encodeNetworkString(sealedaeskey)); // // Base64 encode the encryptedtoken // String b64token = new String(Base64.encode(token.toByteArray()), "UTF-8"); // // Send request to OSS // URIBuilder builder = new URIBuilder(ossURL + (remove ? GuiceServletModule.SERVLET_PATH_REMOVE_ACL : GuiceServletModule.SERVLET_PATH_ADD_ACL)); builder.addParameter("token", b64token); URI uri = builder.build(); String qs = uri.getRawQuery(); HttpPost post = new HttpPost( uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort() + uri.getPath()); post.setHeader("Content-Type", "application/x-www-form-urlencoded"); post.setEntity(new StringEntity(qs)); httpclient = newHttpClient(); HttpResponse response = httpclient.execute(post); HttpEntity resEntity = response.getEntity(); String content = EntityUtils.toString(resEntity, "UTF-8"); post.reset(); if (HttpServletResponse.SC_OK != response.getStatusLine().getStatusCode()) { // Only throw an exception if this is the last SSH key we could try if (idx == fingerprints.size()) { throw new OSSException("None of the provided keys (" + idx + ") could be used to modify ACL. Latest error message was: " + response.getStatusLine().getReasonPhrase()); } else { continue; } } return; } } catch (OSSException osse) { throw osse; } catch (Exception e) { throw new OSSException(e); } finally { if (null != httpclient) { httpclient.getConnectionManager().shutdown(); } if (null != agent) { agent.close(); } } }
From source file:com.hortonworks.hbase.replication.bridge.HBaseServer.java
/** * Setup response for the IPC Call.// w ww . ja va 2 s .com * * @param response buffer to serialize the response into * @param call {@link Call} to which we are setting up the response * @param status {@link Status} of the IPC call * @param rv return value for the IPC Call, if the call was successful * @param errorClass error class, if the the call failed * @param error error message, if the call failed * @throws IOException */ private void setupResponse(ByteArrayOutputStream response, Call call, Status status, Writable rv, String errorClass, String error) throws IOException { response.reset(); DataOutputStream out = new DataOutputStream(response); if (status == Status.SUCCESS) { try { rv.write(out); call.setResponse(rv, status, null, null); } catch (Throwable t) { LOG.warn("Error serializing call response for call " + call, t); // Call back to same function - this is OK since the // buffer is reset at the top, and since status is changed // to ERROR it won't infinite loop. call.setResponse(null, status.ERROR, t.getClass().getName(), StringUtils.stringifyException(t)); } } else { call.setResponse(rv, status, errorClass, error); } }
From source file:org.apache.pdfbox.pdmodel.encryption.StandardSecurityHandler.java
/** * This will compute the user password hash. * * @param password The plain text password. * @param owner The owner password hash. * @param permissions The document permissions. * @param id The document id.//from ww w . j av a 2s .co m * @param encRevision The revision of the encryption. * @param length The length of the encryption key. * @param encryptMetadata The encryption metadata * * @return The user password. * * @throws IOException if the password could not be computed */ public byte[] computeUserPassword(byte[] password, byte[] owner, int permissions, byte[] id, int encRevision, int length, boolean encryptMetadata) throws IOException { ByteArrayOutputStream result = new ByteArrayOutputStream(); byte[] encKey = computeEncryptedKey(password, owner, null, null, null, permissions, id, encRevision, length, encryptMetadata, true); if (encRevision == 2) { encryptDataRC4(encKey, ENCRYPT_PADDING, result); } else if (encRevision == 3 || encRevision == 4) { MessageDigest md = MessageDigests.getMD5(); md.update(ENCRYPT_PADDING); md.update(id); result.write(md.digest()); byte[] iterationKey = new byte[encKey.length]; for (int i = 0; i < 20; i++) { System.arraycopy(encKey, 0, iterationKey, 0, iterationKey.length); for (int j = 0; j < iterationKey.length; j++) { iterationKey[j] = (byte) (iterationKey[j] ^ i); } ByteArrayInputStream input = new ByteArrayInputStream(result.toByteArray()); result.reset(); encryptDataRC4(iterationKey, input, result); } byte[] finalResult = new byte[32]; System.arraycopy(result.toByteArray(), 0, finalResult, 0, 16); System.arraycopy(ENCRYPT_PADDING, 0, finalResult, 16, 16); result.reset(); result.write(finalResult); } return result.toByteArray(); }
From source file:org.deviceconnect.android.deviceplugin.host.camera.CameraOverlay.java
@Override public void onPreviewFrame(final byte[] data, final Camera camera) { synchronized (mCameraLock) { final long currentTime = System.currentTimeMillis(); if (mLastFrameTime != 0) { if ((currentTime - mLastFrameTime) < mFrameInterval) { mLastFrameTime = currentTime; return; }/*from ww w . ja v a 2 s .c o m*/ } if (mCamera != null && mCamera.equals(camera)) { mCamera.setPreviewCallback(null); if (mServer != null) { int format = mPreview.getPreviewFormat(); int width = mPreview.getPreviewWidth(); int height = mPreview.getPreviewHeight(); YuvImage yuvimage = new YuvImage(data, format, width, height, null); Rect rect = new Rect(0, 0, width, height); ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (yuvimage.compressToJpeg(rect, JPEG_COMPRESS_QUALITY, baos)) { byte[] jdata = baos.toByteArray(); int degree = mPreview.getCameraDisplayOrientation(mContext); if (degree == 0) { mServer.offerMedia(jdata); } else { BitmapFactory.Options bitmapFactoryOptions = new BitmapFactory.Options(); bitmapFactoryOptions.inPreferredConfig = Bitmap.Config.RGB_565; Bitmap bmp = BitmapFactory.decodeByteArray(jdata, 0, jdata.length, bitmapFactoryOptions); if (bmp != null) { Matrix m = new Matrix(); m.setRotate(degree * mFacingDirection); Bitmap rotatedBmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), m, true); if (rotatedBmp != null) { baos.reset(); if (rotatedBmp.compress(CompressFormat.JPEG, JPEG_COMPRESS_QUALITY, baos)) { mServer.offerMedia(baos.toByteArray()); } rotatedBmp.recycle(); } bmp.recycle(); } } } } mCamera.setPreviewCallback(this); } mLastFrameTime = currentTime; } }
From source file:org.wings.session.MultipartRequest.java
/** * Parses passed request and stores contained parameters. * * @throws IOException On unrecoverable parsing bugs due to old Tomcat version. *///from ww w . j a v a 2 s . co m protected void processRequest(HttpServletRequest req) throws IOException { String type = req.getContentType(); if (type == null || !type.toLowerCase().startsWith("multipart/form-data")) { urlencodedRequest = true; return; } urlencodedRequest = false; parameters = new HashMap<String, List>(); files = new HashMap<String, UploadedFile>(); for (Iterator iterator = req.getParameterMap().entrySet().iterator(); iterator.hasNext(); /**/) { Map.Entry entry = (Map.Entry) iterator.next(); parameters.put((String) entry.getKey(), new ArrayList(Arrays.asList((String[]) entry.getValue()))); } String boundaryToken = extractBoundaryToken(type); if (boundaryToken == null) { /* * this could happen due to a bug in Tomcat 3.2.2 in combination * with Opera. * Opera sends the boundary on a separate line, which is perfectly * correct regarding the way header may be constructed * (multiline headers). Alas, Tomcat fails to read the header in * the content type line and thus we cannot read it.. haven't * checked later versions of Tomcat, but upgrading is * definitly needed, since we cannot do anything about it here. * (JServ works fine, BTW.) (Henner) */ throw new IOException("Separation boundary was not specified (BUG in Tomcat 3.* with Opera?)"); } MultipartInputStream mimeStream = null; ByteArrayOutputStream headerByteArray; StringBuilder content = new StringBuilder(); HashMap headers = null; int currentByte = 0; int currentPos = 0; int currentTransformByte = 0; String currentParam = null; File uploadFile = null; OutputStream fileStream = null; boolean done; int last = -1; try { mimeStream = new MultipartInputStream(req.getInputStream(), req.getContentLength(), maxSize); while (currentByte != -1) { // Read MIME part header line done = false; headerByteArray = new ByteArrayOutputStream(); while ((currentByte = mimeStream.read()) != -1 && !done) { headerByteArray.write(currentByte); done = (last == '\n' && currentByte == '\r'); last = currentByte; } if (currentByte == -1) break; headers = parseHeader(headerByteArray.toString(req.getCharacterEncoding())); headerByteArray.reset(); currentParam = (String) headers.get("name"); if (headers.size() == 1) { // .. it's not a file byte[] bytes = new byte[req.getContentLength()]; currentPos = 0; while ((currentByte = mimeStream.read()) != -1) { bytes[currentPos] = (byte) currentByte; currentPos++; if (currentPos >= boundaryToken.length()) { int i; for (i = 0; i < boundaryToken.length(); i++) { if (boundaryToken .charAt(boundaryToken.length() - i - 1) != bytes[currentPos - i - 1]) { i = 0; break; } } if (i == boundaryToken.length()) { // end of part .. ByteArrayInputStream bais = new ByteArrayInputStream(bytes, 0, currentPos - boundaryToken.length() - 4); InputStreamReader ir; if (req.getCharacterEncoding() != null) // It's common behaviour of browsers to encode their form input in the character // encoding of the page, though they don't declare the used characterset explicetly // for backward compatibility. ir = new InputStreamReader(bais, req.getCharacterEncoding()); else ir = new InputStreamReader(bais); content.setLength(0); while ((currentTransformByte = ir.read()) != -1) { content.append((char) currentTransformByte); } putParameter(currentParam, content.toString()); break; } } } } else { // .. it's a file String filename = (String) headers.get("filename"); if (filename != null && filename.length() != 0) { // The filename may contain a full path. Cut to just the filename. int slash = Math.max(filename.lastIndexOf('/'), filename.lastIndexOf('\\')); if (slash > -1) { filename = filename.substring(slash + 1); } String name = (String) headers.get("name"); String contentType = (String) headers.get("content-type"); try { uploadFile = File.createTempFile("wings_uploaded", "tmp"); } catch (IOException e) { log.error("couldn't create temp file in '" + System.getProperty("java.io.tmpdir") + "' (CATALINA_TMPDIR set correctly?)", e); throw e; } UploadedFile upload = new UploadedFile(filename, contentType, uploadFile); fileStream = new FileOutputStream(uploadFile); fileStream = UploadFilterManager.createFilterInstance(name, fileStream); AccessibleByteArrayOutputStream byteArray = new AccessibleByteArrayOutputStream(); byte[] bytes = null; int blength = boundaryToken.length(); int i; while ((currentByte = mimeStream.read()) != -1) { byteArray.write(currentByte); for (i = 0; i < blength; i++) { if (boundaryToken.charAt(blength - i - 1) != byteArray.charAt(-i - 1)) { i = 0; if (byteArray.size() > 512 + blength + 2) byteArray.writeTo(fileStream, 512); break; } } if (i == blength) // end of part .. break; } bytes = byteArray.toByteArray(); fileStream.write(bytes, 0, bytes.length - blength - 4); fileStream.close(); files.put(name, upload); putParameter(name, upload.toString()); } else { // workaround for some netscape bug int i; int blength = boundaryToken.length(); while ((currentByte = mimeStream.read()) != -1) { content.append((char) currentByte); if (content.length() >= blength) { for (i = 0; i < blength; i++) { if (boundaryToken.charAt(blength - i - 1) != content .charAt(content.length() - i - 1)) { i = 0; break; } } if (i == blength) break; } } } } currentByte = mimeStream.read(); if (currentByte == '\r' && mimeStream.read() != '\n') log.error("No line return char? " + currentByte); if (currentByte == '-' && mimeStream.read() != '-') log.error("?? No clue " + currentByte); } } catch (IOException ex) { // cleanup and store the exception for notification of SFileChooser log.warn("upload", ex); if (uploadFile != null) uploadFile.delete(); setException(currentParam, ex); } finally { try { fileStream.close(); } catch (Exception ign) { } try { mimeStream.close(); } catch (Exception ign) { } } }
From source file:test.jamocha.languages.clips.SystemTest.java
@Test public void testSimpleWatchedFactAssertion() throws ParseException { final Network network = new Network(); final ByteArrayOutputStream out = initializeAppender(network); {// w w w . j a va 2 s . c om final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network, "(unwatch all)\n(watch facts)\n"); assertThat(returnValues.getLeft(), empty()); assertThat(returnValues.getRight(), empty()); assertThat(out.toString(), isEmptyString()); } { final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network, "(deftemplate t1 (slot s1 (type INTEGER)))\n"); assertThat(returnValues.getLeft(), empty()); assertThat(returnValues.getRight(), empty()); assertThat(out.toString(), isEmptyString()); } { final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network, "(assert (t1 (s1 2)))\n"); final Queue<Object> values = returnValues.getLeft(); assertThat(values, hasSize(1)); final Object value = values.iterator().next(); assertThat(value, instanceOf(String.class)); assertEquals("<Fact-2>", value); assertThat(returnValues.getRight(), empty()); final String output = out.toString(); assertThat(output, not(isEmptyString())); final String[] lines = output.split(linesep); assertThat(lines, arrayWithSize(1)); assertEquals("==> f-2\t(t1 (s1 2))", lines[0]); out.reset(); } }
From source file:org.dbgl.gui.AddGameWizardDialog.java
private Control page1() { final Group group = new Group(shell, SWT.NONE); group.setText(settings.msg("dialog.addgamewizard.step2")); group.setLayout(new GridLayout()); Composite installexeComposite = new Composite(group, SWT.NONE); installexeComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); installexeComposite.setLayout(new GridLayout(3, false)); final Label mainExeLabel = new Label(installexeComposite, SWT.NONE); mainExeLabel.setText(settings.msg("dialog.addgamewizard.installexe")); installExe = new Text(installexeComposite, SWT.BORDER); installExe.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); final BrowseButton installexeBrowseButton = new BrowseButton(installexeComposite, SWT.NONE); installexeBrowseButton.connect(shell, installExe, null, BrowseType.FILE, CanonicalType.INSTALLER, false, null);// w w w . ja v a2 s . com final Label parametersLabel = new Label(installexeComposite, SWT.NONE); parametersLabel.setText(settings.msg("dialog.profile.mainparameters")); installParameters = new Text(installexeComposite, SWT.BORDER); installParameters.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); final Label manualLabel = new Label(installexeComposite, SWT.NONE); manualLabel.setText(settings.msg("dialog.addgamewizard.manualmode")); btnInstallManual = new Button(installexeComposite, SWT.CHECK); btnInstallManual.setText(settings.msg("dialog.addgamewizard.manualmodeinfo")); btnInstallManual.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false, 2, 1)); final Group mountGroup = new Group(group, SWT.NONE); GridData gd = new GridData(SWT.FILL, SWT.CENTER, true, false); gd.verticalIndent = 20; mountGroup.setLayoutData(gd); mountGroup.setText(settings.msg("dialog.template.mountingoverview")); mountGroup.setLayout(new GridLayout(2, false)); mountingpoints = new List(mountGroup, SWT.V_SCROLL | SWT.BORDER); mountingpoints.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 3)); mountingpoints.addMouseListener(new MouseAdapter() { public void mouseDoubleClick(final MouseEvent event) { if (mountingpoints.getSelectionIndex() == -1) { doAddMount(); } else { doEditMount(); } } }); final Button addButton = new Button(mountGroup, SWT.NONE); addButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); addButton.setText(settings.msg("dialog.template.mount.add")); addButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(final SelectionEvent event) { doAddMount(); } }); final Button editButton = new Button(mountGroup, SWT.NONE); editButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); editButton.setText(settings.msg("dialog.template.mount.edit")); editButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(final SelectionEvent event) { doEditMount(); } }); final Button removeButton = new Button(mountGroup, SWT.NONE); removeButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); removeButton.setText(settings.msg("dialog.template.mount.remove")); removeButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(final SelectionEvent event) { doRemoveMount(); } }); VerifyListener addMountListener = new VerifyListener() { public void verifyText(final VerifyEvent event) { if (event.text.length() > 1) { addMountIfNoMounts(event.text); } } }; installExe.addVerifyListener(addMountListener); Group associationGroup = new Group(group, SWT.NONE); associationGroup.setText(settings.msg("dialog.template.association")); associationGroup.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); associationGroup.setLayout(new GridLayout(2, false)); final Label dbversionLabel = new Label(associationGroup, SWT.NONE); dbversionLabel.setText(settings.msg("dialog.template.dosboxversion")); final Combo dbversion = new Combo(associationGroup, SWT.READ_ONLY); dbversion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); dbversion.setVisibleItemCount(20); for (DosboxVersion dbv : dbversionsList) { dbversion.add(dbv.getTitle()); } int dbversionIndex = DosboxVersion.findIndexById(dbversionsList, profile.getDbversionId()); dbversion.select(dbversionIndex); dbversion.addSelectionListener(new SelectionAdapter() { public void widgetSelected(final SelectionEvent event) { try { String[] mounts = profile.getConf().getAutoexec().getMountingpoints(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(bos); Conf newDosboxVersion = new Conf(dbversionsList.get(dbversion.getSelectionIndex()), ps); profile.getConf().switchToDosboxVersion(newDosboxVersion); profile.setDbversionId(newDosboxVersion.getDbversion().getId()); profile.getConf().unmountDosboxMounts(); for (String m : mounts) profile.getConf().addMount(m); mountingpoints.setItems(profile.getConf().getAutoexec().getMountingpoints()); if (bos.size() > 0) { GeneralPurposeDialogs.warningMessage(getParent(), bos.toString()); bos.reset(); } } catch (IOException e) { GeneralPurposeDialogs.warningMessage(getParent(), e); } } }); return group; }
From source file:com.github.hrpc.rpc.Server.java
/** * Setup response for the IPC Call./*from ww w .j a v a2s.c om*/ * * @param responseBuf buffer to serialize the response into * @param call {@link Call} to which we are setting up the response * @param status of the IPC call * @param rv return value for the IPC Call, if the call was successful * @param errorClass error class, if the the call failed * @param error error message, if the call failed * @throws IOException */ private void setupResponse(ByteArrayOutputStream responseBuf, Call call, RpcStatusProto status, RpcErrorCodeProto erCode, Writable rv, String errorClass, String error) throws IOException { responseBuf.reset(); DataOutputStream out = new DataOutputStream(responseBuf); RpcResponseHeaderProto.Builder headerBuilder = RpcResponseHeaderProto.newBuilder(); headerBuilder.setClientId(ByteString.copyFrom(call.clientId)); headerBuilder.setCallId(call.callId); headerBuilder.setRetryCount(call.retryCount); headerBuilder.setStatus(status); headerBuilder.setServerIpcVersionNum(CURRENT_VERSION); if (status == RpcStatusProto.SUCCESS) { RpcResponseHeaderProto header = headerBuilder.build(); final int headerLen = header.getSerializedSize(); int fullLength = CodedOutputStream.computeRawVarint32Size(headerLen) + headerLen; try { if (rv instanceof ProtobufRpcEngine.RpcWrapper) { ProtobufRpcEngine.RpcWrapper resWrapper = (ProtobufRpcEngine.RpcWrapper) rv; fullLength += resWrapper.getLength(); out.writeInt(fullLength); header.writeDelimitedTo(out); rv.write(out); } else { // Have to serialize to buffer to get len final DataOutputBuffer buf = new DataOutputBuffer(); rv.write(buf); byte[] data = buf.getData(); fullLength += buf.getLength(); out.writeInt(fullLength); header.writeDelimitedTo(out); out.write(data, 0, buf.getLength()); } } catch (Throwable t) { LOG.warn("Error serializing call response for call " + call, t); // Call back to same function - this is OK since the // buffer is reset at the top, and since status is changed // to ERROR it won't infinite loop. setupResponse(responseBuf, call, RpcStatusProto.ERROR, RpcErrorCodeProto.ERROR_SERIALIZING_RESPONSE, null, t.getClass().getName(), StringUtils.stringifyException(t)); return; } } else { // Rpc Failure headerBuilder.setExceptionClassName(errorClass); headerBuilder.setErrorMsg(error); headerBuilder.setErrorDetail(erCode); RpcResponseHeaderProto header = headerBuilder.build(); int headerLen = header.getSerializedSize(); final int fullLength = CodedOutputStream.computeRawVarint32Size(headerLen) + headerLen; out.writeInt(fullLength); header.writeDelimitedTo(out); } call.setResponse(ByteBuffer.wrap(responseBuf.toByteArray())); }
From source file:test.jamocha.languages.clips.SystemTest.java
@Test public void testSimpleNegatedExistentialRule() throws ParseException { final Network network = new Network(); final ByteArrayOutputStream out = initializeAppender(network); {// w w w.ja v a 2 s . c om final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network, "(unwatch all)\n(watch facts)\n"); assertThat(returnValues.getLeft(), empty()); assertThat(returnValues.getRight(), empty()); assertThat(out.toString(), isEmptyString()); } { final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network, "(deftemplate t1 (slot s1 (type INTEGER)))\n"); assertThat(returnValues.getLeft(), empty()); assertThat(returnValues.getRight(), empty()); assertThat(out.toString(), isEmptyString()); } { final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network, "(defrule r1 (not (t1)) => (assert (t1 (s1 999))) )\n"); assertThat(returnValues.getLeft(), empty()); assertThat(returnValues.getRight(), empty()); assertThat(out.toString(), isEmptyString()); } { final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network, "(run)\n"); assertThat(returnValues.getLeft(), empty()); assertThat(returnValues.getRight(), empty()); final String[] lines = out.toString().split(linesep); assertThat(lines, arrayWithSize(1)); assertEquals("==> f-2\t(t1 (s1 999))", lines[0]); out.reset(); } { final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network, "(retract 2)\n"); assertThat(returnValues.getLeft(), empty()); assertThat(returnValues.getRight(), empty()); final String[] lines = out.toString().split(linesep); assertThat(lines, arrayWithSize(1)); assertEquals("<== f-2\t(t1 (s1 999))", lines[0]); out.reset(); } { final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network, "(run)\n"); assertThat(returnValues.getLeft(), empty()); assertThat(returnValues.getRight(), empty()); final String[] lines = out.toString().split(linesep); assertThat(lines, arrayWithSize(1)); assertEquals("==> f-3\t(t1 (s1 999))", lines[0]); out.reset(); } }
From source file:org.apache.jackrabbit.core.query.lucene.SQL2IndexingAggregateTest.java
/** * //w w w . j av a 2s . c om * this test is very similar to * {@link SQL2IndexingAggregateTest#testNtFileAggregate() * testNtFileAggregate} but checks embedded index aggregates. * * The aggregation hierarchy is defined in * src/test/repository/workspaces/indexing-test/indexing-configuration.xml * * basically a folder aggregates other folders and files that aggregate a * stream of content. * * see <a href="https://issues.apache.org/jira/browse/JCR-2989">JCR-2989</a> * * nt:folder: recursive="true" recursiveLimit="10" * */ @SuppressWarnings("unchecked") public void testDeepHierarchy() throws Exception { // this parameter IS the 'recursiveLimit' defined in the index // config file int definedRecursiveLimit = 10; int levelsDeep = 14; List<Node> allNodes = new ArrayList<Node>(); List<Node> updatedNodes = new ArrayList<Node>(); List<Node> staleNodes = new ArrayList<Node>(); String sqlBase = "SELECT * FROM [nt:folder] as f WHERE "; String sqlCat = sqlBase + " CONTAINS (f.*, 'cat')"; String sqlDog = sqlBase + " CONTAINS (f.*, 'dog')"; ByteArrayOutputStream out = new ByteArrayOutputStream(); Writer writer = new OutputStreamWriter(out, "UTF-8"); writer.write("the quick brown fox jumps over the lazy dog."); writer.flush(); Node folderRoot = testRootNode.addNode("myFolder", "nt:folder"); Node folderChild = folderRoot; allNodes.add(folderChild); for (int i = 0; i < levelsDeep; i++) { folderChild.addNode("0" + i + "-dummy", "nt:folder"); folderChild = folderChild.addNode("0" + i, "nt:folder"); allNodes.add(folderChild); // -2 because: // 1 because 'i' starts at 0, // + // 1 because we are talking about same node type aggregation levels // extra to the current node that is updated if (i > levelsDeep - definedRecursiveLimit - 2) { updatedNodes.add(folderChild); } } staleNodes.addAll(CollectionUtils.disjunction(allNodes, updatedNodes)); Node file = folderChild.addNode("myFile", "nt:file"); Node resource = file.addNode("jcr:content", "nt:resource"); resource.setProperty("jcr:lastModified", Calendar.getInstance()); resource.setProperty("jcr:encoding", "UTF-8"); resource.setProperty("jcr:mimeType", "text/plain"); resource.setProperty("jcr:data", session.getValueFactory().createBinary(new ByteArrayInputStream(out.toByteArray()))); testRootNode.getSession().save(); // because of the optimizations, the first save is expected to update // ALL nodes // executeSQL2Query(sqlDog, allNodes.toArray(new Node[] {})); // update jcr:data out.reset(); writer.write("the quick brown fox jumps over the lazy cat."); writer.flush(); resource.setProperty("jcr:data", session.getValueFactory().createBinary(new ByteArrayInputStream(out.toByteArray()))); testRootNode.getSession().save(); executeSQL2Query(sqlDog, staleNodes.toArray(new Node[] {})); executeSQL2Query(sqlCat, updatedNodes.toArray(new Node[] {})); // replace jcr:content with unstructured resource.remove(); Node unstrContent = file.addNode("jcr:content", "nt:unstructured"); Node foo = unstrContent.addNode("foo"); foo.setProperty("text", "the quick brown fox jumps over the lazy dog."); testRootNode.getSession().save(); executeSQL2Query(sqlDog, allNodes.toArray(new Node[] {})); executeSQL2Query(sqlCat, new Node[] {}); // remove foo foo.remove(); testRootNode.getSession().save(); executeSQL2Query(sqlDog, staleNodes.toArray(new Node[] {})); executeSQL2Query(sqlCat, new Node[] {}); }