text:
namespace net {

QuicReliableClientStream::QuicReliableClientStream(QuicStreamId id,
                                                   QuicSession* session,
                                                   const BoundNetLog& net_log)
    : QuicDataStream(id, session),
      net_log_(net_log),
      delegate_(NULL) {
}

QuicReliableClientStream::~QuicReliableClientStream() {
  if (delegate_)
    delegate_->OnClose(connection_error());
}

uint32 QuicReliableClientStream::ProcessData(const char* data,
                                             uint32 data_len) {
  // TODO(rch): buffer data if we don't have a delegate.
  if (!delegate_) {
    DLOG(ERROR) << "Missing delegate";
    Reset(QUIC_STREAM_CANCELLED);
    return 0;
  }

  int rv = delegate_->OnDataReceived(data, data_len);
  if (rv != OK) {
    DLOG(ERROR) << "Delegate refused data, rv: " << rv;
    Reset(QUIC_BAD_APPLICATION_PAYLOAD);
    return 0;
  }
  return data_len;
}

void QuicReliableClientStream::OnClose() {
  if (delegate_) {
    delegate_->OnClose(connection_error());
    delegate_ = NULL;
  }
  ReliableQuicStream::OnClose();
}

void QuicReliableClientStream::OnCanWrite() {
  ReliableQuicStream::OnCanWrite();

  if (!HasBufferedData() && !callback_.is_null()) {
    base::ResetAndReturn(&callback_).Run(OK);
  }
}

QuicPriority QuicReliableClientStream::EffectivePriority() const {
  if (delegate_ && delegate_->HasSendHeadersComplete()) {
    return QuicDataStream::EffectivePriority();
  }
  return QuicWriteBlockedList::kHighestPriority;
}

int QuicReliableClientStream::WriteStreamData(
    base::StringPiece data,
    bool fin,
    const CompletionCallback& callback) {
  // We should not have data buffered.
  DCHECK(!HasBufferedData());
  // Writes the data, or buffers it.
  WriteOrBufferData(data, fin, NULL);
  if (!HasBufferedData()) {
    return OK;
  }

  callback_ = callback;
  return ERR_IO_PENDING;
}

void QuicReliableClientStream::SetDelegate(
    QuicReliableClientStream::Delegate* delegate) {
  DCHECK((!delegate_ && delegate) || (delegate_ && !delegate));
  delegate_ = delegate;
}

void QuicReliableClientStream::OnError(int error) {
  if (delegate_) {
    QuicReliableClientStream::Delegate* delegate = delegate_;
    delegate_ = NULL;
    delegate->OnError(error);
  }
}

bool QuicReliableClientStream::CanWrite(const CompletionCallback& callback) {
  bool can_write =  session()->connection()->CanWrite(HAS_RETRANSMITTABLE_DATA);
  if (!can_write) {
    session()->MarkWriteBlocked(id(), EffectivePriority());
    DCHECK(callback_.is_null());
    callback_ = callback;
  }
  return can_write;
}

}  // namespace net


text:
package org.apache.hadoop.fs.azurebfs.contracts.exceptions;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.fs.azurebfs.contracts.services.AzureServiceErrorCode;
import org.apache.hadoop.fs.azurebfs.oauth2.AzureADAuthenticator.HttpException;
import org.apache.hadoop.fs.azurebfs.services.AbfsHttpOperation;

/**
 * Exception to wrap Azure service error responses.
 */
@InterfaceAudience.Public
@InterfaceStability.Evolving
public class AbfsRestOperationException extends AzureBlobFileSystemException {
  private final int statusCode;
  private final AzureServiceErrorCode errorCode;
  private final String errorMessage;

  public AbfsRestOperationException(
      final int statusCode,
      final String errorCode,
      final String errorMessage,
      final Exception innerException) {
    super("Status code: " + statusCode + " error code: " + errorCode + " error message: " + errorMessage, innerException);

    this.statusCode = statusCode;
    this.errorCode = AzureServiceErrorCode.getAzureServiceCode(this.statusCode, errorCode);
    this.errorMessage = errorMessage;
  }

  public AbfsRestOperationException(
      final int statusCode,
      final String errorCode,
      final String errorMessage,
      final Exception innerException,
      final AbfsHttpOperation abfsHttpOperation) {
    super(formatMessage(abfsHttpOperation), innerException);

    this.statusCode = statusCode;
    this.errorCode = AzureServiceErrorCode.getAzureServiceCode(this.statusCode, errorCode);
    this.errorMessage = errorMessage;
  }

  public AbfsRestOperationException(final HttpException innerException) {
    super(innerException.getMessage(), innerException);

    this.statusCode = innerException.getHttpErrorCode();
    this.errorCode = AzureServiceErrorCode.UNKNOWN;
    this.errorMessage = innerException.getMessage();
  }

  public int getStatusCode() {
    return this.statusCode;
  }

  public AzureServiceErrorCode getErrorCode() {
    return this.errorCode;
  }

  public String getErrorMessage() {
    return this.errorMessage;
  }

  private static String formatMessage(final AbfsHttpOperation abfsHttpOperation) {
    // HEAD request response doesn't have StorageErrorCode, StorageErrorMessage.
    if (abfsHttpOperation.getMethod().equals("HEAD")) {
      return String.format(
              "Operation failed: \"%1$s\", %2$s, HEAD, %3$s",
              abfsHttpOperation.getStatusDescription(),
              abfsHttpOperation.getStatusCode(),
              abfsHttpOperation.getUrl().toString());
    }

    return String.format(
            "Operation failed: \"%1$s\", %2$s, %3$s, %4$s, %5$s, \"%6$s\"",
            abfsHttpOperation.getStatusDescription(),
            abfsHttpOperation.getStatusCode(),
            abfsHttpOperation.getMethod(),
            abfsHttpOperation.getUrl().toString(),
            abfsHttpOperation.getStorageErrorCode(),
            // Remove break line to ensure the request id and timestamp can be shown in console.
            abfsHttpOperation.getStorageErrorMessage().replaceAll("\\n", " "));
  }
}

redpajama_set_name: RedPajamaGithub


text:
.class public Lorg/apache/http/impl/conn/LoggingSessionOutputBuffer;
.super Ljava/lang/Object;
.source "LoggingSessionOutputBuffer.java"

# interfaces
.implements Lorg/apache/http/io/SessionOutputBuffer;

# annotations
.annotation runtime Ljava/lang/Deprecated;
.end annotation

.annotation build Lorg/apache/http/annotation/Contract;
    threading = .enum Lorg/apache/http/annotation/ThreadingBehavior;->IMMUTABLE:Lorg/apache/http/annotation/ThreadingBehavior;
.end annotation

# instance fields
.field private final charset:Ljava/lang/String;

.field private final out:Lorg/apache/http/io/SessionOutputBuffer;

.field private final wire:Lorg/apache/http/impl/conn/Wire;

# direct methods
.method public constructor <init>(Lorg/apache/http/io/SessionOutputBuffer;Lorg/apache/http/impl/conn/Wire;)V
    .locals 1

    const/4 v0, 0x0

    invoke-direct {p0, p1, p2, v0}, Lorg/apache/http/impl/conn/LoggingSessionOutputBuffer;-><init>(Lorg/apache/http/io/SessionOutputBuffer;Lorg/apache/http/impl/conn/Wire;Ljava/lang/String;)V

    return-void
.end method

.method public constructor <init>(Lorg/apache/http/io/SessionOutputBuffer;Lorg/apache/http/impl/conn/Wire;Ljava/lang/String;)V
    .locals 1

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    iput-object p1, p0, Lorg/apache/http/impl/conn/LoggingSessionOutputBuffer;->out:Lorg/apache/http/io/SessionOutputBuffer;

    iput-object p2, p0, Lorg/apache/http/impl/conn/LoggingSessionOutputBuffer;->wire:Lorg/apache/http/impl/conn/Wire;

    if-nez p3, :cond_0

    sget-object v0, Lorg/apache/http/Consts;->ASCII:Ljava/nio/charset/Charset;

    invoke-virtual {v0}, Ljava/nio/charset/Charset;->name()Ljava/lang/String;

    move-result-object p3

    :cond_0
    iput-object p3, p0, Lorg/apache/http/impl/conn/LoggingSessionOutputBuffer;->charset:Ljava/lang/String;

    return-void
.end method

# virtual methods
.method public flush()V
    .locals 1
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation

    iget-object v0, p0, Lorg/apache/http/impl/conn/LoggingSessionOutputBuffer;->out:Lorg/apache/http/io/SessionOutputBuffer;

    invoke-interface {v0}, Lorg/apache/http/io/SessionOutputBuffer;->flush()V

    return-void
.end method

.method public getMetrics()Lorg/apache/http/io/HttpTransportMetrics;
    .locals 1

    iget-object v0, p0, Lorg/apache/http/impl/conn/LoggingSessionOutputBuffer;->out:Lorg/apache/http/io/SessionOutputBuffer;

    invoke-interface {v0}, Lorg/apache/http/io/SessionOutputBuffer;->getMetrics()Lorg/apache/http/io/HttpTransportMetrics;

    move-result-object v0

    return-object v0
.end method

.method public write(I)V
    .locals 1
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation

    iget-object v0, p0, Lorg/apache/http/impl/conn/LoggingSessionOutputBuffer;->out:Lorg/apache/http/io/SessionOutputBuffer;

    invoke-interface {v0, p1}, Lorg/apache/http/io/SessionOutputBuffer;->write(I)V

    iget-object v0, p0, Lorg/apache/http/impl/conn/LoggingSessionOutputBuffer;->wire:Lorg/apache/http/impl/conn/Wire;

    invoke-virtual {v0}, Lorg/apache/http/impl/conn/Wire;->enabled()Z

    move-result v0

    if-nez v0, :cond_0

    :goto_0
    return-void

    :cond_0
    iget-object v0, p0, Lorg/apache/http/impl/conn/LoggingSessionOutputBuffer;->wire:Lorg/apache/http/impl/conn/Wire;

    invoke-virtual {v0, p1}, Lorg/apache/http/impl/conn/Wire;->output(I)V

    goto :goto_0
.end method

