text:
/*
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.comcast.cdn.traffic_control.traffic_router.core.router;

import com.comcast.cdn.traffic_control.traffic_router.core.cache.CacheLocation;
import com.comcast.cdn.traffic_control.traffic_router.core.cache.CacheRegister;
import com.comcast.cdn.traffic_control.traffic_router.core.ds.DeliveryService;
import com.comcast.cdn.traffic_control.traffic_router.core.loc.FederationRegistry;
import com.comcast.cdn.traffic_control.traffic_router.core.request.DNSRequest;
import com.comcast.cdn.traffic_control.traffic_router.core.request.Request;
import com.comcast.cdn.traffic_control.traffic_router.core.router.StatTracker.Track;
import com.comcast.cdn.traffic_control.traffic_router.core.router.StatTracker.Track.ResultType;
import com.comcast.cdn.traffic_control.traffic_router.core.router.StatTracker.Track.ResultDetails;

import com.comcast.cdn.traffic_control.traffic_router.core.util.CidrAddress;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;
import org.xbill.DNS.Name;
import org.xbill.DNS.Type;

import static org.mockito.Mockito.*;
import static org.powermock.api.mockito.PowerMockito.doCallRealMethod;
import static org.powermock.api.mockito.PowerMockito.spy;
import static org.powermock.reflect.Whitebox.setInternalState;

@RunWith(PowerMockRunner.class)
@PrepareForTest({DeliveryService.class, TrafficRouter.class})
public class DNSRoutingMissesTest {

    private DNSRequest request;
    private TrafficRouter trafficRouter;
    private Track track;

    @Before
    public void before() throws Exception {
        request = new DNSRequest();

        request.setClientIP("192.168.34.56");
        request.setHostname(Name.fromString("edge.foo-img.kabletown.com").relativize(Name.root).toString());
        request.setQtype(Type.A);

        FederationRegistry federationRegistry = mock(FederationRegistry.class);
        when(federationRegistry.findInetRecords(anyString(), any(CidrAddress.class))).thenReturn(null);

        trafficRouter = mock(TrafficRouter.class);
        when(trafficRouter.getCacheRegister()).thenReturn(mock(CacheRegister.class));
        Whitebox.setInternalState(trafficRouter, "federationRegistry", federationRegistry);
        when(trafficRouter.selectCachesByGeo(anyString(), any(DeliveryService.class), any(CacheLocation.class), any(Track.class))).thenCallRealMethod();

        track = spy(StatTracker.getTrack());
        doCallRealMethod().when(trafficRouter).route(request, track);
    }

    @Test
    public void itSetsDetailsWhenNoDeliveryService() throws Exception {
        trafficRouter.route(request, track);

        verify(track).setResult(ResultType.STATIC_ROUTE);
        verify(track).setResultDetails(ResultDetails.DS_NOT_FOUND);
    }

    // When the delivery service is unavailable ...
    @Test
    public void itSetsDetailsWhenNoBypass() throws Exception {
        DeliveryService deliveryService = mock(DeliveryService.class);
        when(deliveryService.isAvailable()).thenReturn(false);
        when(deliveryService.getFailureDnsResponse(request, track)).thenCallRealMethod();
        when(deliveryService.getRoutingName()).thenReturn("edge");

        doReturn(deliveryService).when(trafficRouter).selectDeliveryService(request, false);

        trafficRouter.route(request, track);

        verify(track).setResult(ResultType.MISS);
        verify(track).setResultDetails(ResultDetails.DS_NO_BYPASS);
    }

    @Test
    public void itSetsDetailsWhenBypassDestination() throws Exception {
        DeliveryService deliveryService = mock(DeliveryService.class);
        when(deliveryService.isAvailable()).thenReturn(false);
        when(deliveryService.getFailureDnsResponse(request, track)).thenCallRealMethod();
        when(deliveryService.getRoutingName()).thenReturn("edge");

        doReturn(deliveryService).when(trafficRouter).selectDeliveryService(request, false);

        JSONObject bypassDestination = mock(JSONObject.class);
        when(bypassDestination.optJSONObject("DNS")).thenReturn(null);

        setInternalState(deliveryService, "bypassDestination", bypassDestination);

        trafficRouter.route(request, track);

        verify(track).setResult(ResultType.DS_REDIRECT);
        verify(track).setResultDetails(ResultDetails.DS_BYPASS);
    }

    // The Delivery Service is available but we don't find the cache in the coverage zone map

    // - and DS doesn't support other lookups
    @Test
    public void itSetsDetailsAboutMissesWhenOnlyCoverageZoneSupported() throws Exception {
        DeliveryService deliveryService = mock(DeliveryService.class);
        doReturn(true).when(deliveryService).isAvailable();
        when(deliveryService.getRoutingName()).thenReturn("edge");

        when(deliveryService.isCoverageZoneOnly()).thenReturn(true);

        doReturn(deliveryService).when(trafficRouter).selectDeliveryService(any(Request.class), anyBoolean());
        trafficRouter.route(request, track);

        verify(track).setResult(ResultType.MISS);
        verify(track).setResultDetails(ResultDetails.DS_CZ_ONLY);
    }

    // 1. We got an unsupported cache location from the coverage zone map
    // 2. we looked up the client location from maxmind
    // 3. delivery service says the client location is unsupported
    @Test
    public void itSetsDetailsWhenClientGeolocationNotSupported() throws Exception {
        DeliveryService deliveryService = mock(DeliveryService.class);
        doReturn(true).when(deliveryService).isAvailable();
        when(deliveryService.getRoutingName()).thenReturn("edge");

        when(deliveryService.isCoverageZoneOnly()).thenReturn(false);

        doReturn(deliveryService).when(trafficRouter).selectDeliveryService(request, false);

        trafficRouter.route(request, track);

        verify(track).setResult(ResultType.MISS);
        verify(track).setResultDetails(ResultDetails.DS_CLIENT_GEO_UNSUPPORTED);

    }

    @Test
    public void itSetsDetailsWhenCacheNotFoundByGeolocation() throws Exception {
        doCallRealMethod().when(trafficRouter).selectCachesByGeo(anyString(), any(DeliveryService.class), any(CacheLocation.class), any(Track.class));
        CacheLocation cacheLocation = mock(CacheLocation.class);
        CacheRegister cacheRegister = mock(CacheRegister.class);

        DeliveryService deliveryService = mock(DeliveryService.class);
        doReturn(true).when(deliveryService).isAvailable();
        when(deliveryService.isLocationAvailable(cacheLocation)).thenReturn(false);
        when(deliveryService.isCoverageZoneOnly()).thenReturn(false);
        when(deliveryService.getRoutingName()).thenReturn("edge");

        doReturn(deliveryService).when(trafficRouter).selectDeliveryService(request, false);
        doReturn(cacheLocation).when(trafficRouter).getCoverageZoneCacheLocation("192.168.34.56", deliveryService);
        doReturn(cacheRegister).when(trafficRouter).getCacheRegister();

        trafficRouter.route(request, track);

        verify(track).setResult(ResultType.MISS);
        verify(track).setResultDetails(ResultDetails.DS_CLIENT_GEO_UNSUPPORTED);
    }
}


text:
'use strict';

// The public elements in this file implement the Server Connector Interface,
// part of the contract between the signaling server and the webrtc client.
// No changes that break backward compatibility are allowed here. Any new
// features must be added as a new function/class in the interface. Any
// additions to the interface must be checked for existence by the client before
// using it.

// The id of the device the client is supposed to connect to.
// The List Devices page in the signaling server may choose any way to pass the
// device id to the client page, this function retrieves that information once
// the client loaded.
// In this case the device id is passed as a parameter in the url.
export function deviceId() {
  // The server connector is loaded from the client.html file, which is loaded
  // with a path like "/vX/devices/{deviceId}/files/"
  let pathElements = location.pathname.split('/');
  let devIdx = pathElements.indexOf("devices");
  if (devIdx < 0 || devIdx + 2 >= pathElements.length ||
      pathElements[devIdx + 2] != 'files') {
    // The path doesn't match our expectations
    throw 'server connector is incompatible with this server';
  }
  return pathElements[devIdx + 1];
}

// Creates a connector capable of communicating with the signaling server.
export async function createConnector() {
  return new PollingConnector();
}

// A connector object provides high level functions for communicating with the
// signaling server, while hiding away implementation details.
// This class is an interface and shouldn't be instantiated direclty.
// Only the public methods present in this class form part of the Server
// Connector Interface, any implementations of the interface are considered
// internal and not accessible to client code.
class Connector {
  constructor() {
    if (this.constructor == Connector) {
      throw new Error('Connector is an abstract class');
    }
  }

  // Registers a callback to receive messages from the device. A race may occur
  // if this is called after requestDevice() is called in which some device
  // messages are lost.
  onDeviceMsg(cb) {
    throw 'Not implemented!';
  }

  // Selects a particular device in the signaling server and opens the signaling
  // channel with it (but doesn't send any message to the device). Returns a
  // promise to an object with the following properties:
  // - deviceInfo: The info object provided by the device when it registered
  // with the server.
  // - infraConfig: The server's infrastructure configuration (mainly STUN and
  // TURN servers)
  // The promise may take a long time to resolve if, for example, the server
  // decides to wait for a device with the provided id to register with it. The
  // promise may be rejected if there are connectivity issues, a device with
  // that id doesn't exist or this client doesn't have rights to access that
  // device.
  async requestDevice(deviceId) {
    throw 'Not implemented!';
  }

  // Sends a message to the device selected with requestDevice. It's an error to
  // call this function before the promise from requestDevice() has resolved.
  // Returns an empty promise that is rejected when the message can not be
  // delivered, either because the device has not been requested yet or because
  // of connectivity issues.
  async sendToDevice(msg) {
    throw 'Not implemented!';
  }
}

// End of Server Connector Interface.

// The following code is internal and shouldn't be accessed outside this file.

function httpUrl(path) {
  // The host url includes the api version as a prefix
  let curr = location.pathname;
  // Device files are always served from the /<prefix>/devices/... url
  let endIdx = curr.indexOf("/devices/");
  if (endIdx < 0) {
    // The path doesn't match our expectations
    throw "server connector is incompatible with this server";
  }
  let prefix = curr.substr(0, endIdx);
  return location.protocol + '//' + location.host + prefix + '/' + path;
}

async function ajaxPostJson(url, data) {
  const response = await fetch(url, {
    method: 'POST',
    cache: 'no-cache',
    headers: {'Content-Type': 'application/json'},
    redirect: 'follow',
    body: JSON.stringify(data),
  });
  return response.json();
}

// Implementation of the Connector interface using HTTP long polling
class PollingConnector extends Connector {
  #configUrl = httpUrl('infra_config');
  #connectUrl = httpUrl('connections');
  #forwardUrl;
  #messagesUrl;
  #config = undefined;
  #messagesReceived = 0;
  #pollerSchedule;
  #onDeviceMsgCb = msg =>
      console.error('Received device message without registered listener');

  onDeviceMsg(cb) {
    this.#onDeviceMsgCb = cb;
  }

  constructor() {
    super();
  }

  async requestDevice(deviceId) {
    let config = await this.#getConfig();
    let response = await ajaxPostJson(this.#connectUrl, {device_id: deviceId});
    let connId = response.connection_id;
    this.#forwardUrl = httpUrl(`connections/${connId}/:forward`);
    this.#messagesUrl = httpUrl(`connections/${connId}/messages`);

    this.#startPolling();

    return {
      deviceInfo: response.device_info,
      infraConfig: config,
    };
  }

  async sendToDevice(msg) {
    return await ajaxPostJson(this.#forwardUrl, {
      payload: msg,
    });
  }

  async #getConfig() {
    if (this.#config === undefined) {
      this.#config = await (await fetch(this.#configUrl, {
                       method: 'GET',
                       redirect: 'follow',
                     })).json();
    }
    return this.#config;
  }

  async #pollMessages() {
    let r = await fetch(
        this.#messagesUrl + `?start=${this.#messagesReceived}`, {
          method: 'GET',
          redirect: 'follow',
        })
    let arr = await r.json();
    this.#messagesReceived += arr.length;
    return arr;
  }

  #startPolling() {
    if (this.#pollerSchedule !== undefined) {
      return;
    }

    let currentPollDelay = 1000;
    let pollerRoutine = async () => {
      let messages = await this.#pollMessages();

      // Do exponential backoff on the polling up to 60 seconds
      currentPollDelay = Math.min(60000, 2 * currentPollDelay);
      for (const message of messages) {
        this.#onDeviceMsgCb(message.payload);
        // There is at least one message, poll sooner
        currentPollDelay = 1000;
      }
      this.#pollerSchedule = setTimeout(pollerRoutine, currentPollDelay);
    };

    this.#pollerSchedule = setTimeout(pollerRoutine, currentPollDelay);
  }
}

redpajama_set_name: RedPajamaGithub


text:
package org.killbill.billing.entitlement.block;

import java.util.List;
import java.util.UUID;

import org.killbill.billing.account.api.Account;
import org.killbill.billing.api.TestApiListener.NextEvent;
import org.killbill.billing.callcontext.InternalCallContext;
import org.killbill.billing.entitlement.EntitlementTestSuiteWithEmbeddedDB;
import org.killbill.billing.entitlement.api.BlockingState;
import org.killbill.billing.entitlement.api.BlockingStateType;
import org.killbill.billing.junction.DefaultBlockingState;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableList;

public class TestBlockingApi extends EntitlementTestSuiteWithEmbeddedDB {

    @BeforeMethod(groups = "slow")
    public void beforeMethod() throws Exception {
        super.beforeMethod();
        clock.resetDeltaFromReality();
    }

    @Test(groups = "slow")
    public void testApi() {
        final UUID uuid = UUID.randomUUID();
        final String overdueStateName = "WayPassedItMan";
        final String service = "TEST";

        final boolean blockChange = true;
        final boolean blockEntitlement = false;
        final boolean blockBilling = false;

        testListener.pushExpectedEvent(NextEvent.BLOCK);
        final BlockingState state1 = new DefaultBlockingState(uuid, BlockingStateType.ACCOUNT, overdueStateName, service, blockChange, blockEntitlement, blockBilling, clock.getUTCNow());
        blockingInternalApi.setBlockingState(state1, internalCallContext);
        assertListenerStatus();

        clock.setDeltaFromReality(1000 * 3600 * 24);

        testListener.pushExpectedEvent(NextEvent.BLOCK);
        final String overdueStateName2 = "NoReallyThisCantGoOn";
        final BlockingState state2 = new DefaultBlockingState(uuid, BlockingStateType.ACCOUNT, overdueStateName2, service, blockChange, blockEntitlement, blockBilling, clock.getUTCNow());
        blockingInternalApi.setBlockingState(state2, internalCallContext);
        assertListenerStatus();

        Assert.assertEquals(blockingInternalApi.getBlockingStateForService(uuid, BlockingStateType.ACCOUNT, service, internalCallContext).getStateName(), overdueStateName2);
    }

    @Test(groups = "slow")
    public void testApiHistory() throws Exception {
        final UUID uuid = UUID.randomUUID();
        final String overdueStateName = "WayPassedItMan";
        final String service = "TEST";

        final boolean blockChange = true;
        final boolean blockEntitlement = false;
        final boolean blockBilling = false;

        final Account account = accountApi.createAccount(getAccountData(7), callContext);
        final InternalCallContext internalCallContext = internalCallContextFactory.createInternalCallContext(account.getId(), callContext);

        testListener.pushExpectedEvent(NextEvent.BLOCK);
        final BlockingState state1 = new DefaultBlockingState(uuid, BlockingStateType.ACCOUNT, overdueStateName, service, blockChange, blockEntitlement, blockBilling, clock.getUTCNow());
        blockingInternalApi.setBlockingState(state1, internalCallContext);
        assertListenerStatus();

        clock.setDeltaFromReality(1000 * 3600 * 24);

        testListener.pushExpectedEvent(NextEvent.BLOCK);
        final String overdueStateName2 = "NoReallyThisCantGoOn";
        final BlockingState state2 = new DefaultBlockingState(uuid, BlockingStateType.ACCOUNT, overdueStateName2, service, blockChange, blockEntitlement, blockBilling, clock.getUTCNow());
        blockingInternalApi.setBlockingState(state2, internalCallContext);
        assertListenerStatus();

        final List<BlockingState> blockingAll = blockingInternalApi.getBlockingAllForAccount(internalCallContext);
        final List<BlockingState> history = ImmutableList.<BlockingState>copyOf(Collections2.<BlockingState>filter(blockingAll,
                                                                                new Predicate<BlockingState>() {
                                                                                @Override
                                                                                public boolean apply(final BlockingState input) {
                                                                                return input.getService().equals(service);
                                                                                }
                                                                                }));

        Assert.assertEquals(history.size(), 2);
        Assert.assertEquals(history.get(0).getStateName(), overdueStateName);
        Assert.assertEquals(history.get(1).getStateName(), overdueStateName2);
    }
}


text:
begin
  require 'dotenv'
  Dotenv.load
rescue LoadError
end

module Kracken
  PROVIDER_URL = ENV['RADIUS_OAUTH_PROVIDER_URL'] || "https://account.radiusnetworks.com"
end


text:
package com.miraclewong.modedemo;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by miraclewong on 15/8/25.
 */
public class TimeUtils {
    public static final SimpleDateFormat DEFAULT_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");         // 默认的时间格式
    public static final SimpleDateFormat DATE_FORMAT_DATE    = new SimpleDateFormat("yyyy-MM-dd");                  // 日期格式

    private TimeUtils() {
        throw new AssertionError();
    }

    /**
     * long time to string
     *
     * @param timeInMillis
     * @param dateFormat
     * @return
     */
    public static String getTime(long timeInMillis, SimpleDateFormat dateFormat) {
        return dateFormat.format(new Date(timeInMillis));
    }

    /**
     * long time to string, format is {@link #DEFAULT_DATE_FORMAT}
     *
     * @param timeInMillis
     * @return
     */
    public static String getTime(long timeInMillis) {
        return getTime(timeInMillis, DEFAULT_DATE_FORMAT);
    }

    /**
     * get current time in milliseconds
     *
     * @return
     */
    public static long getCurrentTimeInLong() {
        return System.currentTimeMillis();
    }

    /**
     * get current time in milliseconds, format is {@link #DEFAULT_DATE_FORMAT}
     *
     * @return
     */
    public static String getCurrentTimeInString() {
        return getTime(getCurrentTimeInLong());
    }

    /**
     * get current time in milliseconds
     *
     * @return
     */
    public static String getCurrentTimeInString(SimpleDateFormat dateFormat) {
        return getTime(getCurrentTimeInLong(), dateFormat);
    }
}


text:
class RedirectLoop < Exception
end


text:
#include <linux/time.h>
#include <sound/core.h>
#include <sound/emu10k1.h>

static int snd_emu10k1_timer_start(struct snd_timer *timer)
{
	struct snd_emu10k1 *emu;
	unsigned long flags;
	unsigned int delay;

	emu = snd_timer_chip(timer);
	delay = timer->sticks - 1;
	if (delay < 5 ) /* minimum time is 5 ticks */
		delay = 5;
	spin_lock_irqsave(&emu->reg_lock, flags);
	snd_emu10k1_intr_enable(emu, INTE_INTERVALTIMERENB);
	outw(delay & TIMER_RATE_MASK, emu->port + TIMER);
	spin_unlock_irqrestore(&emu->reg_lock, flags);
	return 0;
}

static int snd_emu10k1_timer_stop(struct snd_timer *timer)
{
	struct snd_emu10k1 *emu;
	unsigned long flags;

	emu = snd_timer_chip(timer);
	spin_lock_irqsave(&emu->reg_lock, flags);
	snd_emu10k1_intr_disable(emu, INTE_INTERVALTIMERENB);
	spin_unlock_irqrestore(&emu->reg_lock, flags);
	return 0;
}

static int snd_emu10k1_timer_precise_resolution(struct snd_timer *timer,
					       unsigned long *num, unsigned long *den)
{
	*num = 1;
	*den = 48000;
	return 0;
}

static struct snd_timer_hardware snd_emu10k1_timer_hw = {
	.flags = SNDRV_TIMER_HW_AUTO,
	.resolution = 20833, /* 1 sample @ 48KHZ = 20.833...us */
	.ticks = 1024,
	.start = snd_emu10k1_timer_start,
	.stop = snd_emu10k1_timer_stop,
	.precise_resolution = snd_emu10k1_timer_precise_resolution,
};

int __devinit snd_emu10k1_timer(struct snd_emu10k1 *emu, int device)
{
	struct snd_timer *timer = NULL;
	struct snd_timer_id tid;
	int err;

	tid.dev_class = SNDRV_TIMER_CLASS_CARD;
	tid.dev_sclass = SNDRV_TIMER_SCLASS_NONE;
	tid.card = emu->card->number;
	tid.device = device;
	tid.subdevice = 0;
	if ((err = snd_timer_new(emu->card, "EMU10K1", &tid, &timer)) >= 0) {
		strcpy(timer->name, "EMU10K1 timer");
		timer->private_data = emu;
		timer->hw = snd_emu10k1_timer_hw;
	}
	emu->timer = timer;
	return err;
}


text:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class InventoryItem : MonoBehaviour {

	[SerializeField] Image img_item;
	[SerializeField] Image img_owner;

	public Item itemInField;

	public int buttonId;

	private void Start(){
		DisplayItem();
	}

	public void DisplayItem(){
		if(itemInField != null && itemInField.itemType != Item.ItemType.None){
			Color outColor;
			img_item.enabled = true;
			img_item.sprite = itemInField.GetSprite(out outColor);
			img_item.color = outColor;
		}else if(itemInField.itemType == Item.ItemType.None){
			img_item.enabled = false;
		}
	}
	public void SelectItem(){

		if(itemInField.itemType == Item.ItemType.Armor){
			SwapItem (CharacterManager.SelectedCharacter.ArmorItem);
		}else if(itemInField.itemType != Item.ItemType.None){
			SwapItem(CharacterManager.SelectedCharacter.WeaponItem, false);
		}else if(CharacterManager.SelectedCharacter.WeaponItem.itemType != null){
			SwapItem(CharacterManager.SelectedCharacter.WeaponItem, false);
		}else if(CharacterManager.SelectedCharacter.ArmorItem !=null){
			SwapItem(CharacterManager.SelectedCharacter.ArmorItem);
		}
	}

	void SwapItem (Item charactersItem, bool armor = true)
	{
		Item auxItem = itemInField;
		auxItem.itemOwner = CharacterManager.SelectedCharacter;
		itemInField = charactersItem;
		itemInField.itemOwner = null;
		if(armor)CharacterManager.SelectedCharacter.ArmorItem = auxItem;
		else CharacterManager.SelectedCharacter.WeaponItem = auxItem;

		DisplayItem ();
		HubManager.ShowCharacter (CharacterManager.SelectedCharacter);

	}
}


text:
<?xml version="1.0"?>
<!--
  ~ Copyright (c) 2010-2013 Evolveum
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<name>Dummy Connector</name>
	<groupId>com.evolveum.icf</groupId>
	<artifactId>dummy-connector</artifactId>
	<version>3.3-SNAPSHOT</version>
	<packaging>jar</packaging>
	<parent>
		<artifactId>icf-connectors</artifactId>
		<groupId>com.evolveum.midpoint</groupId>
		<version>3.3-SNAPSHOT</version>
	</parent>
    <scm>
        <connection>https://github.com/Evolveum/midpoint.git</connection>
        <developerConnection>git@github.com:Evolveum/midpoint.git</developerConnection>
        <url>https://fisheye.evolveum.com/browse/midPoint</url>
    </scm>
	<dependencies>
		<dependency>
			<groupId>net.tirasa.connid</groupId>
			<artifactId>connector-framework</artifactId>
		</dependency>
		<dependency>
			<groupId>net.tirasa.connid</groupId>
			<artifactId>connector-framework-internal</artifactId>
		</dependency>
		<dependency>
			<groupId>com.evolveum.icf</groupId>
			<artifactId>dummy-resource</artifactId>
			<version>3.3-SNAPSHOT</version>
		</dependency>
		<dependency>
			<groupId>org.testng</groupId>
			<artifactId>testng</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<configuration>
					<archive>
						<manifestEntries>
							<Version-Number>${project.version}</Version-Number>
							<SCM-Revision>${describe}</SCM-Revision>
							<Organization>Evolveum</Organization>
							<Organization-URL>http://www.evolveum.com</Organization-URL>
							<Bugtracking-System>http://jira.evolveum.com</Bugtracking-System>
							<License>Apache License v2.0</License>
							<License-URL>http://www.apache.org/licenses/LICENSE-2.0.txt</License-URL>
							<Bundle-Name>Dummy Connector</Bundle-Name>
							<ConnectorBundle-FrameworkVersion>1.1</ConnectorBundle-FrameworkVersion>
							<ConnectorBundle-Name>com.evolveum.icf.dummy</ConnectorBundle-Name>
							<Bundle-Vendor>Evolveum</Bundle-Vendor>
							<ConnectorBundle-Version>2.0</ConnectorBundle-Version>
							<Bundle-Version>2.0</Bundle-Version>
							<Bundle-ManifestVersion>2</Bundle-ManifestVersion>
							<Bundle-SymbolicName>com.evolveum.icf.dummy</Bundle-SymbolicName>
						</manifestEntries>
					</archive>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>


text: <!doctype html><title>&</title>


text:
package com.sage.cerberus.core.validators;

import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.sage.cerberus.coreAPI.PlatformService;
import com.sage.cerberus.model.Game;
import com.sage.cerberus.model.Platform;
import com.sage.cerberus.validation.MessageInvalidationReason;
import com.sage.cerberus.validation.ValidationResult;
import com.sage.cerberus.validation.Validator;

public class GameValidator implements Validator<Game> {

	private Session session;

	private PlatformService platformService;

	public GameValidator(Session session, PlatformService platformService){
		this.session = session;
		this.platformService = platformService;
	}

	@Override
	public ValidationResult validate(Game candidate) {
		ValidationResult result = new ValidationResult();

		for (Platform platform : candidate.getPlatforms()) {
			if (this.platformService.getPlatformById(platform.getId()) == null) {
				result.addReason(MessageInvalidationReason.error("Invalid platforms for Game"));
			}
		}

		boolean exists = session.createCriteria(Game.class)
				.add(Restrictions.eq("name", candidate.getName()))
				.uniqueResult() != null;

		if(exists){
			result.addReason(MessageInvalidationReason.error("A Game with this name already exists"));
		}

		return result;
	}

}


text:
import * as actions from '../actions/hpMonitorActions';

const initialState = {
  jobData: [],
  trialData: [],
  dialogTrialOpen: false,
  loading: false,
  trialName: '',
};

const hpMonitorReducer = (state = initialState, action) => {
  switch (action.type) {
    case actions.FETCH_HP_JOB_INFO_REQUEST:
      return {
        ...state,
        loading: true,
        dialogTrialOpen: false,
      };
    case actions.FETCH_HP_JOB_INFO_SUCCESS:
      return {
        ...state,
        jobData: action.jobData,
        loading: false,
      };
    case actions.FETCH_HP_JOB_INFO_FAILURE:
      return {
        ...state,
        loading: false,
      };
    case actions.FETCH_HP_JOB_TRIAL_INFO_SUCCESS:
      return {
        ...state,
        trialData: action.trialData,
        dialogTrialOpen: true,
        trialName: action.trialName,
      };
    case actions.CLOSE_DIALOG_TRIAL:
      return {
        ...state,
        dialogTrialOpen: false,
      };
    default:
      return state;
  }
};

export default hpMonitorReducer;


text:
package org.fife.rsta.ac.java;

import java.awt.Cursor;
import java.awt.Point;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;

import org.fife.rsta.ac.ShorthandCompletionCache;
import org.fife.rsta.ac.java.buildpath.LibraryInfo;
import org.fife.rsta.ac.java.buildpath.SourceLocation;
import org.fife.rsta.ac.java.classreader.ClassFile;
import org.fife.rsta.ac.java.classreader.FieldInfo;
import org.fife.rsta.ac.java.classreader.MemberInfo;
import org.fife.rsta.ac.java.classreader.MethodInfo;
import org.fife.rsta.ac.java.rjc.ast.CodeBlock;
import org.fife.rsta.ac.java.rjc.ast.CompilationUnit;
import org.fife.rsta.ac.java.rjc.ast.Field;
import org.fife.rsta.ac.java.rjc.ast.FormalParameter;
import org.fife.rsta.ac.java.rjc.ast.ImportDeclaration;
import org.fife.rsta.ac.java.rjc.ast.LocalVariable;
import org.fife.rsta.ac.java.rjc.ast.Member;
import org.fife.rsta.ac.java.rjc.ast.Method;
import org.fife.rsta.ac.java.rjc.ast.NormalClassDeclaration;
import org.fife.rsta.ac.java.rjc.ast.TypeDeclaration;
import org.fife.rsta.ac.java.rjc.lang.Type;
import org.fife.rsta.ac.java.rjc.lang.TypeArgument;
import org.fife.rsta.ac.java.rjc.lang.TypeParameter;
import org.fife.ui.autocomplete.DefaultCompletionProvider;
import org.fife.ui.rsyntaxtextarea.RSyntaxDocument;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.RSyntaxUtilities;
import org.fife.ui.rsyntaxtextarea.Token;

/**
 * Parses a Java AST for code completions.  It currently scans the following:
 *
 *

 *
Import statements
 *
Method names
 *
Field names
 *

 *
 * Also, if the caret is inside a method, local variables up to the caret
 * position are also returned.
 *
 * @author Robert Futrell
 * @version 1.0
 */
class SourceCompletionProvider extends DefaultCompletionProvider {

	/**
	 * The parent completion provider.
	 */
	private JavaCompletionProvider javaProvider;

	/**
	 * Used to get information about what classes match imports.
	 */
	private JarManager jarManager;

	private static final String JAVA_LANG_PACKAGE			= "java.lang.*";
	private static final String THIS						= "this";

	//Shorthand completions (templates and comments)
	private ShorthandCompletionCache shorthandCache;
	/**
	 * Constructor.
	 */
	public SourceCompletionProvider() {
		this(null);
	}

	/**
	 * Constructor.
	 *
	 * @param jarManager The jar manager for this provider.
	 */
	public SourceCompletionProvider(JarManager jarManager) {
		if (jarManager==null) {
			jarManager = new JarManager();
		}
		this.jarManager = jarManager;
		setParameterizedCompletionParams('(', ", ", ')');
		setAutoActivationRules(false, "."); // Default - only activate after '.'
		setParameterChoicesProvider(new SourceParamChoicesProvider());
	}

	private void addCompletionsForStaticMembers(Set set,
						CompilationUnit cu, ClassFile cf, String pkg) {

		// Check us first, so if we override anything, we get the "newest"
		// version.
		int methodCount = cf.getMethodCount();
		for (int i=0; i<methodCount; i++) {
			MethodInfo info = cf.getMethodInfo(i);
			if (isAccessible(info, pkg) && info.isStatic()) {
				MethodCompletion mc = new MethodCompletion(this, info);
				set.add(mc);
			}
		}

		int fieldCount = cf.getFieldCount();
		for (int i=0; i<fieldCount; i++) {
			FieldInfo info = cf.getFieldInfo(i);
			if (isAccessible(info, pkg) && info.isStatic()) {
				FieldCompletion fc = new FieldCompletion(this, info);
				set.add(fc);
			}
		}

		ClassFile superClass = getClassFileFor(cu, cf.getSuperClassName(true));
		if (superClass!=null) {
			addCompletionsForStaticMembers(set, cu, superClass, pkg);
		}

	}

	/**
	 * Adds completions for accessible methods and fields of super classes.
	 * This is only called when the caret is inside of a class.
	 * TODO: Handle accessibility correctly!
	 *
	 * @param set
	 * @param cu The compilation unit.
	 * @param cf A class in the chain of classes that a type being parsed
	 *        inherits from.
	 * @param pkg The package of the source being parsed.
	 * @param typeParamMap A mapping of type parameters to type arguments
	 *        for the object whose fields/methods/etc. are currently being
	 *        code-completed.
	 */
	private void addCompletionsForExtendedClass(Set set,
						CompilationUnit cu, ClassFile cf, String pkg,
						Map typeParamMap) {

		// Reset this class's type-arguments-to-type-parameters map, so that
		// when methods and fields need to know type arguments, they can query
		// for them.
		cf.setTypeParamsToTypeArgs(typeParamMap);

		// Check us first, so if we override anything, we get the "newest"
		// version.
		int methodCount = cf.getMethodCount();
		for (int i=0; i<methodCount; i++) {
			MethodInfo info = cf.getMethodInfo(i);
			// Don't show constructors
			if (isAccessible(info, pkg) && !info.isConstructor()) {
				MethodCompletion mc = new MethodCompletion(this, info);
				set.add(mc);
			}
		}

		int fieldCount = cf.getFieldCount();
		for (int i=0; i<fieldCount; i++) {
			FieldInfo info = cf.getFieldInfo(i);
			if (isAccessible(info, pkg)) {
				FieldCompletion fc = new FieldCompletion(this, info);
				set.add(fc);
			}
		}

		// Add completions for any non-overridden super-class methods.
		ClassFile superClass = getClassFileFor(cu, cf.getSuperClassName(true));
		if (superClass!=null) {
			addCompletionsForExtendedClass(set, cu, superClass, pkg, typeParamMap);
		}

		// Add completions for any interface methods, in case this class is
		// abstract and hasn't implemented some of them yet.
		// TODO: Do this only if "top-level" class is declared abstract
		for (int i=0; i<cf.getImplementedInterfaceCount(); i++) {
			String inter = cf.getImplementedInterfaceName(i, true);
			cf = getClassFileFor(cu, inter);
			addCompletionsForExtendedClass(set, cu, cf, pkg, typeParamMap);
		}

	}

	/**
	 * Adds completions for all methods and public fields of a local variable.
	 * This will add nothing if the local variable is a primitive type.
	 *
	 * @param cu The compilation unit being parsed.
	 * @param var The local variable.
	 * @param retVal The set to add completions to.
	 */
	private void addCompletionsForLocalVarsMethods(CompilationUnit cu,
			LocalVariable var, Set retVal) {

		Type type = var.getType();
		String pkg = cu.getPackageName();

		if (type.isArray()) {
			ClassFile cf = getClassFileFor(cu, "java.lang.Object");
			addCompletionsForExtendedClass(retVal, cu, cf, pkg, null);
			FieldCompletion fc = FieldCompletion.
				createLengthCompletion(this, type);
			retVal.add(fc);
		}

		else if (!type.isBasicType()) {
			String typeStr = type.getName(true, false);
			ClassFile cf = getClassFileFor(cu, typeStr);
			if (cf!=null) {
				Map typeParamMap = createTypeParamMap(type, cf);
				addCompletionsForExtendedClass(retVal, cu, cf, pkg, typeParamMap);
			}
		}

	}

	/**
	 * Adds simple shorthand completions relevant to Java.
	 *
	 * @param set The set to add to.
	 */
	private void addShorthandCompletions(Set set) {
		if(shorthandCache != null) {
			set.addAll(shorthandCache.getShorthandCompletions());
		}
	}

	/**
	 * Set template completion cache for source completion provider
	 * @param templateCache
	 */
	public void setShorthandCache(ShorthandCompletionCache shorthandCache) {
		this.shorthandCache = shorthandCache;
	}

	/**
	 * Gets the {@link ClassFile} for a class.
	 *
	 * @param cu The compilation unit being parsed.
	 * @param className The name of the class (fully qualified or not).
	 * @return The {@link ClassFile} for the class, or null if
	 *         cf represents java.lang.Object (or
	 *         if the super class could not be determined).
	 */
	private ClassFile getClassFileFor(CompilationUnit cu, String className) {

		//System.err.println(">>> Getting class file for: " + className);
		if (className==null) {
			return null;
		}

		ClassFile superClass = null;

		// Determine the fully qualified class to grab
		if (!Util.isFullyQualified(className)) {

			// Check in this source file's package first
			String pkg = cu.getPackageName();
			if (pkg!=null) {
				String temp = pkg + "." + className;
				superClass = jarManager.getClassEntry(temp);
			}

			// Next, go through the imports (order is important)
			if (superClass==null) {
				for (Iterator i=cu.getImportIterator(); i.hasNext(); ) {
					ImportDeclaration id = (ImportDeclaration)i.next();
					String imported = id.getName();
					if (imported.endsWith(".*")) {
						String temp = imported.substring(
								0, imported.length()-1) + className;
						superClass = jarManager.getClassEntry(temp);
						if (superClass!=null) {
							break;
						}
					}
					else if (imported.endsWith("." + className)) {
						superClass = jarManager.getClassEntry(imported);
						break;
					}
				}
			}

			// Finally, try java.lang
			if (superClass==null) {
				String temp = "java.lang." + className;
				superClass = jarManager.getClassEntry(temp);
			}

		}

		else {
			superClass = jarManager.getClassEntry(className);
		}

		return superClass;

	}

	/**
	 * Adds completions for local variables in a method.
	 *
	 * @param set
	 * @param method
	 * @param offs The caret's offset into the source.  This should be inside
	 *        of method.
	 */
	private void addLocalVarCompletions(Set set, Method method, int offs) {

		for (int i=0; i<method.getParameterCount(); i++) {
			FormalParameter param = method.getParameter(i);
			set.add(new LocalVariableCompletion(this, param));
		}

		CodeBlock body = method.getBody();
		if (body!=null) {
			addLocalVarCompletions(set, body, offs);
		}

	}

	/**
	 * Adds completions for local variables in a code block inside of a method.
	 *
	 * @param set
	 * @param block The code block.
	 * @param offs The caret's offset into the source. This should be inside
	 *        of block.
	 */
	private void addLocalVarCompletions(Set set, CodeBlock block, int offs) {

		for (int i=0; i<block.getLocalVarCount(); i++) {
			LocalVariable var = block.getLocalVar(i);
			if (var.getNameEndOffset()<=offs) {
				set.add(new LocalVariableCompletion(this, var));
			}
			else { // This and all following declared after offs
				break;
			}
		}

		for (int i=0; i<block.getChildBlockCount(); i++) {
			CodeBlock child = block.getChildBlock(i);
			if (child.containsOffset(offs)) {
				addLocalVarCompletions(set, child, offs);
				break; // All other blocks are past this one
			}
			// If we've reached a block that's past the offset we're
			// searching for...
			else if (child.getNameStartOffset()>offs) {
				break;
			}
		}

	}

	/**
	 * Adds a jar to read from.
	 *
	 * @param info The jar to add.  If this is null, then
	 *        the current JVM's main JRE jar (rt.jar, or classes.jar on OS X)
	 *        will be added.  If this jar has already been added, adding it
	 *        again will do nothing (except possibly update its attached source
	 *        location).
	 * @throws IOException If an IO error occurs.
	 * @see #getJars()
	 * @see #removeJar(File)
	 */
	public void addJar(LibraryInfo info) throws IOException {
		jarManager.addClassFileSource(info);
	}

	/**
	 * Checks whether the user is typing a completion for a String member after
	 * a String literal.
	 *
	 * @param comp The text component.
	 * @param alreadyEntered The text already entered.
	 * @param cu The compilation unit being parsed.
	 * @param set The set to add possible completions to.
	 * @return Whether the user is indeed typing a completion for a String
	 *         literal member.
	 */
	private boolean checkStringLiteralMember(JTextComponent comp,
											String alreadyEntered,
											CompilationUnit cu, Set set) {

		boolean stringLiteralMember = false;

		int offs = comp.getCaretPosition() - alreadyEntered.length() - 1;
		if (offs>1) {
			RSyntaxTextArea textArea = (RSyntaxTextArea)comp;
			RSyntaxDocument doc = (RSyntaxDocument)textArea.getDocument();
			try {
				//System.out.println(doc.charAt(offs) + ", " + doc.charAt(offs+1));
				if (doc.charAt(offs)=='"' && doc.charAt(offs+1)=='.') {
					int curLine = textArea.getLineOfOffset(offs);
					Token list = textArea.getTokenListForLine(curLine);
					Token prevToken = RSyntaxUtilities.getTokenAtOffset(list, offs);
					if (prevToken!=null &&
							prevToken.getType()==Token.LITERAL_STRING_DOUBLE_QUOTE) {
						ClassFile cf = getClassFileFor(cu, "java.lang.String");
						addCompletionsForExtendedClass(set, cu, cf,
													cu.getPackageName(), null);
						stringLiteralMember = true;
					}
					else {
						System.out.println(prevToken);
					}
				}
			} catch (BadLocationException ble) { // Never happens
				ble.printStackTrace();
			}
		}

		return stringLiteralMember;

	}

	/**
	 * Removes all jars from the "build path."
	 *
	 * @see #removeJar(File)
	 * @see #addClassFileSource(JarInfo)
	 * @see #getJars()
	 */
	public void clearJars() {
		jarManager.clearClassFileSources();
		// The memory used by the completions can be quite large, so go ahead
		// and clear out the completions list so no-longer-needed ones are
		// eligible for GC.
		clear();
	}

	/**
	 * Creates and returns a mapping of type parameters to type arguments.
	 *
	 * @param type The type of a variable/field/etc. whose fields/methods/etc.
	 *        are being code completed, as declared in the source.  This
	 *        includes type arguments.
	 * @param cf The ClassFile representing the actual type of
	 *        the variable/field/etc. being code completed
	 * @return A mapping of type parameter names to type arguments (both
	 *         Strings).
	 */
	private Map createTypeParamMap(Type type, ClassFile cf) {
		Map typeParamMap = null;
		List typeArgs = type.getTypeArguments(type.getIdentifierCount()-1);
		if (typeArgs!=null) {
			typeParamMap = new HashMap();
			List paramTypes = cf.getParamTypes();
			// Should be the same size!  Otherwise, the source code has
			// too many/too few type arguments listed for this type.
			int min = Math.min(paramTypes==null ? 0 : paramTypes.size(),
									typeArgs.size());
			for (int i=0; i<min; i++) {
				TypeArgument typeArg = (TypeArgument)typeArgs.get(i);
				typeParamMap.put(paramTypes.get(i), typeArg.toString());
			}
		}
		return typeParamMap;
	}

	/**
	 * {@inheritDoc}
	 */
	public List getCompletionsAt(JTextComponent tc, Point p) {
		getCompletionsImpl(tc); // Force loading of completions
		return super.getCompletionsAt(tc, p);
	}

	/**
	 * {@inheritDoc}
	 */
	protected List getCompletionsImpl(JTextComponent comp) {

		comp.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

		try {

		completions.clear();

		CompilationUnit cu = javaProvider.getCompilationUnit();
		if (cu==null) {
			return completions; // empty
		}

		Set set = new TreeSet();

		// Cut down the list to just those matching what we've typed.
		// Note: getAlreadyEnteredText() never returns null
		String text = getAlreadyEnteredText(comp);

		// Special case - end of a String literal
		boolean stringLiteralMember = checkStringLiteralMember(comp, text, cu,
																set);

		// Not after a String literal - regular code completion
		if (!stringLiteralMember) {

			// Don't add shorthand completions if they're typing something
			// qualified
			if (text.indexOf('.')==-1) {
				addShorthandCompletions(set);
			}

			loadImportCompletions(set, text, cu);

			// Add completions for fully-qualified stuff (e.g. "com.sun.jav")
			//long startTime = System.currentTimeMillis();
			jarManager.addCompletions(this, text, set);
			//long time = System.currentTimeMillis() - startTime;
			//System.out.println("jar completions loaded in: " + time);

			// Loop through all types declared in this source, and provide
			// completions depending on in what type/method/etc. the caret's in.
			loadCompletionsForCaretPosition(cu, comp, text, set);

		}

		// Do a final sort of all of our completions and we're good to go!
		completions = new ArrayList(set);
		Collections.sort(completions);

		// Only match based on stuff after the final '.', since that's what is
		// displayed for all of our completions.
		text = text.substring(text.lastIndexOf('.')+1);

		int start = Collections.binarySearch(completions, text, comparator);
		if (start<0) {
			start = -(start+1);
		}
		else {
			// There might be multiple entries with the same input text.
			while (start>0 &&
					comparator.compare(completions.get(start-1), text)==0) {
				start--;
			}
		}

		int end = Collections.binarySearch(completions, text+'{', comparator);
		end = -(end+1);

		return completions.subList(start, end);

		} finally {
			comp.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
		}

	}

	/**
	 * Returns the jars on the "build path."
	 *
	 * @return A list of {@link JarInfo}s.  Modifying a <tt>JarInfo</tt> in
	 *         this list will have no effect on this completion provider; in
	 *         order to do that, you must re-add the jar via
	 *         {@link #addClassFileSource(JarInfo)}. If there are no jars on the
	 *         "build path," this will be an empty list.
	 * @see #addClassFileSource(JarInfo)
	 */
	public List getJars() {
		return jarManager.getClassFileSources();
	}

public SourceLocation  getSourceLocForClass(String className) {
	return jarManager.getSourceLocForClass(className);
}

	/**
	 * Returns whether a method defined by a super class is accessible to
	 * this class.
	 *
	 * @param info Information about the member.
	 * @param pkg The package of the source currently being parsed.
	 * @return Whether or not the method is accessible.
	 */
	private boolean isAccessible(MemberInfo info, String pkg) {

		boolean accessible = false;
		int access = info.getAccessFlags();

		if (org.fife.rsta.ac.java.classreader.Util.isPublic(access) ||
				org.fife.rsta.ac.java.classreader.Util.isProtected(access)) {
			accessible = true;
		}
		else if (org.fife.rsta.ac.java.classreader.Util.isDefault(access)) {
			String pkg2 = info.getClassFile().getPackageName();
			accessible = (pkg==null && pkg2==null) ||
						(pkg!=null && pkg.equals(pkg2));
		}

		return accessible;

	}

	/**
	 * {@inheritDoc}
	 */
	protected boolean isValidChar(char ch) {
		return Character.isJavaIdentifierPart(ch) || ch=='.';
	}

	/**
	 * Loads completions based on the current caret location in the source.  In
	 * other words:
	 *
	 *

	 *
If the caret is anywhere in a class, the names of all methods and
	 *       fields in the class are loaded.  Methods and fields in super
	 *       classes are also loaded.  TODO: Get super methods/fields added
	 *       correctly by access!
	 *
If the caret is in a field, local variables currently accessible
	 *       are loaded.
	 *

	 *
	 * @param cu
	 * @param comp
	 * @param alreadyEntered
	 * @param retVal
	 */
	private void loadCompletionsForCaretPosition(CompilationUnit cu,
			JTextComponent comp, String alreadyEntered, Set retVal) {

		// Get completions for all fields and methods of all type declarations.

		//long startTime = System.currentTimeMillis();
		int caret = comp.getCaretPosition();
		//List temp = new ArrayList();
		int start, end;

		int lastDot = alreadyEntered.lastIndexOf('.');
		boolean qualified = lastDot>-1;
		String prefix = qualified ? alreadyEntered.substring(0, lastDot) : null;

		for (Iterator i=cu.getTypeDeclarationIterator(); i.hasNext(); ) {

			TypeDeclaration td = (TypeDeclaration)i.next();
			start = td.getBodyStartOffset();
			end = td.getBodyEndOffset();

			if (caret>start && caret<=end) {
				loadCompletionsForCaretPosition(cu, comp, alreadyEntered,
									retVal, td, prefix, caret);
			}

			else if (caret<start) {
				break; // We've passed any type declarations we could be in
			}

		}

		//long time = System.currentTimeMillis() - startTime;
		//System.out.println("methods/fields/localvars loaded in: " + time);

	}

	/**
	 * Loads completions based on the current caret location in the source.
	 * This method is called when the caret is found to be in a specific type
	 * declaration.  This method checks if the caret is in a child type
	 * declaration first, then adds completions for itself next.
	 *
	 *

	 *
If the caret is anywhere in a class, the names of all methods and
	 *       fields in the class are loaded.  Methods and fields in super
	 *       classes are also loaded.  TODO: Get super methods/fields added
	 *       correctly by access!
	 *
If the caret is in a field, local variables currently accessible
	 *       are loaded.
	 *

	 *
	 * @param cu
	 * @param comp
	 * @param alreadyEntered
	 * @param retVal
	 */
	private void loadCompletionsForCaretPosition(CompilationUnit cu,
			JTextComponent comp, String alreadyEntered, Set retVal,
			TypeDeclaration td, String prefix, int caret) {

		// Do any child types first, so if any vars, etc. have duplicate names,
		// we pick up the one "closest" to us first.
		for (int i=0; i<td.getChildTypeCount(); i++) {
			TypeDeclaration childType = td.getChildType(i);
			loadCompletionsForCaretPosition(cu, comp, alreadyEntered, retVal,
					childType, prefix, caret);
		}

		Method currentMethod = null;

		Map typeParamMap = new HashMap();
		if (td instanceof NormalClassDeclaration) {
			NormalClassDeclaration ncd = (NormalClassDeclaration)td;
			List typeParams = ncd.getTypeParameters();
			if (typeParams!=null) {
				for (int i=0; i<typeParams.size(); i++) {
					TypeParameter typeParam = (TypeParameter)typeParams.get(i);
					String typeVar = typeParam.getName();
					// For non-qualified completions, use type var name.
					typeParamMap.put(typeVar, typeVar);
				}
			}
		}

		// Get completions for this class's methods, fields and local
		// vars.  Do this before checking super classes so that, if
		// we overrode anything, we get the "newest" version.
		String pkg = cu.getPackageName();
		for (Iterator j=td.getMemberIterator(); j.hasNext(); ) {
			Member m = (Member)j.next();
			if (m instanceof Method) {
				Method method = (Method)m;
				if (prefix==null || THIS.equals(prefix)) {
					retVal.add(new MethodCompletion(this, method));
				}
				if (caret>=method.getBodyStartOffset() && caret<method.getBodyEndOffset()) {
					currentMethod = method;
					// Don't add completions for local vars if there is
					// a prefix, even "this".
					if (prefix==null) {
						addLocalVarCompletions(retVal, method, caret);
					}
				}
			}
			else if (m instanceof Field) {
				if (prefix==null || THIS.equals(prefix)) {
					Field field = (Field)m;
					retVal.add(new FieldCompletion(this, field));
				}
			}
		}

		// Completions for superclass methods.
		// TODO: Implement me better
		if (prefix==null || THIS.equals(prefix)) {
			if (td instanceof NormalClassDeclaration) {
				NormalClassDeclaration ncd = (NormalClassDeclaration)td;
				Type extended = ncd.getExtendedType();
				if (extended!=null) { // e.g., not java.lang.Object
					String superClassName = extended.toString();
					ClassFile cf = getClassFileFor(cu, superClassName);
					if (cf!=null) {
						addCompletionsForExtendedClass(retVal, cu, cf, pkg, null);
					}
					else {
						System.out.println("[DEBUG]: Couldn't find ClassFile for: " + superClassName);
					}
				}
			}
		}

		// Completions for methods of fields, return values of methods,
		// static fields/methods, etc.
		if (prefix!=null && !THIS.equals(prefix)) {
			loadCompletionsForCaretPositionQualified(cu,
					alreadyEntered, retVal,
					td, currentMethod, prefix, caret);
		}

	}

	/**
	 * Loads completions for the text at the current caret position, if there
	 * is a "prefix" of chars and at least one '.' character in the text up to
	 * the caret.  This is currently very limited and needs to be improved.
	 *
	 * @param cu
	 * @param alreadyEntered
	 * @param retVal
	 * @param td The type declaration the caret is in.
	 * @param currentMethod The method the caret is in, or null if
	 *        none.
	 * @param prefix The text up to the current caret position.  This is
	 *        guaranteed to be non-null not equal to
	 *        "<tt>this</tt>".
	 * @param offs The offset of the caret in the document.
	 */
	private void loadCompletionsForCaretPositionQualified(CompilationUnit cu,
			String alreadyEntered, Set retVal,
			TypeDeclaration td, Method currentMethod, String prefix, int offs) {

		// TODO: Remove this restriction.
		int dot = prefix.indexOf('.');
		if (dot>-1) {
			System.out.println("[DEBUG]: Qualified non-this completions currently only go 1 level deep");
			return;
		}

		// TODO: Remove this restriction.
		else if (!prefix.matches("[A-Za-z_][A-Za-z0-9_\\$]*")) {
			System.out.println("[DEBUG]: Only identifier non-this completions are currently supported");
			return;
		}

		String pkg = cu.getPackageName();
		boolean matched = false;

		for (Iterator j=td.getMemberIterator(); j.hasNext(); ) {

			Member m = (Member)j.next();

			// The prefix might be a field in the local class.
			if (m instanceof Field) {

				Field field = (Field)m;

				if (field.getName().equals(prefix)) {
					//System.out.println("FOUND: " + prefix + " (" + pkg + ")");
					Type type = field.getType();
					if (type.isArray()) {
						ClassFile cf = getClassFileFor(cu, "java.lang.Object");
						addCompletionsForExtendedClass(retVal, cu, cf, pkg, null);
						FieldCompletion fc = FieldCompletion.
							createLengthCompletion(this, type);
						retVal.add(fc);
					}
					else if (!type.isBasicType()) {
						String typeStr = type.getName(true, false);
						ClassFile cf = getClassFileFor(cu, typeStr);
						// Add completions for extended class type chain
						if (cf!=null) {
							Map typeParamMap = createTypeParamMap(type, cf);
							addCompletionsForExtendedClass(retVal, cu, cf, pkg, typeParamMap);
							// Add completions for all implemented interfaces
							// TODO: Only do this if type is abstract!
							for (int i=0; i<cf.getImplementedInterfaceCount(); i++) {
								String inter = cf.getImplementedInterfaceName(i, true);
								cf = getClassFileFor(cu, inter);
								System.out.println(cf);
							}
						}
					}
					matched = true;
					break;
				}

			}

		}

		// The prefix might be for a local variable in the current method.
		if (currentMethod!=null) {

			boolean found = false;

			// Check parameters to the current method
			for (int i=0; i<currentMethod.getParameterCount(); i++) {
				FormalParameter param = currentMethod.getParameter(i);
				String name = param.getName();
				// Assuming prefix is "one level deep" and contains no '.'...
				if (prefix.equals(name)) {
					addCompletionsForLocalVarsMethods(cu, param, retVal);
					found = true;
					break;
				}
			}

			// If a formal param wasn't matched, check local variables.
			if (!found) {
				CodeBlock body = currentMethod.getBody();
				if (body!=null) {
					loadCompletionsForCaretPositionQualifiedCodeBlock(cu,
											retVal, td, body, prefix, offs);
				}
			}

			matched |= found;

		}

		// Could be a class name, in which case we'll need to add completions
		// for static fields and methods.
		if (!matched) {
			List imports = cu.getImports();
			List matches = jarManager.getClassesWithUnqualifiedName(
															prefix, imports);
			if (matches!=null) {
				for (int i=0; i<matches.size(); i++) {
					ClassFile cf = (ClassFile)matches.get(i);
					addCompletionsForStaticMembers(retVal, cu, cf, pkg);
				}
			}
		}

	}

	private void loadCompletionsForCaretPositionQualifiedCodeBlock(
			CompilationUnit cu, Set retVal,
			TypeDeclaration td, CodeBlock block, String prefix, int offs) {

		boolean found = false;

		for (int i=0; i<block.getLocalVarCount(); i++) {
			LocalVariable var = block.getLocalVar(i);
			if (var.getNameEndOffset()<=offs) {
				// TODO: This assumes prefix is "1 level deep"
				if (prefix.equals(var.getName())) {
					addCompletionsForLocalVarsMethods(cu, var, retVal);
					found = true;
					break;
				}
			}
			else { // This and all following declared after offs
				break;
			}
		}

		if (found) {
			return;
		}

		for (int i=0; i<block.getChildBlockCount(); i++) {
			CodeBlock child = block.getChildBlock(i);
			if (child.containsOffset(offs)) {
				loadCompletionsForCaretPositionQualifiedCodeBlock(cu, retVal,
						td, child, prefix, offs);
				break; // All other blocks are past this one
			}
			// If we've reached a block that's past the offset we're
			// searching for...
			else if (child.getNameStartOffset()>offs) {
				break;
			}
		}

	}

	/**
	 * Loads completions for a single import statement.
	 *
	 * @param importStr The import statement.
	 * @param pkgName The package of the source currently being parsed.
	 */
	private void loadCompletionsForImport(Set set, String importStr, String pkgName) {

		if (importStr.endsWith(".*")) {
			String pkg = importStr.substring(0, importStr.length()-2);
			boolean inPkg = pkg.equals(pkgName);
			List classes = jarManager.getClassesInPackage(pkg, inPkg);
			for (Iterator i=classes.iterator(); i.hasNext(); ) {
				ClassFile cf = (ClassFile)i.next();
				set.add(new ClassCompletion(this, cf));
			}
		}

		else {
			ClassFile cf = jarManager.getClassEntry(importStr);
			if (cf!=null) {
				set.add(new ClassCompletion(this, cf));
			}
		}

	}

	/**
	 * Loads completions for all import statements.
	 *
	 * @param cu The compilation unit being parsed.
	 */
	private void loadImportCompletions(Set set, String text,
									CompilationUnit cu) {

		// Fully-qualified completions are handled elsewhere, so no need to
		// duplicate the work here
		if (text.indexOf('.')>-1) {
			return;
		}

		//long startTime = System.currentTimeMillis();

		String pkgName = cu.getPackageName();
		loadCompletionsForImport(set, JAVA_LANG_PACKAGE, pkgName);
		for (Iterator i=cu.getImportIterator(); i.hasNext(); ) {
			ImportDeclaration id = (ImportDeclaration)i.next();
			String name = id.getName();
			if (!JAVA_LANG_PACKAGE.equals(name)) {
				loadCompletionsForImport(set, name, pkgName);
			}
		}
//		Collections.sort(completions);

		//long time = System.currentTimeMillis() - startTime;
		//System.out.println("imports loaded in: " + time);

	}

	/**
	 * Removes a jar from the "build path."
	 *
	 * @param jar The jar to remove.
	 * @return Whether the jar was removed.  This will be false
	 *         if the jar was not on the build path.
	 * @see #addClassFileSource(JarInfo)
	 * @see #getJars()
	 * @see #clearJars()
	 */
	public boolean removeJar(File jar) {
		boolean removed = jarManager.removeClassFileSource(jar);
		// The memory used by the completions can be quite large, so go ahead
		// and clear out the completions list so no-longer-needed ones are
		// eligible for GC.
		if (removed) {
			clear();
		}
		return removed;
	}

	/**
	 * Sets the parent Java provider.
	 *
	 * @param javaProvider The parent completion provider.
	 */
	void setJavaProvider(JavaCompletionProvider javaProvider) {
		this.javaProvider = javaProvider;
	}

}


text:
StumbleUponEvergreen
====================


text:
require File.join(File.dirname(__FILE__), '../config/environment')

def flatten_keys(hash, prefix="")
  keys = []
  hash.keys.each do |key|
    if hash[key].is_a? Hash
      current_prefix = prefix + "#{key}."
      keys << flatten_keys(hash[key], current_prefix)
    else
      keys << "#{prefix}#{key}"
    end
  end
  prefix == "" ? keys.flatten : keys
end

# list of locales
available_locales = Rails.application.config.i18n.available_locales.collect { |locale| locale.to_s }

# load locale.yml files
locales = {}
locales['xx'] = []
available_locales.each do |locale|
  locales[locale] = flatten_keys(YAML::load_file(Rails.root.join('config', 'locales', "#{locale}.yml"))).
      collect { |key| key.from(3) }
  locales['xx'] += locales[locale]
end

# list missing translations
available_locales.each do |locale|
  missing_keys = locales['xx'] - locales[locale]
  puts "#{locale}: missing keys: #{missing_keys.join(', ')}" if missing_keys.size > 0
end


text:
#ifndef _MINIX_PATHS_H_
#define _MINIX_PATHS_H_

#define _PATH_SERVICE	"/bin/service"
#define _PATH_PROC	"/proc/"

#define _PATH_SYSTEM_CONF "/etc/system.conf"
#define _PATH_SYSTEM_CONF_DIR "/etc/system.conf.d"
#define _PATH_SYSTEM_CONF_PKG_DIR       "/usr/pkg/etc/system.conf.d"

#define _PATH_DHCPCONF	"/etc/dhcp.conf"
#define _PATH_DHCPPID	"/usr/run/dhcpd.pid"
#define _PATH_DHCPCACHE	"/usr/adm/dhcp.cache"
#define _PATH_DHCPPOOL	"/usr/adm/dhcp.pool"

#define _PATH_RAMDISK	"/dev/ram"

#define _PATH_DRIVERS	"/service"

#define	_PATH_SERVACCES	"/etc/serv.access"

#define _PATH_HOSTNAME_FILE "/etc/hostname.file"

#endif /* _MINIX_PATHS_H_ */


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.paramsPositions = undefined;
exports.setupMethodHandlers = setupMethodHandlers;

var _feathersCommons = require('feathers-commons');

var _utils = require('./utils');

var debug = require('debug')('feathers-socket-commons:methods');

// The position of the params parameters for a service method so that we can extend them
// default is 1
var paramsPositions = exports.paramsPositions = {
  find: 0,
  update: 2,
  patch: 2
};

// Set up all method handlers for a service and socket.
function setupMethodHandlers(info, socket, path, service) {
  this.methods.forEach(function (method) {
    if (typeof service[method] !== 'function') {
      return;
    }

    var name = path + '::' + method;
    var connection = info.params(socket);
    var position = typeof paramsPositions[method] !== 'undefined' ? paramsPositions[method] : 1;

    debug('Setting up socket listener for event \'' + name + '\'');

    socket.on(name, function () {
      var _arguments = arguments;

      debug('Got \'' + name + '\' event with connection', connection);

      try {
        (function () {
          var args = (0, _feathersCommons.getArguments)(method, _arguments);
          var callback = args[args.length - 1];

          // NOTE (EK): socket.io just bombs silently if there is an error that
          // isn't up to it's standards, so you we inject a new error handler
          // to print a debug log and clean up the error object so it actually
          // gets transmitted back to the client.
          args[position] = Object.assign({ query: args[position] }, connection);
          args[args.length - 1] = function (error, data) {
            if (error) {
              debug('Error calling ' + name, error);
              return callback((0, _utils.normalizeError)(error));
            }

            callback(error, data);
          };

          service[method].apply(service, args);
        })();
      } catch (e) {
        var _callback = arguments[arguments.length - 1];
        debug('Error on socket', e);
        if (typeof _callback === 'function') {
          _callback((0, _utils.normalizeError)(e));
        }
      }
    });
  });
}


text:
class CreateFavorites < ActiveRecord::Migration
  def change
    create_table :favorites do |t|
      t.integer :artifact_id
      t.integer :user_id

      t.timestamps null: false
    end
  end
end


text:
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import playerController from './playerController';
import YouTubeEmbed from './embeds/YouTubeEmbed';

class YouTubePlayer extends Component {
  render() {
    const {
      aspectRatio,
    } = this.props;

    let style = {};

    if (aspectRatio) {
      const [width, height] = aspectRatio.split(':');
      style = {
        position: 'relative',
        height: 0,
        paddingBottom: `${height / width * 100}%`,
      };
    }

    return (
      <YouTubeEmbed {...this.props} style={style} />
    );
  }
}

YouTubePlayer.propTypes = {
  aspectRatio: PropTypes.string,
  loop: PropTypes.bool,
  play: PropTypes.bool,
  time: PropTypes.number,
  volume: PropTypes.number,
  onEnded: PropTypes.func,
  onError: PropTypes.func,
  onPause: PropTypes.func,
  onPlay: PropTypes.func,
  onReady: PropTypes.func,
  onTimeUpdate: PropTypes.func,
  onVolumeChange: PropTypes.func,
};

YouTubePlayer.defaultProps = {
  aspectRatio: '16:9',
  loop: false,
  play: false,
  time: 0,
  volume: 1,
  onEnded: () => {},
  onError: () => {},
  onPause: () => {},
  onPlay: () => {},
  onReady: () => {},
  onTimeUpdate: () => {},
  onVolumeChange: () => {},
};

export default playerController(YouTubePlayer);


text:
define(function(){

	require('core/string/trim'); //引用trim模块

});


text:
#tabs_container {
    width:100%;
    margin:0;
    padding:0;
    line-height:normal;
    /*overflow: hidden;*/
}

#tabs_container .mootabs_title {
    list-style-image: none;
    list-style-type: none;
    margin: 0px;
    background:url("../images/tab_back_tr.gif") repeat-x bottom;
    line-height:normal;
    padding: 10px 0 0 10px;
    float:left;
    width: 99%;
}

#tabs_container .mootabs_title li {
    float:left;
    margin:0;
    padding:0 0 0 9px;
    display:inline;
    background:url("../images/tab_norm_lft.gif") no-repeat left top;
}

#tabs_container .mootabs_title li.active {
    float:left;
    margin:0;
    padding:0 0 0 9px;
    display:inline;
    background:url("../images/tab_on_lft_dk.gif") no-repeat left top;
}

#tabs_container .mootabs_title li div {
    float:left;
    color:#00b;
    cursor:pointer;
    display:block;
    background:url("../images/tab_norm_rght_dk.gif") no-repeat right top;
    margin:0;
    padding:5px 15px 4px 6px;
}

#tabs_container .mootabs_title li.active div {
    float:left;
    color:#00b;
    cursor:pointer;
    display:block;
    background:url("../images/tab_on_rght_dk.gif") no-repeat right top;
    margin:0;
    padding:5px 15px 5px 6px;
}

#tabs_container .mootabs_panel {
    display: none;
    position: relative;
    width: 100%;
    clear: both;
    background-color:#fff;
    margin:0;
    padding: 0;
}

#tabs_container .mootabs_panel.active {
    background-color: #fff;
    display: block;
}

.panel_content {
    width:100%;
    margin:0;
    border-top:none;
    padding:0;
    border-right:1px #ccc solid;
    border-bottom:1px #ccc solid;
    border-left:1px #02176e solid;
    clear: both;
}

/*#tabs_container .mootabs_title li.over {
    font-weight: bold;
}*/


text:
var mc = require('minecraft-protocol');
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var path = require('path');
var requireIndex = require('requireindex');
var plugins = requireIndex(path.join(__dirname, 'lib', 'plugins'));
var nmcData = require('node-minecraft-data');

module.exports = {
  vec3: require('vec3'),
  createBot: createBot,
  Block: require('./lib/block'),
  Location: require('./lib/location'),
  Biome: require('./lib/biome'),
  Entity: require('./lib/entity'),
  Painting: require('./lib/painting'),
  Item: require('./lib/item'),
  Recipe: require('./lib/recipe'),
  windows: require('./lib/windows'),
  Chest: require('./lib/chest'),
  Furnace: require('./lib/furnace'),
  Dispenser: require('./lib/dispenser'),
  EnchantmentTable: require('./lib/enchantment_table'),
  blocks: nmcData.blocks,
  biomes: nmcData.biomes,
  items: nmcData.items,
  recipes: nmcData.recipes,
  instruments: nmcData.instruments,
  materials: nmcData.materials,
  entities: nmcData.entities,
  data: nmcData
};

function createBot(options) {
  options = options || {};
  options.username = options.username || 'Player';
  var bot = new Bot();
  bot.connect(options);
  return bot;
}

function Bot() {
  EventEmitter.call(this);
  this._client = null;
}
util.inherits(Bot, EventEmitter);

Bot.prototype.connect = function(options) {
  var self = this;
  self._client = mc.createClient(options);
  self.username = self._client.username;
  self._client.on('session', function() {
    self.username = self._client.username;
  });
  self._client.on('connect', function() {
    self.emit('connect');
  });
  self._client.on('error', function(err) {
    self.emit('error', err);
  });
  self._client.on('end', function() {
    self.emit('end');
  });
  for(var pluginName in plugins) {
    plugins[pluginName](self, options);
  }
};

Bot.prototype.end = function() {
  this._client.end();
};


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Query</title>
<meta name="date" content="2015-08-18">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.clearblade.platform.api

Class Query

java.lang.Object

com.clearblade.platform.api.Query

public class Query
extends java.lang.Object

This class consists exclusively of instance methods that operate on ClearBlade Collections and Items.

 ClearBlade Query are objects that can query Cloud platform collections for Items.
 A typical example would be:

                Query query = new Query(collectionId);
                query.equalTo("firstName", "John").greaterThan("age",40);
                query.fetch(new DataCallback(){

Since:

1.0

Author:

Clyde Byrd, Aaron Allsbrook

See Also:

Item,
Query,
ClearBladeException

Constructor Summary

Constructors

Constructor and Description

Query()

Constructs a new Query object for modifying a collection
 A collection id must be set

Query(java.lang.String collectionId)

Constructs a new Query object for modifying a collection

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

void
addChange(java.lang.String name,
         java.lang.Object value)

Adds a change set to the query.

void
ascending(java.lang.String field)

Creates an ascending clause in the query object

void
clearChanges()

Clears the changes currently set in they query.

void
descending(java.lang.String field)

Creates an descending clause in the query object

Query
equalTo(java.lang.String field,
       java.lang.Object value)

Creates an equality clause in the query object

void
fetch(DataCallback callback)

Executes the query built by the Query Class.

Item[]
fetchSync()

java.lang.String
getCollectionId()

java.lang.String
getFetchURLParameter()

Internal only, made public for test and verification.

java.lang.String
getURLParameter()

Internal only, made public for test and verification.

Query
greaterThan(java.lang.String field,
           java.lang.Object value)

Creates an greater than clause in the query object

Query
greaterThanEqualTo(java.lang.String field,
                  java.lang.Object value)

Creates an greater than or equal to clause in the query object

Query
lessThan(java.lang.String field,
        java.lang.Object value)

Creates a less than to clause in the query object

Query
lessThanEqualTo(java.lang.String field,
               java.lang.Object value)

Creates a less than to clause in the query object

Query
notEqual(java.lang.String field,
        java.lang.Object value)

Creates an non equality clause in the query object

void
or(Query orQuery)

void
remove(DataCallback callback)

Removes on all items matching the query criteria within a Collection

Item[]
removeSync()

void
setCollectionId(java.lang.String collectionId)

void
setPageNum(int pageNum)

Sets the page number of the query results to be returned by the server

void
setPageSize(int pageSize)

Sets the desired page size returned by server for the query results

void
update(DataCallback callback)

Call an update on all items matching the query criteria to conform to the changes that have been added via the addChange method

Item[]
updateSync()

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

Query

public Query()

Constructs a new Query object for modifying a collection
 A collection id must be set

Query

public Query(java.lang.String collectionId)

Constructs a new Query object for modifying a collection

Parameters:

collectionId - - The id of the collection to be queried

Method Detail

equalTo

public Query equalTo(java.lang.String field,
                     java.lang.Object value)

Creates an equality clause in the query object

 Query query = new Query(collectionId);
 query.equalTo('name', 'John');
 query.fetch(new DataCallback{
          public void done(QueryResponse resp){
       //your logic here
    }
 });
 //will only match if an item has an attribute 'name' that is equal to 'John'

Parameters:

field - - name of the column to be used for query criteria

value - - the value of the search criteria

Returns:

modified Query object for chaining purposes.

notEqual

public Query notEqual(java.lang.String field,
                      java.lang.Object value)

Creates an non equality clause in the query object

 Query query = new Query(collectionId);
 query.notEqualTo('name', 'John');
 query.fetch(new DataCallback{
          public void done(QueryResponse resp){
       //your logic here
    }
 });
 //will only match if an item has an attribute 'name' that is not equal to 'John'

Parameters:

field - - name of the column to be used for query criteria

value - - the value of the search criteria

Returns:

modified Query object for chaining purposes.

greaterThan

public Query greaterThan(java.lang.String field,
                         java.lang.Object value)

Creates an greater than clause in the query object

 Query query = new Query(collectionId);
 query.greaterThan('age', '18');
 query.fetch(new DataCallback{
          public void done(QueryResponse resp){
       //your logic here
    }
 });

Parameters:

field - - name of the column to be used for query criteria

value - - the value of the search criteria

Returns:

modified Query object for chaining purposes.

greaterThanEqualTo

public Query greaterThanEqualTo(java.lang.String field,
                                java.lang.Object value)

Creates an greater than or equal to clause in the query object

 Query query = new Query(collectionId);
 query.greaterThanEqualTo('age', '18');
 query.fetch(new DataCallback{
          public void done(QueryResponse resp){
       //your logic here
    }
 });

Parameters:

field - - name of the column to be used for query criteria

value - - the value of the search criteria

Returns:

modified Query object for chaining purposes.

lessThan

public Query lessThan(java.lang.String field,
                      java.lang.Object value)

Creates a less than to clause in the query object

 Query query = new Query(collectionId);
 query.lessThan('age', '18');
 query.fetch(new DataCallback{
          public void done(QueryResponse resp){
       //your logic here
    }
 });

Parameters:

field - - name of the column to be used for query criteria

value - - the value of the search criteria

Returns:

modified Query object for chaining purposes.

lessThanEqualTo

public Query lessThanEqualTo(java.lang.String field,
                             java.lang.Object value)

Creates a less than to clause in the query object

 Query query = new Query(collectionId);
 query.lessThanEqualTo('age', '18');
 query.fetch(new DataCallback{
          public void done(QueryResponse resp){
       //your logic here
    }
 });

Parameters:

field - - name of the column to be used for query criteria

value - - the value of the search criteria

Returns:

modified Query object for chaining purposes.

ascending

public void ascending(java.lang.String field)

Creates an ascending clause in the query object

 Query query = new Query(collectionId);
 query.ascending('age');
 query.fetch(new DataCallback{
          public void done(QueryResponse resp){
       //your logic here
    }
 });

Parameters:

field - - name of the column to be used for sorting in ascending manner

descending

public void descending(java.lang.String field)

Creates an descending clause in the query object

 Query query = new Query(collectionId);
 query.descending('age');
 query.fetch(new DataCallback{
          public void done(QueryResponse resp){
       //your logic here
    }
 });

Parameters:

field - - name of the column to be used for sorting in descending manner

or

public void or(Query orQuery)

setPageSize

public void setPageSize(int pageSize)

Sets the desired page size returned by server for the query results

 Query query = new Query(collectionId);
 query.setPageSize(50);
 query.fetch(new DataCallback{
          public void done(QueryResponse resp){
       //your logic here
    }
 });

Parameters:

field - - name of the column to be used for sorting in descending manner

setPageNum

public void setPageNum(int pageNum)

Sets the page number of the query results to be returned by the server

 Query query = new Query(collectionId);
 query.setPageNum(2);
 query.fetch(new DataCallback{
          public void done(QueryResponse resp){
       //your logic here
    }
 });

Parameters:

field - - name of the column to be used for sorting in descending manner

fetch

public void fetch(DataCallback callback)

Executes the query built by the Query Class. Will return a QueryResponse object
 which contains an array of the Items, and pagination information

 Query query = new Query(collectionId);
 query.offset(75);
 query.fetch(new DataCallback{
          public void done(QueryResponse resp){
       //your logic here
    }
          public void error(ClearBladeException exception){
                 //error handling
    }
 });

Parameters:

callback - - a DataCallback to be called upon success/failure of the query.

fetchSync

public Item[] fetchSync()
                 throws ClearBladeException

Throws:

ClearBladeException

getFetchURLParameter

public java.lang.String getFetchURLParameter()

Internal only, made public for test and verification.  Returns the query string parameter necessary to implement the fetch query

Returns:

String

getURLParameter

public java.lang.String getURLParameter()

Internal only, made public for test and verification.  Returns the query string parameter necessary to implement the query

Returns:

String

addChange

public void addChange(java.lang.String name,
                      java.lang.Object value)

Adds a change set to the query.  When update is run all of the changes
 are honored across the matching criteria

Parameters:

name - - the name of the column to be modified

value - - the new value to insert into the column

clearChanges

public void clearChanges()

Clears the changes currently set in they query.  Update will perform no action after this
 is executed.

update

public void update(DataCallback callback)

Call an update on all items matching the query criteria to conform to the changes that have been added via the addChange method

 Query query = new Query(collectionText.getText().toString());
        query.equalTo("name", "John");
        query.addChange("name", "Johan");
        query.update( new DataCallback() {

Parameters:

callback -

updateSync

public Item[] updateSync()
                  throws ClearBladeException

Throws:

ClearBladeException

remove

public void remove(DataCallback callback)

Removes on all items matching the query criteria within a Collection

Query query = new Query(collectionText.getText().toString());
        query.equalTo("name", "John");
        query.remove( new DataCallback() {

Parameters:

callback -

removeSync

public Item[] removeSync()
                  throws ClearBladeException

Throws:

ClearBladeException

getCollectionId

public java.lang.String getCollectionId()

Returns:

the collectionId

setCollectionId

public void setCollectionId(java.lang.String collectionId)

Parameters:

collectionId - the collectionId to set

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
using System.Runtime.CompilerServices;

[assembly: InternalsVisibleTo("Ducode.Wolk.Persistence.Tests")]