text:
package org.apache.cassandra.io.sstable.format.big;

import java.io.ByteArrayInputStream;
import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.Set;
import java.util.function.Function;

import com.google.common.collect.ImmutableSet;
import org.apache.cassandra.io.util.File;
import org.junit.BeforeClass;
import org.junit.Test;

import io.netty.buffer.Unpooled;
import io.netty.channel.embedded.EmbeddedChannel;
import org.apache.cassandra.SchemaLoader;
import org.apache.cassandra.Util;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.db.DecoratedKey;
import org.apache.cassandra.db.Keyspace;
import org.apache.cassandra.db.RowUpdateBuilder;
import org.apache.cassandra.db.Slices;
import org.apache.cassandra.db.compaction.OperationType;
import org.apache.cassandra.db.filter.ColumnFilter;
import org.apache.cassandra.db.lifecycle.LifecycleTransaction;
import org.apache.cassandra.db.rows.UnfilteredRowIterator;
import org.apache.cassandra.io.sstable.Component;
import org.apache.cassandra.io.sstable.Descriptor;
import org.apache.cassandra.io.sstable.format.SSTableReader;
import org.apache.cassandra.io.sstable.format.SSTableReadsListener;
import org.apache.cassandra.io.util.DataInputPlus;
import org.apache.cassandra.io.util.FileHandle;
import org.apache.cassandra.net.AsyncStreamingInputPlus;
import org.apache.cassandra.schema.CachingParams;
import org.apache.cassandra.schema.KeyspaceParams;
import org.apache.cassandra.schema.Schema;
import org.apache.cassandra.schema.TableMetadataRef;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.Pair;

import static org.apache.cassandra.io.util.DataInputPlus.DataInputStreamPlus;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;

public class BigTableZeroCopyWriterTest
{
    public static final String KEYSPACE1 = "BigTableBlockWriterTest";
    public static final String CF_STANDARD = "Standard1";
    public static final String CF_STANDARD2 = "Standard2";
    public static final String CF_INDEXED = "Indexed1";
    public static final String CF_STANDARDLOWINDEXINTERVAL = "StandardLowIndexInterval";

    public static SSTableReader sstable;
    public static ColumnFamilyStore store;
    private static int expectedRowCount;

    @BeforeClass
    public static void defineSchema() throws Exception
    {
        SchemaLoader.prepareServer();
        SchemaLoader.createKeyspace(KEYSPACE1,
                                    KeyspaceParams.simple(1),
                                    SchemaLoader.standardCFMD(KEYSPACE1, CF_STANDARD),
                                    SchemaLoader.standardCFMD(KEYSPACE1, CF_STANDARD2),
                                    SchemaLoader.compositeIndexCFMD(KEYSPACE1, CF_INDEXED, true),
                                    SchemaLoader.standardCFMD(KEYSPACE1, CF_STANDARDLOWINDEXINTERVAL)
                                                .minIndexInterval(8)
                                                .maxIndexInterval(256)
                                                .caching(CachingParams.CACHE_NOTHING));

        String ks = KEYSPACE1;
        String cf = "Standard1";

        // clear and create just one sstable for this test
        Keyspace keyspace = Keyspace.open(ks);
        store = keyspace.getColumnFamilyStore(cf);
        store.clearUnsafe();
        store.disableAutoCompaction();

        DecoratedKey firstKey = null, lastKey = null;
        long timestamp = System.currentTimeMillis();
        for (int i = 0; i < store.metadata().params.minIndexInterval; i++)
        {
            DecoratedKey key = Util.dk(String.valueOf(i));
            if (firstKey == null)
                firstKey = key;
            if (lastKey == null)
                lastKey = key;
            if (store.metadata().partitionKeyType.compare(lastKey.getKey(), key.getKey()) < 0)
                lastKey = key;

            new RowUpdateBuilder(store.metadata(), timestamp, key.getKey())
            .clustering("col")
            .add("val", ByteBufferUtil.EMPTY_BYTE_BUFFER)
            .build()
            .applyUnsafe();
            expectedRowCount++;
        }
        store.forceBlockingFlush();

        sstable = store.getLiveSSTables().iterator().next();
    }

    @Test
    public void writeDataFile_DataInputPlus()
    {
        writeDataTestCycle(buffer -> new DataInputStreamPlus(new ByteArrayInputStream(buffer.array())));
    }

    @Test
    public void writeDataFile_RebufferingByteBufDataInputPlus()
    {
        try (AsyncStreamingInputPlus input = new AsyncStreamingInputPlus(new EmbeddedChannel()))
        {
            writeDataTestCycle(buffer ->
            {
                input.append(Unpooled.wrappedBuffer(buffer));
                return input;
            });

            input.requestClosure();
        }
    }

    private void writeDataTestCycle(Function<ByteBuffer, DataInputPlus> bufferMapper)
    {
        File dir = store.getDirectories().getDirectoryForNewSSTables();
        Descriptor desc = store.newSSTableDescriptor(dir);
        TableMetadataRef metadata = Schema.instance.getTableMetadataRef(desc);

        LifecycleTransaction txn = LifecycleTransaction.offline(OperationType.STREAM);
        Set<Component> componentsToWrite = ImmutableSet.of(Component.DATA, Component.PRIMARY_INDEX,
                                                           Component.STATS);

        BigTableZeroCopyWriter btzcw = new BigTableZeroCopyWriter(desc, metadata, txn, componentsToWrite);

        for (Component component : componentsToWrite)
        {
            if (Files.exists(Paths.get(desc.filenameFor(component))))
            {
                Pair<DataInputPlus, Long> pair = getSSTableComponentData(sstable, component, bufferMapper);

                try
                {
                    btzcw.writeComponent(component.type, pair.left, pair.right);
                }
                catch (ClosedChannelException e)
                {
                    throw new UncheckedIOException(e);
                }
            }
        }

        Collection<SSTableReader> readers = btzcw.finish(true);

        SSTableReader reader = readers.toArray(new SSTableReader[0])[0];

        assertNotEquals(sstable.getFilename(), reader.getFilename());
        assertEquals(sstable.estimatedKeys(), reader.estimatedKeys());
        assertEquals(sstable.isPendingRepair(), reader.isPendingRepair());

        assertRowCount(expectedRowCount);
    }

    private void assertRowCount(int expected)
    {
        int count = 0;
        for (int i = 0; i < store.metadata().params.minIndexInterval; i++)
        {
            DecoratedKey dk = Util.dk(String.valueOf(i));
            UnfilteredRowIterator rowIter = sstable.iterator(dk,
                                                             Slices.ALL,
                                                             ColumnFilter.all(store.metadata()),
                                                             false,
                                                             SSTableReadsListener.NOOP_LISTENER);
            while (rowIter.hasNext())
            {
                rowIter.next();
                count++;
            }
        }
        assertEquals(expected, count);
    }

    private Pair<DataInputPlus, Long> getSSTableComponentData(SSTableReader sstable, Component component,
                                                              Function<ByteBuffer, DataInputPlus> bufferMapper)
    {
        FileHandle componentFile = new FileHandle.Builder(sstable.descriptor.filenameFor(component))
                                   .bufferSize(1024).complete();
        ByteBuffer buffer = ByteBuffer.allocate((int) componentFile.channel.size());
        componentFile.channel.read(buffer, 0);
        buffer.flip();

        DataInputPlus inputPlus = bufferMapper.apply(buffer);

        return Pair.create(inputPlus, componentFile.channel.size());
    }
}


text:
require 'spec_helper'

require 'puppet/util/json_lockfile'

describe Puppet::Util::JsonLockfile do
  require 'puppet_spec/files'
  include PuppetSpec::Files

  before(:each) do
    @lockfile = tmpfile("lock")
    @lock = Puppet::Util::JsonLockfile.new(@lockfile)
  end

  describe "#lock" do
    it "should create a lock file containing a json hash" do
      data = { "foo" => "foofoo", "bar" => "barbar" }
      @lock.lock(data)

      PSON.parse(File.read(@lockfile)).should == data
    end
  end

  describe "reading lock data" do
    it "returns deserialized JSON from the lockfile" do
      data = { "foo" => "foofoo", "bar" => "barbar" }
      @lock.lock(data)
      expect(@lock.lock_data).to eq data
    end

    it "returns nil if the file read returned nil" do
      @lock.lock
      File.stubs(:read).returns nil
      expect(@lock.lock_data).to be_nil
    end

    it "returns nil if the file was empty" do
      @lock.lock
      File.stubs(:read).returns ''
      expect(@lock.lock_data).to be_nil
    end

    it "returns nil if the file was not in PSON" do
      @lock.lock
      File.stubs(:read).returns ']['
      expect(@lock.lock_data).to be_nil
    end

  end
end

redpajama_set_name: RedPajamaGithub


text:
/*
 * Name: AuthenticationEndpoint.js
 * Module: ExternalAPIManager
 * Location: Norris/Main/ExternalAPIManager
 * Date: 2015-05-24
 * Version: v1.00
 *
 * History:
 *
 * ================================================================================
 * Version Date Programmer Changes
 * ================================================================================
 * v1.00 2015-06-15 Carlon Chiara  Approved
 * ================================================================================
 * v0.06 2015-06-02 Pavanello Fabio Matteo   Verify
 * ================================================================================
 * v0.05 2015-05-29 Bucco Riccardo   Edit
 * ================================================================================
 * v0.04 2015-05-24 Carlon Chiara   Verify
 * ================================================================================
 * v0.03 2015-05-21 Pavanello Fabio Matteo   Edit
 * ================================================================================
 * v0.02 2015-04-14 Pavanello Fabio Matteo   Verify
 * ================================================================================
 * v0.01 2015-04-12 Moretto Alessandro   Creation
 * ================================================================================
 */

var ExternalAPIController = require('./ExternalAPIController.js');
var ExternalAPIConstructor = require('./ExternalAPIConstructor.js');

module.exports = AuthenticationEndpoint;

/**
 * Creates an AuthenticationEndpoint.
 * @param {ExternalAPIController} controller
 * @returns {AuthenticationEndpoint}
 * @constructor
 */
function AuthenticationEndpoint(controller) {
    if (!(this instanceof AuthenticationEndpoint)) return new AuthenticationEndpoint(controller);
    if (controller) {
        var authenticationEndpoint = this;
        this.controller = controller;
        this.app = controller.getApp();
        this.app.post(this.controller.getEndpoint() + 'auth/login', function (req, res) {authenticationEndpoint.handleLogin(req, res);});
        this.app.post(this.controller.getEndpoint() + 'auth/logout', function (req, res) {authenticationEndpoint.handleLogout(req, res);});
        this.app.post(this.controller.getEndpoint() + 'auth/keepalive', function (req, res) {authenticationEndpoint.handleKeepAlive(req, res);});
    } else {
        console.error("ERROR: an ExternalAPIController is required.");
        throw("AuthenticationEndpoint:requiredExternalAPIController");
    }
}

/**
 * Manages an authentication request
 * @param {express::request} req
 * @param {express::response} res
 */
AuthenticationEndpoint.prototype.handleLogin = function(req, res) {
    var cookies = {
        getCookies: req.cookies,
        getSignedCookies: req.signedCookies,
        setCookie: function () {
            res.cookie.apply(res, arguments);
        },
        clearCookie: function () {
            res.clearCookie.apply(res, arguments);
        }
    };

    if(!req.body.username || !req.body.password) {
        res.sendStatus(400);
    } else if(!this.controller.performLogin(cookies, req.body.username, req.body.password)) {
        res.sendStatus(401);
    } else
        res.sendStatus(200);
};

/**
 * Manages an end-session request
 * @param {express::request} req
 * @param {express::response} res
 */
AuthenticationEndpoint.prototype.handleLogout = function(req, res) {
    var cookies = {
        getCookies: req.cookies,
        getSignedCookies: req.signedCookies,
        setCookie: function () {
            res.cookie.apply(res, arguments);
        },
        clearCookie: function () {
            res.clearCookie.apply(res, arguments);
        }
    };
    if(!this.controller.performLogout(cookies))
        res.sendStatus(401);
    else
        res.sendStatus(200);
};

/**
 * Manages a request in order to renew an activated session
 * @param {express::request} req
 * @param {express::response} res
 */
AuthenticationEndpoint.prototype.handleKeepAlive = function(req, res) {
    var cookies = {
        getCookies: req.cookies,
        getSignedCookies: req.signedCookies,
        setCookie: function () {
            res.cookie.apply(res, arguments);
        },
        clearCookie: function () {
            res.clearCookie.apply(res, arguments);
        }
    };
    if(!this.controller.performKeepAlive(cookies))
        res.sendStatus(401);
    else
        res.sendStatus(200);
};

/* AuthenticationEndpointFactory ------------------------------------------------------- */

/**
 * Creates a new AuthenticationEndpointFactory.
 * @constructor
 */
function AuthenticationEndpointFactory() {
    if(!(this instanceof AuthenticationEndpointFactory)) {
        return new AuthenticationEndpointFactory();
    }
}

AuthenticationEndpointFactory.prototype.instance=new AuthenticationEndpointFactory(); // static

/**
 * Gets the AuthenticationEndpointFactory's instance.
 * @returns {AuthenticationEndpointFactory} the factory's instance.
 */
AuthenticationEndpointFactory.getInstance = function() { // static
    return AuthenticationEndpointFactory.prototype.instance;
};

/**
 * Creates a new AuthenticationEndpoint.
 * @param {ExternalAPIController} controller - ;
 * @returns {AuthenticationEndpoint} - the created endpoint.
 */
AuthenticationEndpointFactory.prototype.createEndpoint = function (controller) {
    return new AuthenticationEndpoint (controller);
};

// Dependency injection:
ExternalAPIConstructor.registerEndpoint(AuthenticationEndpointFactory.getInstance());


text: export { Americas as default } from "../../";