.method public write([B)V
    .locals 1
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation

    iget-object v0, p0, Lorg/apache/http/impl/conn/LoggingSessionOutputBuffer;->out:Lorg/apache/http/io/SessionOutputBuffer;

    invoke-interface {v0, p1}, Lorg/apache/http/io/SessionOutputBuffer;->write([B)V

    iget-object v0, p0, Lorg/apache/http/impl/conn/LoggingSessionOutputBuffer;->wire:Lorg/apache/http/impl/conn/Wire;

    invoke-virtual {v0}, Lorg/apache/http/impl/conn/Wire;->enabled()Z

    move-result v0

    if-nez v0, :cond_0

    :goto_0
    return-void

    :cond_0
    iget-object v0, p0, Lorg/apache/http/impl/conn/LoggingSessionOutputBuffer;->wire:Lorg/apache/http/impl/conn/Wire;

    invoke-virtual {v0, p1}, Lorg/apache/http/impl/conn/Wire;->output([B)V

    goto :goto_0
.end method

.method public write([BII)V
    .locals 1
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation

    iget-object v0, p0, Lorg/apache/http/impl/conn/LoggingSessionOutputBuffer;->out:Lorg/apache/http/io/SessionOutputBuffer;

    invoke-interface {v0, p1, p2, p3}, Lorg/apache/http/io/SessionOutputBuffer;->write([BII)V

    iget-object v0, p0, Lorg/apache/http/impl/conn/LoggingSessionOutputBuffer;->wire:Lorg/apache/http/impl/conn/Wire;

    invoke-virtual {v0}, Lorg/apache/http/impl/conn/Wire;->enabled()Z

    move-result v0

    if-nez v0, :cond_0

    :goto_0
    return-void

    :cond_0
    iget-object v0, p0, Lorg/apache/http/impl/conn/LoggingSessionOutputBuffer;->wire:Lorg/apache/http/impl/conn/Wire;

    invoke-virtual {v0, p1, p2, p3}, Lorg/apache/http/impl/conn/Wire;->output([BII)V

    goto :goto_0
.end method

.method public writeLine(Ljava/lang/String;)V
    .locals 3
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation

    iget-object v1, p0, Lorg/apache/http/impl/conn/LoggingSessionOutputBuffer;->out:Lorg/apache/http/io/SessionOutputBuffer;

    invoke-interface {v1, p1}, Lorg/apache/http/io/SessionOutputBuffer;->writeLine(Ljava/lang/String;)V

    iget-object v1, p0, Lorg/apache/http/impl/conn/LoggingSessionOutputBuffer;->wire:Lorg/apache/http/impl/conn/Wire;

    invoke-virtual {v1}, Lorg/apache/http/impl/conn/Wire;->enabled()Z

    move-result v1

    if-nez v1, :cond_0

    :goto_0
    return-void

    :cond_0
    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    invoke-virtual {v1, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    const-string/jumbo v2, "\r\n"

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v0

    iget-object v1, p0, Lorg/apache/http/impl/conn/LoggingSessionOutputBuffer;->wire:Lorg/apache/http/impl/conn/Wire;

    iget-object v2, p0, Lorg/apache/http/impl/conn/LoggingSessionOutputBuffer;->charset:Ljava/lang/String;

    invoke-virtual {v0, v2}, Ljava/lang/String;->getBytes(Ljava/lang/String;)[B

    move-result-object v2

    invoke-virtual {v1, v2}, Lorg/apache/http/impl/conn/Wire;->output([B)V

    goto :goto_0
.end method

.method public writeLine(Lorg/apache/http/util/CharArrayBuffer;)V
    .locals 5
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation

    const/4 v4, 0x0

    iget-object v2, p0, Lorg/apache/http/impl/conn/LoggingSessionOutputBuffer;->out:Lorg/apache/http/io/SessionOutputBuffer;

    invoke-interface {v2, p1}, Lorg/apache/http/io/SessionOutputBuffer;->writeLine(Lorg/apache/http/util/CharArrayBuffer;)V

    iget-object v2, p0, Lorg/apache/http/impl/conn/LoggingSessionOutputBuffer;->wire:Lorg/apache/http/impl/conn/Wire;

    invoke-virtual {v2}, Lorg/apache/http/impl/conn/Wire;->enabled()Z

    move-result v2

    if-nez v2, :cond_0

    :goto_0
    return-void

    :cond_0
    new-instance v0, Ljava/lang/String;

    invoke-virtual {p1}, Lorg/apache/http/util/CharArrayBuffer;->buffer()[C

    move-result-object v2

    invoke-virtual {p1}, Lorg/apache/http/util/CharArrayBuffer;->length()I

    move-result v3

    invoke-direct {v0, v2, v4, v3}, Ljava/lang/String;-><init>([CII)V

    new-instance v2, Ljava/lang/StringBuilder;

    invoke-direct {v2}, Ljava/lang/StringBuilder;-><init>()V

    invoke-virtual {v2, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v2

    const-string/jumbo v3, "\r\n"

    invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v2

    invoke-virtual {v2}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    iget-object v2, p0, Lorg/apache/http/impl/conn/LoggingSessionOutputBuffer;->wire:Lorg/apache/http/impl/conn/Wire;

    iget-object v3, p0, Lorg/apache/http/impl/conn/LoggingSessionOutputBuffer;->charset:Ljava/lang/String;

    invoke-virtual {v1, v3}, Ljava/lang/String;->getBytes(Ljava/lang/String;)[B

    move-result-object v3

    invoke-virtual {v2, v3}, Lorg/apache/http/impl/conn/Wire;->output([B)V

    goto :goto_0
.end method


text:
package org.apache.commons.net.telnet;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;

final class TelnetInputStream extends BufferedInputStream implements Runnable
{
    /** End of file has been reached */
    private static final int EOF = -1;

    /** Read would block */
    private static final int WOULD_BLOCK = -2;

    // TODO should these be private enums?
    static final int _STATE_DATA = 0, _STATE_IAC = 1, _STATE_WILL = 2,
                     _STATE_WONT = 3, _STATE_DO = 4, _STATE_DONT = 5,
                     _STATE_SB = 6, _STATE_SE = 7, _STATE_CR = 8, _STATE_IAC_SB = 9;

    private boolean __hasReachedEOF; // @GuardedBy("__queue")
    private volatile boolean __isClosed;
    private boolean __readIsWaiting;
    private int __receiveState, __queueHead, __queueTail, __bytesAvailable;
    private final int[] __queue;
    private final TelnetClient __client;
    private final Thread __thread;
    private IOException __ioException;

    /* TERMINAL-TYPE option (start)*/
    private final int __suboption[] = new int[512];
    private int __suboption_count = 0;
    /* TERMINAL-TYPE option (end)*/

    private volatile boolean __threaded;

    TelnetInputStream(InputStream input, TelnetClient client,
                      boolean readerThread)
    {
        super(input);
        __client = client;
        __receiveState = _STATE_DATA;
        __isClosed = true;
        __hasReachedEOF = false;
        // Make it 2049, because when full, one slot will go unused, and we
        // want a 2048 byte buffer just to have a round number (base 2 that is)
        __queue = new int[2049];
        __queueHead = 0;
        __queueTail = 0;
        __bytesAvailable = 0;
        __ioException = null;
        __readIsWaiting = false;
        __threaded = false;
        if(readerThread) {
            __thread = new Thread(this);
        } else {
            __thread = null;
        }
    }

    TelnetInputStream(InputStream input, TelnetClient client) {
        this(input, client, true);
    }

    void _start()
    {
        if(__thread == null) {
            return;
        }

        int priority;
        __isClosed = false;
        // TODO remove this
        // Need to set a higher priority in case JVM does not use pre-emptive
        // threads.  This should prevent scheduler induced deadlock (rather than
        // deadlock caused by a bug in this code).
        priority = Thread.currentThread().getPriority() + 1;
        if (priority > Thread.MAX_PRIORITY) {
            priority = Thread.MAX_PRIORITY;
        }
        __thread.setPriority(priority);
        __thread.setDaemon(true);
        __thread.start();
        __threaded = true; // tell _processChar that we are running threaded
    }

    // synchronized(__client) critical sections are to protect against
    // TelnetOutputStream writing through the telnet client at same time
    // as a processDo/Will/etc. command invoked from TelnetInputStream
    // tries to write.
    /**
     * Get the next byte of data.
     * IAC commands are processed internally and do not return data.
     *
     * @param mayBlock true if method is allowed to block
     * @return the next byte of data,
     * or -1 (EOF) if end of stread reached,
     * or -2 (WOULD_BLOCK) if mayBlock is false and there is no data available
     */
    private int __read(boolean mayBlock) throws IOException
    {
        int ch;

        while (true)
        {

            // If there is no more data AND we were told not to block,
            // just return WOULD_BLOCK (-2). (More efficient than exception.)
            if(!mayBlock && super.available() == 0) {
                return WOULD_BLOCK;
            }

            // Otherwise, exit only when we reach end of stream.
            if ((ch = super.read()) < 0) {
                return EOF;
            }

            ch = (ch & 0xff);

            /* Code Section added for supporting AYT (start)*/
            synchronized (__client)
            {
                __client._processAYTResponse();
            }
            /* Code Section added for supporting AYT (end)*/

            /* Code Section added for supporting spystreams (start)*/
            __client._spyRead(ch);
            /* Code Section added for supporting spystreams (end)*/

            switch (__receiveState)
            {

            case _STATE_CR:
                if (ch == '\0')
                {
                    // Strip null
                    continue;
                }
                // How do we handle newline after cr?
                //  else if (ch == '\n' && _requestedDont(TelnetOption.ECHO) &&

                // Handle as normal data by falling through to _STATE_DATA case

                //$FALL-THROUGH$
            case _STATE_DATA:
                if (ch == TelnetCommand.IAC)
                {
                    __receiveState = _STATE_IAC;
                    continue;
                }

                if (ch == '\r')
                {
                    synchronized (__client)
                    {
                        if (__client._requestedDont(TelnetOption.BINARY)) {
                            __receiveState = _STATE_CR;
                        } else {
                            __receiveState = _STATE_DATA;
                        }
                    }
                } else {
                    __receiveState = _STATE_DATA;
                }
                break;

            case _STATE_IAC:
                switch (ch)
                {
                case TelnetCommand.WILL:
                    __receiveState = _STATE_WILL;
                    continue;
                case TelnetCommand.WONT:
                    __receiveState = _STATE_WONT;
                    continue;
                case TelnetCommand.DO:
                    __receiveState = _STATE_DO;
                    continue;
                case TelnetCommand.DONT:
                    __receiveState = _STATE_DONT;
                    continue;
                /* TERMINAL-TYPE option (start)*/
                case TelnetCommand.SB:
                    __suboption_count = 0;
                    __receiveState = _STATE_SB;
                    continue;
                /* TERMINAL-TYPE option (end)*/
                case TelnetCommand.IAC:
                    __receiveState = _STATE_DATA;
                    break; // exit to enclosing switch to return IAC from read
                case TelnetCommand.SE: // unexpected byte! ignore it (don't send it as a command)
                    __receiveState = _STATE_DATA;
                    continue;
                default:
                    __receiveState = _STATE_DATA;
                    __client._processCommand(ch); // Notify the user
                    continue; // move on the next char
                }
                break; // exit and return from read
            case _STATE_WILL:
                synchronized (__client)
                {
                    __client._processWill(ch);
                    __client._flushOutputStream();
                }
                __receiveState = _STATE_DATA;
                continue;
            case _STATE_WONT:
                synchronized (__client)
                {
                    __client._processWont(ch);
                    __client._flushOutputStream();
                }
                __receiveState = _STATE_DATA;
                continue;
            case _STATE_DO:
                synchronized (__client)
                {
                    __client._processDo(ch);
                    __client._flushOutputStream();
                }
                __receiveState = _STATE_DATA;
                continue;
            case _STATE_DONT:
                synchronized (__client)
                {
                    __client._processDont(ch);
                    __client._flushOutputStream();
                }
                __receiveState = _STATE_DATA;
                continue;
            /* TERMINAL-TYPE option (start)*/
            case _STATE_SB:
                switch (ch)
                {
                case TelnetCommand.IAC:
                    __receiveState = _STATE_IAC_SB;
                    continue;
                default:
                    // store suboption char
                    if (__suboption_count < __suboption.length) {
                        __suboption[__suboption_count++] = ch;
                    }
                    break;
                }
                __receiveState = _STATE_SB;
                continue;
            case _STATE_IAC_SB: // IAC received during SB phase
                switch (ch)
                {
                case TelnetCommand.SE:
                    synchronized (__client)
                    {
                        __client._processSuboption(__suboption, __suboption_count);
                        __client._flushOutputStream();
                    }
                    __receiveState = _STATE_DATA;
                    continue;
                case TelnetCommand.IAC: // De-dup the duplicated IAC
                    if (__suboption_count < __suboption.length) {
                        __suboption[__suboption_count++] = ch;
                    }
                    break;
                default:            // unexpected byte! ignore it
                    break;
                }
                __receiveState = _STATE_SB;
                continue;
            /* TERMINAL-TYPE option (end)*/
            }

            break;
        }

        return ch;
    }

    // synchronized(__client) critical sections are to protect against
    // TelnetOutputStream writing through the telnet client at same time
    // as a processDo/Will/etc. command invoked from TelnetInputStream
    // tries to write. Returns true if buffer was previously empty.
    private boolean __processChar(int ch) throws InterruptedException
    {
        // Critical section because we're altering __bytesAvailable,
        // __queueTail, and the contents of _queue.
        boolean bufferWasEmpty;
        synchronized (__queue)
        {
            bufferWasEmpty = (__bytesAvailable == 0);
            while (__bytesAvailable >= __queue.length - 1)
            {
                // The queue is full. We need to wait before adding any more data to it. Hopefully the stream owner
                // will consume some data soon!
                if(__threaded)
                {
                    __queue.notify();
                    try
                    {
                        __queue.wait();
                    }
                    catch (InterruptedException e)
                    {
                        throw e;
                    }
                }
                else
                {
                    // We've been asked to add another character to the queue, but it is already full and there's
                    // no other thread to drain it. This should not have happened!
                    throw new IllegalStateException("Queue is full! Cannot process another character.");
                }
            }

            // Need to do this in case we're not full, but block on a read
            if (__readIsWaiting && __threaded)
            {
                __queue.notify();
            }

            __queue[__queueTail] = ch;
            ++__bytesAvailable;

            if (++__queueTail >= __queue.length) {
                __queueTail = 0;
            }
        }
        return bufferWasEmpty;
    }

    @Override
    public int read() throws IOException
    {
        // Critical section because we're altering __bytesAvailable,
        // __queueHead, and the contents of _queue in addition to
        // testing value of __hasReachedEOF.
        synchronized (__queue)
        {

            while (true)
            {
                if (__ioException != null)
                {
                    IOException e;
                    e = __ioException;
                    __ioException = null;
                    throw e;
                }

                if (__bytesAvailable == 0)
                {
                    // Return EOF if at end of file
                    if (__hasReachedEOF) {
                        return EOF;
                    }

                    // Otherwise, we have to wait for queue to get something
                    if(__threaded)
                    {
                        __queue.notify();
                        try
                        {
                            __readIsWaiting = true;
                            __queue.wait();
                            __readIsWaiting = false;
                        }
                        catch (InterruptedException e)
                        {
                            throw new InterruptedIOException("Fatal thread interruption during read.");
                        }
                    }
                    else
                    {
                        //__alreadyread = false;
                        __readIsWaiting = true;
                        int ch;
                        boolean mayBlock = true;    // block on the first read only

                        do
                        {
                            try
                            {
                                if ((ch = __read(mayBlock)) < 0) { // must be EOF
                                    if(ch != WOULD_BLOCK) {
                                        return (ch);
                                    }
                                }
                            }
                            catch (InterruptedIOException e)
                            {
                                synchronized (__queue)
                                {
                                    __ioException = e;
                                    __queue.notifyAll();
                                    try
                                    {
                                        __queue.wait(100);
                                    }
                                    catch (InterruptedException interrupted)
                                    {
                                        // Ignored
                                    }
                                }
                                return EOF;
                            }

                            try
                            {
                                if(ch != WOULD_BLOCK)
                                {
                                    __processChar(ch);
                                }
                            }
                            catch (InterruptedException e)
                            {
                                if (__isClosed) {
                                    return EOF;
                                }
                            }

                            // Reads should not block on subsequent iterations. Potentially, this could happen if the
                            // remaining buffered socket data consists entirely of Telnet command sequence and no "user" data.
                            mayBlock = false;

                        }
                        // Continue reading as long as there is data available and the queue is not full.
                        while (super.available() > 0 && __bytesAvailable < __queue.length - 1);

                        __readIsWaiting = false;
                    }
                    continue;
                }
                else
                {
                    int ch;

                    ch = __queue[__queueHead];

                    if (++__queueHead >= __queue.length) {
                        __queueHead = 0;
                    }

                    --__bytesAvailable;

            // Need to explicitly notify() so available() works properly
            if(__bytesAvailable == 0 && __threaded) {
                __queue.notify();
            }

                    return ch;
                }
            }
        }
    }

    /***
     * Reads the next number of bytes from the stream into an array and
     * returns the number of bytes read.  Returns -1 if the end of the
     * stream has been reached.
     *

     * @param buffer  The byte array in which to store the data.
     * @return The number of bytes read. Returns -1 if the
     *          end of the message has been reached.
     * @exception IOException If an error occurs in reading the underlying
     *            stream.
     ***/
    @Override
    public int read(byte buffer[]) throws IOException
    {
        return read(buffer, 0, buffer.length);
    }

    /***
     * Reads the next number of bytes from the stream into an array and returns
     * the number of bytes read.  Returns -1 if the end of the
     * message has been reached.  The characters are stored in the array
     * starting from the given offset and up to the length specified.
     *

     * @param buffer The byte array in which to store the data.
     * @param offset  The offset into the array at which to start storing data.
     * @param length   The number of bytes to read.
     * @return The number of bytes read. Returns -1 if the
     *          end of the stream has been reached.
     * @exception IOException If an error occurs while reading the underlying
     *            stream.
     ***/
    @Override
    public int read(byte buffer[], int offset, int length) throws IOException
    {
        int ch, off;

        if (length < 1) {
            return 0;
        }

        // Critical section because run() may change __bytesAvailable
        synchronized (__queue)
        {
            if (length > __bytesAvailable) {
                length = __bytesAvailable;
            }
        }

        if ((ch = read()) == EOF) {
            return EOF;
        }

        off = offset;

        do
        {
            buffer[offset++] = (byte)ch;
        }
        while (--length > 0 && (ch = read()) != EOF);

        //__client._spyRead(buffer, off, offset - off);
        return (offset - off);
    }

    /*** Returns false.  Mark is not supported. ***/
    @Override
    public boolean markSupported()
    {
        return false;
    }

    @Override
    public int available() throws IOException
    {
        // Critical section because run() may change __bytesAvailable
        synchronized (__queue)
        {
            if (__threaded) { // Must not call super.available when running threaded: NET-466
                return __bytesAvailable;
            } else {
                return __bytesAvailable + super.available();
            }
        }
    }

    // Cannot be synchronized.  Will cause deadlock if run() is blocked
    // in read because BufferedInputStream read() is synchronized.
    @Override
    public void close() throws IOException
    {
        // Completely disregard the fact thread may still be running.
        // We can't afford to block on this close by waiting for
        // thread to terminate because few if any JVM's will actually
        // interrupt a system read() from the interrupt() method.
        super.close();

        synchronized (__queue)
        {
            __hasReachedEOF = true;
            __isClosed      = true;

            if (__thread != null && __thread.isAlive())
            {
                __thread.interrupt();
            }

            __queue.notifyAll();
        }

    }

//    @Override
    public void run()
    {
        int ch;

        try
        {
_outerLoop:
            while (!__isClosed)
            {
                try
                {
                    if ((ch = __read(true)) < 0) {
                        break;
                    }
                }
                catch (InterruptedIOException e)
                {
                    synchronized (__queue)
                    {
                        __ioException = e;
                        __queue.notifyAll();
                        try
                        {
                            __queue.wait(100);
                        }
                        catch (InterruptedException interrupted)
                        {
                            if (__isClosed) {
                                break _outerLoop;
                            }
                        }
                        continue;
                    }
                } catch(RuntimeException re) {
                    // We treat any runtime exceptions as though the
                    // stream has been closed.  We close the
                    // underlying stream just to be sure.
                    super.close();
                    // Breaking the loop has the effect of setting
                    // the state to closed at the end of the method.
                    break _outerLoop;
                }

                // Process new character
                boolean notify = false;
                try
                {
                    notify = __processChar(ch);
                }
                catch (InterruptedException e)
                {
                    if (__isClosed) {
                        break _outerLoop;
                    }
                }

                // Notify input listener if buffer was previously empty
                if (notify) {
                    __client.notifyInputListener();
                }
            }
        }
        catch (IOException ioe)
        {
            synchronized (__queue)
            {
                __ioException = ioe;
            }
            __client.notifyInputListener();
        }

        synchronized (__queue)
        {
            __isClosed      = true; // Possibly redundant
            __hasReachedEOF = true;
            __queue.notify();
        }

        __threaded = false;
    }
}

/* Emacs configuration
 * Local variables:        **
 * mode:             java  **
 * c-basic-offset:   4     **
 * indent-tabs-mode: nil   **
 * End:                    **
 */


text:
<?php

/**
 * @file
 * Contains \Drupal\Core\Entity\EntityFormBuilderInterface.
 */

namespace Drupal\Core\Entity;

/**
 * Builds entity forms.
 */
interface EntityFormBuilderInterface {

  /**
   * Returns the built and processed entity form for the given entity.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity to be created or edited.
   * @param string $operation
   *   (optional) The operation identifying the form variation to be returned.
   *   Defaults to 'default'. This is typically used in routing:
   *   @code
   *   _entity_form: node.book_outline
   *   @endcode
   *   where "book_outline" is the value of $operation.
   * @param array $form_state_additions
   *   (optional) An associative array used to build the current state of the
   *   form. Use this to pass additional information to the form, such as the
   *   langcode. Defaults to an empty array.
   *
   * @code
   *   $form_state_additions['langcode'] = $langcode;
   *   $form = \Drupal::service('entity.form_builder')->getForm($entity, 'default', $form_state_additions);
   * @endcode
   *
   * @return array
   *   The processed form for the given entity and operation.
   */
  public function getForm(EntityInterface $entity, $operation = 'default', array $form_state_additions = array());

}


text:
package com.emmanouilpapadimitrou.healthapp.Fragments;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.emmanouilpapadimitrou.healthapp.Activities.PatientsActivity;
import com.emmanouilpapadimitrou.healthapp.POJOs.Message;
import com.emmanouilpapadimitrou.healthapp.POJOs.Patient;
import com.emmanouilpapadimitrou.healthapp.POJOs.Users;
import com.emmanouilpapadimitrou.healthapp.R;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class ChatFragment extends Fragment implements View.OnClickListener {

    private FirebaseUser fUser;
    private FirebaseAuth firebaseAuth;
    private FirebaseDatabase database;
    private DatabaseReference referenceDB;
    private DatabaseReference usersDB;
    private Patient patient;
    private EditText editMessage;
    private FloatingActionButton sendMessageBtn;
    private RecyclerView messageList;
    private Timer timer;
    private String nameToWrite;
    private String getType;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_chat, container, false);

        //Μεταβλητή που μας δίνει τα στοιχεία του συνδεδεμένου χρήστη
        firebaseAuth = FirebaseAuth.getInstance();

        //Παίρνουμε τον επιλεγμένο χρήστη με όλα του τα στοιχεία
        patient = ((PatientsActivity)getActivity()).getCurrentPatient();

        //Ορισμός της βάσης στην μεταβλητή για οποιαδήποτε μελλοντική χρήστη
        database = FirebaseDatabase.getInstance();
        referenceDB =  FirebaseDatabase.getInstance().getReference().child("messages").child(patient.getId());

        editMessage = (EditText) view.findViewById(R.id.editMessage);

        sendMessageBtn = (FloatingActionButton) view.findViewById(R.id.sendMessageBtn);
        sendMessageBtn.setOnClickListener(this);

        final FirebaseRecyclerAdapter <Message,MessageViewHolder> FBRA = new FirebaseRecyclerAdapter<Message, MessageViewHolder>(
                Message.class,
                R.layout.single_message,
                MessageViewHolder.class,
                referenceDB
        ) {
            @Override
            protected void populateViewHolder(MessageViewHolder viewHolder, Message model, int position) {
                viewHolder.setContent(model.getContent());
                viewHolder.setName(model.getName());
                viewHolder.setTime(model.getTime());

            }
        };

        messageList = (RecyclerView) view.findViewById(R.id.messageRec);
        messageList.setHasFixedSize(true);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setStackFromEnd(true);
        messageList.setLayoutManager(linearLayoutManager);
        messageList.setAdapter(FBRA);

        messageList.scrollToPosition(messageList.getAdapter().getItemCount() - 1);

        return view;
    }

    @Override
    public void onClick(View v) {
        if(v == sendMessageBtn){
            fUser = firebaseAuth.getCurrentUser();
            usersDB = FirebaseDatabase.getInstance().getReference().child("users").child(fUser.getUid());
            final String messageValue = editMessage.getText().toString().trim();
            if(!TextUtils.isEmpty(messageValue)){
                final DatabaseReference newPost = referenceDB.push();
                usersDB.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        newPost.child("content").setValue(messageValue);

                        getType = dataSnapshot.child("type").getValue().toString();
                        if(getType.equals("doctor")){
                            nameToWrite = "Δρ. " + dataSnapshot.child("name").getValue() + " " + dataSnapshot.child("surname").getValue();
                        }
                        else{
                            nameToWrite = dataSnapshot.child("name").getValue() + " " + dataSnapshot.child("surname").getValue();
                        }

                        newPost.child("name").setValue(nameToWrite).addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {

                            }
                        });

                        Calendar calendar = Calendar.getInstance();
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
                        String time = simpleDateFormat.format(calendar.getTime());

                        newPost.child("time").setValue(time).addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {

                            }
                        });

                        editMessage.setText("");
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });

            }
        }
    }

    public static class MessageViewHolder extends RecyclerView.ViewHolder{

        View mView;
        public MessageViewHolder(View itemView) {
            super(itemView);
            mView = itemView;
        }

        public void setContent(String content){
            TextView messageText = (TextView) mView.findViewById(R.id.messageText);
            messageText.setText(content);
        }

        public void setName(String name){
            TextView usernameText = (TextView) mView.findViewById(R.id.usernameText);
            usernameText.setText(name);
        }

        public void setTime(String time){
            TextView messageTime = (TextView) mView.findViewById(R.id.messageTime);
            messageTime.setText(time);
        }
    }
}


text:
"""Script for unittesting the confd client module"""

import socket
import unittest

from ganeti import confd
from ganeti import constants
from ganeti import errors

import ganeti.confd.client

import testutils

class ResettableMock(object):
  def __init__(self, *args, **kwargs):
    self.Reset()

  def Reset(self):
    pass

class MockLogger(ResettableMock):
  def Reset(self):
    self.debug_count = 0
    self.warn_count = 0
    self.error_count = 0

  def debug(string):
    self.debug_count += 1

  def warning(string):
    self.warn_count += 1

  def error(string):
    self.error_count += 1

class MockConfdAsyncUDPClient(ResettableMock):
  def Reset(self):
    self.send_count = 0
    self.last_address = ''
    self.last_port = -1
    self.last_sent = ''

  def enqueue_send(self, address, port, payload):
    self.send_count += 1
    self.last_payload = payload
    self.last_port = port
    self.last_address = address

class MockCallback(ResettableMock):
  def Reset(self):
    self.call_count = 0
    self.last_up = None

  def __call__(self, up):
    """Callback

    @type up: L{ConfdUpcallPayload}
    @param up: upper callback

    """
    self.call_count += 1
    self.last_up = up

class MockTime(ResettableMock):
  def Reset(self):
    self.mytime  = 1254213006.5175071

  def time(self):
    return self.mytime

  def increase(self, delta):
    self.mytime += delta

class _BaseClientTest:
  """Base class for client tests"""
  mc_list = None
  new_peers = None
  family = None

  def setUp(self):
    self.mock_time = MockTime()
    confd.client.time = self.mock_time
    confd.client.ConfdAsyncUDPClient = MockConfdAsyncUDPClient
    self.logger = MockLogger()
    hmac_key = "mykeydata"
    self.callback = MockCallback()
    self.client = confd.client.ConfdClient(hmac_key, self.mc_list,
                                           self.callback, logger=self.logger)

  def testRequest(self):
    req1 = confd.client.ConfdClientRequest(type=constants.CONFD_REQ_PING)
    req2 = confd.client.ConfdClientRequest(type=constants.CONFD_REQ_PING)
    self.assertNotEqual(req1.rsalt, req2.rsalt)
    self.assertEqual(req1.protocol, constants.CONFD_PROTOCOL_VERSION)
    self.assertEqual(req2.protocol, constants.CONFD_PROTOCOL_VERSION)
    self.assertRaises(errors.ConfdClientError, confd.client.ConfdClientRequest,
                      type=-33)

  def testClientSend(self):
    req = confd.client.ConfdClientRequest(type=constants.CONFD_REQ_PING)
    self.client.SendRequest(req)
    # Cannot send the same request twice
    self.assertRaises(errors.ConfdClientError, self.client.SendRequest, req)
    req2 = confd.client.ConfdClientRequest(type=constants.CONFD_REQ_PING)
    # Coverage is too big
    self.assertRaises(errors.ConfdClientError, self.client.SendRequest,
                      req2, coverage=15)
    self.assertEquals(self.client._socket.send_count,
                      constants.CONFD_DEFAULT_REQ_COVERAGE)
    # Send with max coverage
    self.client.SendRequest(req2, coverage=-1)
    self.assertEquals(self.client._socket.send_count,
                      constants.CONFD_DEFAULT_REQ_COVERAGE + len(self.mc_list))
    self.assert_(self.client._socket.last_address in self.mc_list)

  def testClientExpire(self):
    req = confd.client.ConfdClientRequest(type=constants.CONFD_REQ_PING)
    self.client.SendRequest(req)
    # Make a couple of seconds pass ;)
    self.mock_time.increase(2)
    # Now sending the second request
    req2 = confd.client.ConfdClientRequest(type=constants.CONFD_REQ_PING)
    self.client.SendRequest(req2)
    self.mock_time.increase(constants.CONFD_CLIENT_EXPIRE_TIMEOUT - 1)
    # First request should be expired, second one should not
    self.client.ExpireRequests()
    self.assertEquals(self.callback.call_count, 1)
    self.assertEquals(self.callback.last_up.type, confd.client.UPCALL_EXPIRE)
    self.assertEquals(self.callback.last_up.salt, req.rsalt)
    self.assertEquals(self.callback.last_up.orig_request, req)
    self.mock_time.increase(3)
    self.assertEquals(self.callback.call_count, 1)
    self.client.ExpireRequests()
    self.assertEquals(self.callback.call_count, 2)
    self.assertEquals(self.callback.last_up.type, confd.client.UPCALL_EXPIRE)
    self.assertEquals(self.callback.last_up.salt, req2.rsalt)
    self.assertEquals(self.callback.last_up.orig_request, req2)

  def testClientCascadeExpire(self):
    req = confd.client.ConfdClientRequest(type=constants.CONFD_REQ_PING)
    self.client.SendRequest(req)
    self.mock_time.increase(constants.CONFD_CLIENT_EXPIRE_TIMEOUT +1)
    req2 = confd.client.ConfdClientRequest(type=constants.CONFD_REQ_PING)
    self.client.SendRequest(req2)
    self.assertEquals(self.callback.call_count, 1)

  def testUpdatePeerList(self):
    self.client.UpdatePeerList(self.new_peers)
    self.assertEquals(self.client._peers, self.new_peers)
    req = confd.client.ConfdClientRequest(type=constants.CONFD_REQ_PING)
    self.client.SendRequest(req)
    self.assertEquals(self.client._socket.send_count, len(self.new_peers))
    self.assert_(self.client._socket.last_address in self.new_peers)

  def testSetPeersFamily(self):
    self.client._SetPeersAddressFamily()
    self.assertEquals(self.client._family, self.family)
    mixed_peers = ["192.0.2.99", "2001:db8:beef::13"]
    self.client.UpdatePeerList(mixed_peers)
    self.assertRaises(errors.ConfdClientError,
                      self.client._SetPeersAddressFamily)

class TestIP4Client(unittest.TestCase, _BaseClientTest):
  """Client tests"""
  mc_list = ["192.0.2.1",
             "192.0.2.2",
             "192.0.2.3",
             "192.0.2.4",
             "192.0.2.5",
             "192.0.2.6",
             "192.0.2.7",
             "192.0.2.8",
             "192.0.2.9",
            ]
  new_peers = ["198.51.100.1", "198.51.100.2"]
  family = socket.AF_INET

  def setUp(self):
    unittest.TestCase.setUp(self)
    _BaseClientTest.setUp(self)

class TestIP6Client(unittest.TestCase, _BaseClientTest):
  """Client tests"""
  mc_list = ["2001:db8::1",
             "2001:db8::2",
             "2001:db8::3",
             "2001:db8::4",
             "2001:db8::5",
             "2001:db8::6",
             "2001:db8::7",
             "2001:db8::8",
             "2001:db8::9",
            ]
  new_peers = ["2001:db8:beef::11", "2001:db8:beef::12"]
  family = socket.AF_INET6

  def setUp(self):
    unittest.TestCase.setUp(self)
    _BaseClientTest.setUp(self)

if __name__ == "__main__":
  testutils.GanetiTestProgram()


text:
package org.pentaho.osgi.platform.plugin.deployer.impl.handlers.pluginxml;

import org.pentaho.osgi.platform.plugin.deployer.api.PluginHandlingException;
import org.pentaho.osgi.platform.plugin.deployer.api.PluginMetadata;
import org.pentaho.osgi.platform.plugin.deployer.impl.JSONUtil;
import org.pentaho.osgi.platform.plugin.deployer.impl.handlers.PluginXmlFileHandler;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.pentaho.osgi.platform.plugin.deployer.impl.handlers.pluginxml.PluginXmlStaticPathsHandler
    .BLUEPRINT_BEAN_NS;

/**
 * Created by bryan on 8/29/14.
 */
public class PluginXmlExternalResourcesHandler extends PluginXmlFileHandler {
  public static final String EXTERNAL_RESOURCES_FILE = "META-INF/js/externalResources.json";
  private static final String LIST_DELIMITER = ",\n    ";

  private JSONUtil jsonUtil;

  public PluginXmlExternalResourcesHandler() {
    super( "//external-resources/file" );
  }

  public void setJsonUtil( JSONUtil jsonUtil ) {
    this.jsonUtil = jsonUtil;
  }

  @Override protected void handle( String relativePath, List<Node> nodes, PluginMetadata pluginMetadata )
      throws PluginHandlingException {
    if ( nodes.size() > 0 ) {
      Map<String, List<String>> contextMap = new HashMap<String, List<String>>();
      for ( Node node : nodes ) {
        Map<String, String> attributes = getAttributes( node );
        String context = attributes.get( "context" );
        List<String> contextFiles = contextMap.get( context );
        if ( contextFiles == null ) {
          contextFiles = new ArrayList<String>();
          contextMap.put( context, contextFiles );
        }
        String contextFile = node.getTextContent();
        if ( !contextFile.startsWith( "/" ) ) {
          contextFile = "/" + contextFile;
        }
        contextFiles.add( contextFile );
      }

      // Pretty print the map while still escaping all variables
      FileWriter fileWriter = null;
      try {
        fileWriter = pluginMetadata.getFileWriter( EXTERNAL_RESOURCES_FILE );
        fileWriter.write( jsonUtil.prettyPrintMapStringListString( contextMap ) );
      } catch ( IOException e ) {
        throw new PluginHandlingException( e );
      } finally {
        if ( fileWriter != null ) {
          try {
            fileWriter.close();
          } catch ( IOException e ) {
            // Ignore
          }
        }
      }
      Document blueprint = pluginMetadata.getBlueprint();
      for ( Map.Entry<String, List<String>> stringListEntry : contextMap.entrySet() ) {
        for ( String string : stringListEntry.getValue() ) {
          Element service = blueprint.createElementNS( BLUEPRINT_BEAN_NS,
              "service" );
          service.setAttribute( "interface", "org.pentaho.platform.api.engine.IPlatformWebResource" );

          Element bean = blueprint.createElementNS( BLUEPRINT_BEAN_NS,
              "bean" );
          bean.setAttribute( "class", "org.pentaho.platform.pdi.PlatformWebResource" );

          Element argument = blueprint.createElementNS( BLUEPRINT_BEAN_NS, "argument" );
          argument.setAttribute( "value", stringListEntry.getKey() );
          bean.appendChild( argument );

          argument = blueprint.createElementNS( BLUEPRINT_BEAN_NS, "argument" );
          argument.setAttribute( "value", string );
          bean.appendChild( argument );
          service.appendChild( bean );

          blueprint.getDocumentElement().appendChild( service );
        }
      }
    }
  }
}


text:
package org.wso2.identity.scenarios.test.scim2;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.identity.scenarios.commons.ScenarioTestBase;
import org.wso2.identity.scenarios.commons.util.Constants;
import org.wso2.identity.scenarios.commons.util.SCIMProvisioningUtil;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.wso2.identity.scenarios.commons.util.IdentityScenarioUtil.getJSONFromResponse;

public class ProvisionEmailUserSCIM2TestCase extends ScenarioTestBase {

    private CloseableHttpClient client;
    private String userNameResponse;
    private final String EMAIL_ID="scim2user@wso2.com";
    private String userId;

    HttpResponse response;

    @BeforeClass(alwaysRun = true)
    public void testInit() throws Exception {

        client = HttpClients.createDefault();
        super.init();
    }

    @Test(description = "1.1.2.1.2.14")
    public void testSCIM2CreateUser() throws Exception {

        JSONObject rootObject = new JSONObject();
        JSONArray schemas = new JSONArray();
        rootObject.put(SCIMConstants.SCHEMAS_ATTRIBUTE, schemas);
        JSONObject names = new JSONObject();
        names.put(SCIMConstants.GIVEN_NAME_ATTRIBUTE, SCIMConstants.GIVEN_NAME_CLAIM_VALUE);
        rootObject.put(SCIMConstants.NAME_ATTRIBUTE, names);
        rootObject.put(SCIMConstants.USER_NAME_ATTRIBUTE, EMAIL_ID);
        rootObject.put(SCIMConstants.PASSWORD_ATTRIBUTE, SCIMConstants.PASSWORD);

        response = SCIMProvisioningUtil.provisionUserSCIM(backendURL, rootObject, Constants.SCIMEndpoints.SCIM2_ENDPOINT,
                Constants.SCIMEndpoints.SCIM_ENDPOINT_USER, ADMIN_USERNAME, ADMIN_PASSWORD);
        assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_CREATED, "Username format is not " +
                "valid ");

        userNameResponse = rootObject.get(SCIMConstants.USER_NAME_ATTRIBUTE).toString();
        assertEquals(userNameResponse, EMAIL_ID, "username not found");

        JSONObject responseObj = getJSONFromResponse(this.response);
        userId = (responseObj).get(SCIMConstants.ID_ATTRIBUTE).toString();
        assertNotNull(userId);
    }

    @AfterClass(alwaysRun = true)
    private void cleanUp() throws Exception {

        response = SCIMProvisioningUtil.deleteUser(backendURL, userId, Constants.SCIMEndpoints.SCIM2_ENDPOINT,
                Constants.SCIMEndpoints.SCIM_ENDPOINT_USER, ADMIN_USERNAME, ADMIN_PASSWORD);
        assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_NO_CONTENT, "User has not been " +
                "deleted successfully");
    }

}


text:
layout: default
title: New Concepts
---

    Improve this doc

Ionic 2 brings even more parity to native SDKs like iOS and Android for the web stack.

With that in mind, some core components (like routing) work differently in v2 than v1.

### Navigation

In Ionic 1, we used UI Router with URL routing heavily to define navigation in your app.

The overwhelming feedback from Ionic 1 developers is that the routing and navigation
system was too difficult to use in practice. It was challenging to correctly map
URLs to views, and the navigation system didn't give the developer enough fine-grained control.

With v2, we've taken a more native-friendly navigation approach with a simpler `push/pop` system.

For example, in v1 we'd create a `ContactDetail` page like this:

```javascript
$stateProvider
  .state('contact', {
    url: "/contact/:contactId",
    templateUrl: "templates/contact.html",
    controller: 'ContactCtrl'
  });
```

Then, to navigate to this, you'd do `<a ui-sref="contact({contact: contact})">{{contact.name}}</a>`

We'd also need to make sure we wired up the current `<ion-nav-view name>` which was considerably more
challenging when using nested navigation. Last but not least, we'd need to define and implement `ContactCtrl`.

In v2, this works a bit differently. Instead of navigating through URLs and routing (which is still
  possible as we will see a bit later), we push and pop views onto the stack:

`<ion-item (click)="showContact(contact)">{{contact.name}}</ion-item>``

```javascript
class ContactsPage {
  showContact(contact) {
    this.nav.push(ContactDetail, {
      contact: contact
    });
  }
}
```

There are also shortcut directives we can use for links much like `ui-sref`, such as
`nav-push` and `nav-pop` which can be used like this:

```html
<button [nav-push]="myContactComponent"
  [push-data]="contact">See contact</button>
```

```html
<button nav-pop>Go back</button>
```

The really nice thing about this is you can infinitely navigate now (for example,
  you can keep pushing new `ContactDetail` pages onto the stack), and
control things like animation and the history stack the user has to navigate through.

You can also navigate inside of practically any container. For example, a modal window that slides up
can have its own navigation, and two split views can navigate independently, something
that was not possible before.

It also makes it incredibly easy to navigate to the same page in completely different
contexts. For example, if you were building something similar to Apple's App Store
app where there are multiple tabs at the bottom and each tab navigates independently,
you could navigate to an `AppDetail` page from any tab, which is exactly how the App Store app works.

For example, here's how the Minecraft `AppDetail` page looks in different tabs:

Notice the page is exactly the same, but the way the user navigated to it is different.

This hits on a core change in Ionic 2: __the history state of the app is now your
responsibility as a developer.__ It's up to you to make sure navigation provides
a good UX, but you have the freedom to navigate as you see fit.

### Routing

Routing has changed significantly in Ionic 2 to make it easier to fully control the
history UX for end users.

In Ionic 2, routing is used more for breadcrumbs and loading state than it is for active
navigation or full history reconstruction. For example, a URL provides a way to deep link to different views (or pages) of
your app (for example, loading the camera view in Instagram from another app),
but in Ionic 2 changing the location bar does not necessarily change the history the user
experiences in the app (a major source of complexity in Ionic 1). Likewise, there
are many paths that lead to a single URL, which was not really possible in v1.

Using the Minecraft example from above, the URL could be `/app/id479516143`, though
what the user sees in the entire UI for the back button, active tab, etc. could vary wildly
depending on how the user navigated.

The point is, that URL provides a way for us to come back to that page in the future (for example,
through a remote app launch), but does not force us to rebuild an entire history stack to get there.

Here's an example of routing in Ionic 2, though please note there is some boilerplate
we will be simplifying in the near future:

```javascript
@Component({
  selector: 'ion-view',
  lifecycle: [onInit]
})
@Page({
  template: ...
  directives: [NavbarTemplate, Navbar, NavPush, Content]
})
export class ContactDetail {
  constructor(nav: NavController) {
    Router.setNavController(nav);

    this.nav = nav;
  }

  viewLoaded() {
    this.router = FirstPage.router.invoke(this);
  }
}

new Routable(FirstPage, {
  url: '/first-page'
})
```

The `Routable` mixin (which will soon be part of a convenient decorator) tells the routing system
that the `ContactDetail` view should be mapped to the `/first-page` URL. If we launched the app
with this URL, the `FirstPage` would get pushed onto the stack.

Whenever `FirstPage` is navigated to (more specifically, when its `viewWillEnter` lifecycle method triggers),
the address bar is updated to be `/first-page`.


text:
require 'sinatra'
require './family_time'
require 'date'
class MySinatraApp < Sinatra::Base
  get '/' do
    ft = FamilyTime.new
    @times = {}
    FamilyTime::MemberLatitudes.each do |k,v|
      @times[k] = ft.showtime(v)
    end
    erb :index
  end
end


text:
package io.crate.metadata.information;

import com.google.common.collect.ImmutableList;
import io.crate.metadata.ColumnIdent;
import io.crate.metadata.ReferenceIdent;
import io.crate.metadata.ReferenceInfo;
import io.crate.metadata.TableIdent;
import io.crate.planner.RowGranularity;
import io.crate.types.DataType;
import io.crate.types.DataTypes;

import java.util.LinkedHashMap;

public class InformationRoutinesTableInfo extends InformationTableInfo {

    public static final String NAME = "routines";
    public static final TableIdent IDENT = new TableIdent(InformationSchemaInfo.NAME, NAME);

    public static class Columns {
        public static final ColumnIdent ROUTINE_NAME = new ColumnIdent("routine_name");
        public static final ColumnIdent ROUTINE_TYPE = new ColumnIdent("routine_type");
    }

    public static class ReferenceInfos {
        public static final ReferenceInfo ROUTINE_NAME = info(Columns.ROUTINE_NAME, DataTypes.STRING);
        public static final ReferenceInfo ROUTINE_TYPE = info(Columns.ROUTINE_TYPE, DataTypes.STRING);
    }

    private static ReferenceInfo info(ColumnIdent columnIdent, DataType dataType) {
        return new ReferenceInfo(new ReferenceIdent(IDENT, columnIdent), RowGranularity.DOC, dataType);
    }

    protected InformationRoutinesTableInfo(InformationSchemaInfo schemaInfo) {
        super(schemaInfo,
                IDENT,
                ImmutableList.<ColumnIdent>of(),
                new LinkedHashMap<ColumnIdent, ReferenceInfo>() {{
                    put(Columns.ROUTINE_NAME, ReferenceInfos.ROUTINE_NAME);
                    put(Columns.ROUTINE_TYPE, ReferenceInfos.ROUTINE_TYPE);
                }}
        );
    }
}


text:
class ReturnCondition < ApplicationRecord
  has_many :return_items

  GOOD      = 'Good'
  DEFECTIVE = 'Defective'
  DAMAGED   = 'Worn / Damaged'

  CONDITIONS = [GOOD, DEFECTIVE, DAMAGED]

  validates :label,      presence: true, :length => { :maximum => 255 }

  # method to get all the return conditions for a RMA form
  # [['Good', 1], ['Defective', 2] ... ]
  #
  # @param [none]
  # @return [ Array[Array] ]
  def self.select_form
    all.collect {|r| [r.label, r.id]}
  end

end


text: Syntax highlighting for Dynare in Sublime Text


text:
CSS property: -webkit-column-break-inside

Description

Determines whether a column break should be avoided within the bounds of an element in a multicolumn flow layout.

Syntax

-webkit-column-break-inside: <policy>;

Values

<policy>

The column break policy.

auto (by default)
A right column break is inserted within the element where appropriate.

avoid
Column breaks are avoided within the element.

Versions

Safari 3.0

iOS 2.0


text:
require "#{File.dirname(__FILE__)}/../utils"
require 'capistrano/cli/help'

class CLIHelpTest < Test::Unit::TestCase
  class MockCLI
    attr_reader :options, :called_original

    def initialize
      @options = {}
      @called_original = false
    end

    def execute_requested_actions(config)
      @called_original = config
    end

    include Capistrano::CLI::Help
  end

  def setup
    @cli = MockCLI.new
    @cli.options[:verbose] = 0
    @ui = stub("ui", :output_cols => 80, :output_rows => 20, :page_at= => nil)
    MockCLI.stubs(:ui).returns(@ui)
  end

  def test_execute_requested_actions_without_tasks_or_explain_should_call_original
    @cli.execute_requested_actions(:config)
    @cli.expects(:task_list).never
    @cli.expects(:explain_task).never
    assert_equal :config, @cli.called_original
  end

  def test_execute_requested_actions_with_tasks_should_call_task_list
    @cli.options[:tasks] = true
    @cli.expects(:task_list).with(:config)
    @cli.expects(:explain_task).never
    @cli.execute_requested_actions(:config)
    assert !@cli.called_original
  end

  def test_execute_requested_actions_with_explain_should_call_explain_task
    @cli.options[:explain] = "deploy_with_niftiness"
    @cli.expects(:task_list).never
    @cli.expects(:explain_task).with(:config, "deploy_with_niftiness")
    @cli.execute_requested_actions(:config)
    assert !@cli.called_original
  end

  def test_task_list_with_no_tasks_should_emit_warning
    config = mock("config", :task_list => [])
    @cli.expects(:warn)
    @cli.task_list(config)
  end

  def test_task_list_should_query_all_tasks_in_all_namespaces
    expected_max_len = 80 - 3 - MockCLI::LINE_PADDING
    task_list = [task("c"), task("g", "c:g"), task("b", "c:b"), task("a")]
    task_list.each { |t| t.expects(:brief_description).with(expected_max_len).returns(t.fully_qualified_name) }

    config = mock("config")
    config.expects(:task_list).with(:all).returns(task_list)
    @cli.stubs(:puts)
    @cli.task_list(config)
  end

  def test_task_list_should_never_use_less_than_MIN_MAX_LEN_chars_for_descriptions
    @ui.stubs(:output_cols).returns(20)
    t = task("c")
    t.expects(:brief_description).with(30).returns("hello")
    config = mock("config", :task_list => [t])
    @cli.stubs(:puts)
    @cli.task_list(config)
  end

  def test_task_list_should_not_include_tasks_with_blank_description_or_internal_by_default
    t1 = task("c")
    t1.expects(:brief_description).returns("hello")
    t2 = task("d", "d", "[internal] howdy")
    t2.expects(:brief_description).never
    t3 = task("e", "e", "")
    t3.expects(:brief_description).never

    config = mock("config", :task_list => [t1, t2, t3])
    @cli.stubs(:puts)
    @cli.expects(:puts).never.with { |s,| (s || "").include?("[internal]") || s =~ /#\s*$/ }
    @cli.task_list(config)
  end

  def test_task_list_should_include_tasks_with_blank_descriptions_and_internal_when_verbose
    t1 = task("c")
    t1.expects(:brief_description).returns("hello")
    t2 = task("d", "d", "[internal] howdy")
    t2.expects(:brief_description).returns("[internal] howdy")
    t3 = task("e", "e", "")
    t3.expects(:brief_description).returns("")

    config = mock("config", :task_list => [t1, t2, t3])
    @cli.options[:verbose] = 1
    @cli.stubs(:puts)
    @cli.expects(:puts).with { |s,| (s || "").include?("[internal]") || s =~ /#\s*$/ }.at_least_once
    @cli.task_list(config)
  end

  def test_explain_task_should_warn_if_task_does_not_exist
    config = mock("config", :find_task => nil)
    @cli.expects(:warn).with { |s,| s =~ /`deploy_with_niftiness'/ }
    @cli.explain_task(config, "deploy_with_niftiness")
  end

  def test_explain_task_with_task_that_has_no_description_should_emit_stub
    t = mock("task", :description => "")
    config = mock("config")
    config.expects(:find_task).with("deploy_with_niftiness").returns(t)
    @cli.stubs(:puts)
    @cli.expects(:puts).with("There is no description for this task.")
    @cli.explain_task(config, "deploy_with_niftiness")
  end

  def test_explain_task_with_task_should_format_description
    t = stub("task", :description => "line1\nline2\n\nline3")
    config = mock("config", :find_task => t)
    @cli.stubs(:puts)
    @cli.explain_task(config, "deploy_with_niftiness")
  end

  def test_long_help_should_load_and_format_help_txt_file
    File.expects(:dirname).returns "a/b/c"
    File.expects(:read).with("a/b/c/help.txt").returns("text")
    @ui.expects(:say).with("text\n")
    @cli.long_help
  end

  private

    def task(name, fqn=name, desc="a description")
      stub("task", :name => name, :fully_qualified_name => fqn, :description => desc)
    end
end


text:
package org.jrimum.bopepo.campolivre;

import org.jrimum.bopepo.BancosSuportados;
import org.jrimum.domkee.financeiro.banco.febraban.Agencia;
import org.jrimum.domkee.financeiro.banco.febraban.Carteira;
import org.jrimum.domkee.financeiro.banco.febraban.NumeroDaConta;
import org.junit.Before;
import org.junit.Test;

/**
 *

 * Teste unitário do campo livre do Banco Bancoob para cobrança não registrada.
 *

 *
 * @author Gilmar P.S.L
 * @author Rômulo Augusto
 *
 * @since 0.2
 *
 * @version 0.2
 */
public class TestCLBancoobCobrancaNaoRegistrada extends AbstractCampoLivreBaseTest {

	private final int NOSSO_NUMERO_LENGTH = 7;

	@Before
	public void setUp(){

		titulo.getContaBancaria().setBanco(BancosSuportados.BANCOOB.create());
		titulo.getContaBancaria().setAgencia(new Agencia(4340));
		titulo.getContaBancaria().setNumeroDaConta(new NumeroDaConta(1, "0"));
		titulo.getContaBancaria().setCarteira(new Carteira(1));
		titulo.setNossoNumero("0200000");
		titulo.setDigitoDoNossoNumero("1");

		createCampoLivreToTest();

		setCampoLivreEsperadoComoString("1434001000001002000001001");
	}

	@Test(expected = CampoLivreException.class)
	public void seNaoPermiteNossoNumeroComTamanhoDiferenteDe7() {
		testeSeNaoPermiteNossoNumeroComTamanhoDiferenteDoEspecificado(NOSSO_NUMERO_LENGTH + 1);
	}

	@Test(expected = CampoLivreException.class)
	public void seNaoPermiteDigitoDaContaNulo() {
		testeSeNaoPermiteDigitoDaContaNulo();
	}

	@Test(expected = CampoLivreException.class)
	public void seNaoPermiteDigitoDaContaNaoNumero() {
		testeSeNaoPermiteDigitoDaContaNaoNumerico();
	}

	@Test(expected = CampoLivreException.class)
	public void seNaoPermiteDigitoDaContaNegativo() {
		testeSeNaoPermiteDigitoDaContaNegativo();
	}

	@Test(expected = CampoLivreException.class)
	public void seNaoPermiteDigitoDaContaVazio() {
		testeSeNaoPermiteDigitoDaContaVazio();
	}

	@Test(expected = CampoLivreException.class)
	public void seNaoPermiteNumeroDaContaMaiorQueSeisDigitos() {
		testeSeNaoPermiteNumeroDaContaComCodigoAcimaDoLimite(1000000);
	}
}


text:
<!DOCTYPE html>

    <title>Should send wildcard ID on load</title>

    <link rel="stylesheet" href="../lib/qunit.css"/>


text:
<?php

/* do NOT run this script through a web browser */
if (!isset($_SERVER["argv"][0]) || isset($_SERVER['REQUEST_METHOD'])  || isset($_SERVER['REMOTE_ADDR'])) {
	die("
This script is only meant to run at the command line.");
}

$no_http_headers = true;

include(dirname(__FILE__) . "/../include/global.php");
include_once($config["base_path"] . "/lib/utility.php");

/* process calling arguments */
$parms = $_SERVER["argv"];
array_shift($parms);

$debug = FALSE;
$host_id = 0;

foreach($parms as $parameter) {
	@list($arg, $value) = @explode("=", $parameter);

	switch ($arg) {
	case "-d":
	case "--debug":
		$debug = TRUE;
		break;
	case "--host-id":
		$host_id = trim($value);

		if (!is_numeric($host_id)) {
			echo "ERROR: You must supply a valid host-id to run this script!\n";
			exit(1);
		}

		break;
	case "-h":
	case "-v":
	case "--version":
	case "--help":
		display_help();

		exit;
	default:
		print "ERROR: Invalid Parameter " . $parameter . "\n\n";
		display_help();

		exit;
	}
}

/* obtain timeout settings */
$max_execution = ini_get("max_execution_time");

/* set new timeout */
ini_set("max_execution_time", "0");

/* get the data_local Id's for the poller cache */
if ($host_id > 0) {
	$poller_data  = db_fetch_assoc("SELECT id FROM data_local WHERE host_id=$host_id");
} else {
	$poller_data  = db_fetch_assoc("SELECT id FROM data_local");
}

/* initialize some variables */
$current_ds = 1;
$total_ds = sizeof($poller_data);

/* setting local_data_ids to an empty array saves time during updates */
$local_data_ids = array();
$poller_items   = array();

/* issue warnings and start message if applicable */
print "WARNING: Do not interrupt this script.  Rebuilding the Poller Cache can take quite some time\n";
debug("There are '" . sizeof($poller_data) . "' data source elements to update.");

/* start rebuilding the poller cache */
if (sizeof($poller_data) > 0) {
	foreach ($poller_data as $data) {
		if (!$debug) print ".";
		$local_data_ids[] = $data["id"];
		$poller_items = array_merge($poller_items, update_poller_cache($data["id"]));

		debug("Data Source Item '$current_ds' of '$total_ds' updated");
		$current_ds++;
	}

	if (sizeof($local_data_ids)) {
		poller_update_poller_cache_from_buffer($local_data_ids, $poller_items);
	}
}
if (!$debug) print "\n";

/* poller cache rebuilt, restore runtime parameters */
ini_set("max_execution_time", $max_execution);

/*	display_help - displays the usage of the function */
function display_help () {
	print "Cacti Rebuild Poller Cache Script 1.0, Copyright 2004-2013 - The Cacti Group\n\n";
	print "usage: rebuild_poller_cache.php [--host-id=ID] [-d | --debug] [-h | --help | -v | --version]\n\n";
	print "-d | --debug  - Display verbose output during execution\n";
	print "-v --version  - Display this help message\n";
	print "-h --help     - Display this help message\n";
}

function debug($message) {
	global $debug;

	if ($debug) {
		print("DEBUG: " . $message . "\n");
	}
}

?>


text:
package org.apache.druid.tests.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Inject;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.java.util.common.logger.Logger;
import org.apache.druid.java.util.http.client.CredentialedHttpClient;
import org.apache.druid.java.util.http.client.HttpClient;
import org.apache.druid.java.util.http.client.auth.BasicCredentials;
import org.apache.druid.security.basic.authorization.entity.BasicAuthorizerGroupMapping;
import org.apache.druid.server.security.ResourceAction;
import org.apache.druid.testing.IntegrationTestingConfig;
import org.apache.druid.testing.guice.DruidTestModuleFactory;
import org.apache.druid.testing.utils.HttpUtil;
import org.apache.druid.testing.utils.ITRetryUtil;
import org.apache.druid.tests.TestNGGroup;
import org.jboss.netty.handler.codec.http.HttpMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;

@Test(groups = TestNGGroup.LDAP_SECURITY)
@Guice(moduleFactory = DruidTestModuleFactory.class)
public class ITBasicAuthLdapConfigurationTest extends AbstractAuthConfigurationTest
{
  private static final Logger LOG = new Logger(ITBasicAuthLdapConfigurationTest.class);

  private static final String LDAP_AUTHENTICATOR = "ldap";
  private static final String LDAP_AUTHORIZER = "ldapauth";

  private static final String EXPECTED_AVATICA_AUTH_ERROR = "Error while executing SQL \"SELECT * FROM INFORMATION_SCHEMA.COLUMNS\": Remote driver error: QueryInterruptedException: User LDAP authentication failed. -> BasicSecurityAuthenticationException: User LDAP authentication failed.";

  @Inject
  IntegrationTestingConfig config;

  @Inject
  ObjectMapper jsonMapper;

  private HttpClient druidUserClient;
  private HttpClient stateOnlyNoLdapGroupUserClient;

  @BeforeClass
  public void before() throws Exception
  {
    // ensure that auth_test segments are loaded completely, we use them for testing system schema tables
    ITRetryUtil.retryUntilTrue(
        () -> coordinatorClient.areSegmentsLoaded("auth_test"), "auth_test segment load"
    );

    setupHttpClientsAndUsers();
    setExpectedSystemSchemaObjects();
  }

  @Test
  public void test_systemSchemaAccess_stateOnlyNoLdapGroupUser() throws Exception
  {
    HttpUtil.makeRequest(stateOnlyUserClient, HttpMethod.GET, config.getBrokerUrl() + "/status", null);

    // as user that can only read STATE
    LOG.info("Checking sys.segments query as stateOnlyNoLdapGroupUser...");
    verifySystemSchemaQuery(
        stateOnlyNoLdapGroupUserClient,
        SYS_SCHEMA_SEGMENTS_QUERY,
        Collections.emptyList()
    );

    LOG.info("Checking sys.servers query as stateOnlyNoLdapGroupUser...");
    verifySystemSchemaServerQuery(
        stateOnlyNoLdapGroupUserClient,
        SYS_SCHEMA_SERVERS_QUERY,
        adminServers
    );

    LOG.info("Checking sys.server_segments query as stateOnlyNoLdapGroupUser...");
    verifySystemSchemaQuery(
        stateOnlyNoLdapGroupUserClient,
        SYS_SCHEMA_SERVER_SEGMENTS_QUERY,
        Collections.emptyList()
    );

    LOG.info("Checking sys.tasks query as stateOnlyNoLdapGroupUser...");
    verifySystemSchemaQuery(
        stateOnlyNoLdapGroupUserClient,
        SYS_SCHEMA_TASKS_QUERY,
        Collections.emptyList()
    );
  }

  @Test
  public void test_druidUser_hasNodeAccess()
  {
    checkNodeAccess(druidUserClient);
  }

  @Override
  protected void setupDatasourceOnlyUser() throws Exception
  {
    createRoleWithPermissionsAndGroupMapping(
        "datasourceOnlyGroup",
        ImmutableMap.of("datasourceOnlyRole", DATASOURCE_ONLY_PERMISSIONS)
    );
  }

  @Override
  protected void setupDatasourceAndSysTableUser() throws Exception
  {
    createRoleWithPermissionsAndGroupMapping(
        "datasourceWithSysGroup",
        ImmutableMap.of("datasourceWithSysRole", DATASOURCE_SYS_PERMISSIONS)
    );
  }

  @Override
  protected void setupDatasourceAndSysAndStateUser() throws Exception
  {
    createRoleWithPermissionsAndGroupMapping(
        "datasourceWithStateGroup",
        ImmutableMap.of("datasourceWithStateRole", DATASOURCE_SYS_STATE_PERMISSIONS)
    );
  }

  @Override
  protected void setupSysTableAndStateOnlyUser() throws Exception
  {
    createRoleWithPermissionsAndGroupMapping(
        "stateOnlyGroup",
        ImmutableMap.of("stateOnlyRole", STATE_ONLY_PERMISSIONS)
    );

    // create a role that can read /status
    createRoleWithPermissionsAndGroupMapping(
        "druidGroup",
        ImmutableMap.of("druidrole", STATE_ONLY_PERMISSIONS)
    );

    assignUserToRole("stateOnlyNoLdapGroup", "stateOnlyRole");
  }

  @Override
  protected void setupTestSpecificHttpClients()
  {
    druidUserClient = new CredentialedHttpClient(
        new BasicCredentials("druid", "helloworld"),
        httpClient
    );

    stateOnlyNoLdapGroupUserClient = new CredentialedHttpClient(
        new BasicCredentials("stateOnlyNoLdapGroup", "helloworld"),
        httpClient
    );
  }

  @Override
  protected String getAuthenticatorName()
  {
    return LDAP_AUTHENTICATOR;
  }

  @Override
  protected String getAuthorizerName()
  {
    return LDAP_AUTHORIZER;
  }

  @Override
  protected String getExpectedAvaticaAuthError()
  {
    return EXPECTED_AVATICA_AUTH_ERROR;
  }

  @Override
  protected Properties getAvaticaConnectionProperties()
  {
    Properties connectionProperties = new Properties();
    connectionProperties.setProperty("user", "admin");
    connectionProperties.setProperty("password", "priest");
    return connectionProperties;
  }

  @Override
  protected Properties getAvaticaConnectionPropertiesFailure()
  {
    Properties connectionProperties = new Properties();
    connectionProperties.setProperty("user", "admin");
    connectionProperties.setProperty("password", "wrongpassword");
    return connectionProperties;
  }

  private void createRoleWithPermissionsAndGroupMapping(
      String group,
      Map<String, List<ResourceAction>> roleTopermissions
  ) throws Exception
  {
    roleTopermissions.keySet().forEach(role -> HttpUtil.makeRequest(
        adminClient,
        HttpMethod.POST,
        StringUtils.format(
            "%s/druid-ext/basic-security/authorization/db/ldapauth/roles/%s",
            config.getCoordinatorUrl(),
            role
        ),
        null
    ));

    for (Map.Entry<String, List<ResourceAction>> entry : roleTopermissions.entrySet()) {
      String role = entry.getKey();
      List<ResourceAction> permissions = entry.getValue();
      byte[] permissionsBytes = jsonMapper.writeValueAsBytes(permissions);
      HttpUtil.makeRequest(
          adminClient,
          HttpMethod.POST,
          StringUtils.format(
              "%s/druid-ext/basic-security/authorization/db/ldapauth/roles/%s/permissions",
              config.getCoordinatorUrl(),
              role
          ),
          permissionsBytes
      );
    }

    String groupMappingName = StringUtils.format("%sMapping", group);
    BasicAuthorizerGroupMapping groupMapping = new BasicAuthorizerGroupMapping(
        groupMappingName,
        StringUtils.format("cn=%s,ou=Groups,dc=example,dc=org", group),
        roleTopermissions.keySet()
    );
    byte[] groupMappingBytes = jsonMapper.writeValueAsBytes(groupMapping);
    HttpUtil.makeRequest(
        adminClient,
        HttpMethod.POST,
        StringUtils.format(
            "%s/druid-ext/basic-security/authorization/db/ldapauth/groupMappings/%s",
            config.getCoordinatorUrl(),
            groupMappingName
        ),
        groupMappingBytes
    );
  }

  private void assignUserToRole(
      String user,
      String role
  )
  {
    HttpUtil.makeRequest(
        adminClient,
        HttpMethod.POST,
        StringUtils.format(
            "%s/druid-ext/basic-security/authorization/db/ldapauth/users/%s",
            config.getCoordinatorUrl(),
            user
        ),
        null
    );

    HttpUtil.makeRequest(
        adminClient,
        HttpMethod.POST,
        StringUtils.format(
            "%s/druid-ext/basic-security/authorization/db/ldapauth/users/%s/roles/%s",
            config.getCoordinatorUrl(),
            user,
            role
        ),
        null
    );
  }
}


text:
package com.ihtsdo.snomed.service.serialiser;

import static org.junit.Assert.assertEquals;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;

import org.junit.Before;
import org.junit.Test;

import com.ihtsdo.snomed.model.Concept;
import com.ihtsdo.snomed.model.Statement;
import com.ihtsdo.snomed.service.serialiser.SnomedSerialiserFactory.Form;

public class ChildParentSerialiserTest {

    private static final String EXPECTED_RESULT =
                    "1\t2\r\n" +
                    "1\t3\r\n" +
                    "1\t4\r\n" +
                    "2\t3\r\n" +
                    "2\t4\r\n" +
                    "3\t4\r\n";

    private Collection<Statement> statements = new HashSet<Statement>();

    @Before
    public void setUp() throws Exception {
        Concept c1 = new Concept(1);
        Concept c2 = new Concept(2);
        Concept c3 = new Concept(3);
        Concept c4 = new Concept(4);
        Concept cp = new Concept(Concept.IS_KIND_OF_RELATIONSHIP_TYPE_ID);

        statements.addAll(Arrays.asList(
                new Statement(0, c1, cp, c2),
                new Statement(1, c2, cp, c3),
                new Statement(2, c3, cp, c4),
                new Statement(3, c1, cp, c3),
                new Statement(4, c1, cp, c4),
                new Statement(6, c2, cp, c4)
                ));
    }

    @Test
    public void shouldPrintOntologyInSpecifiedFormat() throws IOException, ParseException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (PrintWriter pw = new PrintWriter(new OutputStreamWriter(baos, "utf-8"))){
            SnomedSerialiserFactory.getSerialiser(Form.CHILD_PARENT, pw).write(statements);
        }
        baos.flush();
        assertEquals(EXPECTED_RESULT, baos.toString());
    }
}


text:
<?php

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Conditional;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;

require __DIR__ . '/../Header.php';

// Create new Spreadsheet object
$helper->log('Create new Spreadsheet object');
$spreadsheet = new Spreadsheet();

// Set document properties
$helper->log('Set document properties');
$spreadsheet->getProperties()->setCreator('Maarten Balliauw')
        ->setLastModifiedBy('Maarten Balliauw')
        ->setTitle('Office 2007 XLSX Test Document')
        ->setSubject('Office 2007 XLSX Test Document')
        ->setDescription('Test document for Office 2007 XLSX, generated using PHP classes.')
        ->setKeywords('office 2007 openxml php')
        ->setCategory('Test result file');

// Create a first sheet, representing sales data
$helper->log('Add some data');
$spreadsheet->setActiveSheetIndex(0);
$spreadsheet->getActiveSheet()->setCellValue('A1', 'Description')
        ->setCellValue('B1', 'Amount');

$spreadsheet->getActiveSheet()->setCellValue('A2', 'Paycheck received')
        ->setCellValue('B2', 100);

$spreadsheet->getActiveSheet()->setCellValue('A3', 'Cup of coffee bought')
        ->setCellValue('B3', -1.5);

$spreadsheet->getActiveSheet()->setCellValue('A4', 'Cup of coffee bought')
        ->setCellValue('B4', -1.5);

$spreadsheet->getActiveSheet()->setCellValue('A5', 'Cup of tea bought')
        ->setCellValue('B5', -1.2);

$spreadsheet->getActiveSheet()->setCellValue('A6', 'Found some money')
        ->setCellValue('B6', 8);

$spreadsheet->getActiveSheet()->setCellValue('A7', 'Total:')
        ->setCellValue('B7', '=SUM(B2:B6)');

// Set column widths
$helper->log('Set column widths');
$spreadsheet->getActiveSheet()->getColumnDimension('A')->setWidth(30);
$spreadsheet->getActiveSheet()->getColumnDimension('B')->setWidth(12);

// Add conditional formatting
$helper->log('Add conditional formatting');
$conditional1 = new Conditional();
$conditional1->setConditionType(Conditional::CONDITION_CELLIS)
        ->setOperatorType(Conditional::OPERATOR_BETWEEN)
        ->addCondition('200')
        ->addCondition('400');
$conditional1->getStyle()->getFont()->getColor()->setARGB(Color::COLOR_YELLOW);
$conditional1->getStyle()->getFont()->setBold(true);
$conditional1->getStyle()->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE);

$conditional2 = new Conditional();
$conditional2->setConditionType(Conditional::CONDITION_CELLIS)
        ->setOperatorType(Conditional::OPERATOR_LESSTHAN)
        ->addCondition('0');
$conditional2->getStyle()->getFont()->getColor()->setARGB(Color::COLOR_RED);
$conditional2->getStyle()->getFont()->setItalic(true);
$conditional2->getStyle()->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE);

$conditional3 = new Conditional();
$conditional3->setConditionType(Conditional::CONDITION_CELLIS)
        ->setOperatorType(Conditional::OPERATOR_GREATERTHANOREQUAL)
        ->addCondition('0');
$conditional3->getStyle()->getFont()->getColor()->setARGB(Color::COLOR_GREEN);
$conditional3->getStyle()->getFont()->setItalic(true);
$conditional3->getStyle()->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE);

$conditionalStyles = $spreadsheet->getActiveSheet()->getStyle('B2')->getConditionalStyles();
$conditionalStyles[] = $conditional1;
$conditionalStyles[] = $conditional2;
$conditionalStyles[] = $conditional3;
$spreadsheet->getActiveSheet()->getStyle('B2')->setConditionalStyles($conditionalStyles);

//	duplicate the conditional styles across a range of cells
$helper->log('Duplicate the conditional formatting across a range of cells');
$spreadsheet->getActiveSheet()->duplicateConditionalStyle(
    $spreadsheet->getActiveSheet()->getStyle('B2')->getConditionalStyles(),
    'B3:B7'
);

// Set fonts
$helper->log('Set fonts');
$spreadsheet->getActiveSheet()->getStyle('A1:B1')->getFont()->setBold(true);
//$spreadsheet->getActiveSheet()->getStyle('B1')->getFont()->setBold(true);
$spreadsheet->getActiveSheet()->getStyle('A7:B7')->getFont()->setBold(true);
//$spreadsheet->getActiveSheet()->getStyle('B7')->getFont()->setBold(true);
// Set header and footer. When no different headers for odd/even are used, odd header is assumed.
$helper->log('Set header/footer');
$spreadsheet->getActiveSheet()->getHeaderFooter()->setOddHeader('&L&BPersonal cash register&RPrinted on &D');
$spreadsheet->getActiveSheet()->getHeaderFooter()->setOddFooter('&L&B' . $spreadsheet->getProperties()->getTitle() . '&RPage &P of &N');

// Set page orientation and size
$helper->log('Set page orientation and size');
$spreadsheet->getActiveSheet()->getPageSetup()->setOrientation(PageSetup::ORIENTATION_PORTRAIT);
$spreadsheet->getActiveSheet()->getPageSetup()->setPaperSize(PageSetup::PAPERSIZE_A4);

// Rename worksheet
$helper->log('Rename worksheet');
$spreadsheet->getActiveSheet()->setTitle('Invoice');

// Save
$helper->write($spreadsheet, __FILE__);


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE253_Incorrect_Check_of_Function_Return_Value__char_remove_11.c
Label Definition File: CWE253_Incorrect_Check_of_Function_Return_Value.label.xml
Template File: point-flaw-11.tmpl.c
*/
/*
 * @description
 * CWE: 253 Incorrect Check of Return Value
 * Sinks: remove
 *    GoodSink: Correctly check if remove() failed
 *    BadSink : Incorrectly check if remove() failed
 * Flow Variant: 11 Control flow: if(globalReturnsTrue()) and if(globalReturnsFalse())
 *
 * */

#include "std_testcase.h"

#ifndef _WIN32
#include <wchar.h>
#endif

#ifdef _WIN32
#define REMOVE remove
#else
#define REMOVE remove
#endif

#ifndef OMITBAD

void CWE253_Incorrect_Check_of_Function_Return_Value__char_remove_11_bad()
{
    if(globalReturnsTrue())
    {
        /* FLAW: remove() might fail, in which case the return value will be non-zero, but
         * we are checking to see if the return value is 0 */
        if (REMOVE("removemebad.txt") == 0)
        {
            printLine("remove failed!");
        }
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* good1() uses if(globalReturnsFalse()) instead of if(globalReturnsTrue()) */
static void good1()
{
    if(globalReturnsFalse())
    {
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
    }
    else
    {
        /* FIX: check for the correct return value */
        if (REMOVE("removemegood.txt") != 0)
        {
            printLine("remove failed!");
        }
    }
}

/* good2() reverses the bodies in the if statement */
static void good2()
{
    if(globalReturnsTrue())
    {
        /* FIX: check for the correct return value */
        if (REMOVE("removemegood.txt") != 0)
        {
            printLine("remove failed!");
        }
    }
}

void CWE253_Incorrect_Check_of_Function_Return_Value__char_remove_11_good()
{
    good1();
    good2();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE253_Incorrect_Check_of_Function_Return_Value__char_remove_11_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE253_Incorrect_Check_of_Function_Return_Value__char_remove_11_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif