repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
resin-io-library/base-images
|
balena-base-images/node/coral-dev/ubuntu/bionic/17.6.0/run/Dockerfile
|
2905
|
# AUTOGENERATED FILE
FROM balenalib/coral-dev-ubuntu:bionic-run
ENV NODE_VERSION 17.6.0
ENV YARN_VERSION 1.22.4
RUN buildDeps='curl libatomic1' \
&& set -x \
&& for key in \
6A010C5166006599AA17F08146C2130DFD2497F5 \
; do \
gpg --keyserver pgp.mit.edu --recv-keys "$key" || \
gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \
gpg --keyserver keyserver.ubuntu.com --recv-keys "$key" ; \
done \
&& apt-get update && apt-get install -y $buildDeps --no-install-recommends \
&& rm -rf /var/lib/apt/lists/* \
&& curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-arm64.tar.gz" \
&& echo "287b1e42aff686563ee80165c14e9246370cd2e9ae4662787493964dffed1da9 node-v$NODE_VERSION-linux-arm64.tar.gz" | sha256sum -c - \
&& tar -xzf "node-v$NODE_VERSION-linux-arm64.tar.gz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-arm64.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \
&& gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& mkdir -p /opt/yarn \
&& tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \
&& rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& npm config set unsafe-perm true -g --unsafe-perm \
&& rm -rf /tmp/*
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \
&& echo "Running test-stack@node" \
&& chmod +x [email protected] \
&& bash [email protected] \
&& rm -rf [email protected]
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Ubuntu bionic \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v17.6.0, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh
|
apache-2.0
|
resin-io-library/base-images
|
balena-base-images/dotnet/odroid-xu4/ubuntu/focal/3.1-aspnet/run/Dockerfile
|
3157
|
# AUTOGENERATED FILE
FROM balenalib/odroid-xu4-ubuntu:focal-run
RUN apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
ca-certificates \
\
# .NET Core dependencies
libc6 \
libgcc1 \
libgssapi-krb5-2 \
libicu66 \
libssl1.1 \
libstdc++6 \
zlib1g \
&& rm -rf /var/lib/apt/lists/*
ENV \
# Configure web servers to bind to port 80 when present
ASPNETCORE_URLS=http://+:80 \
# Enable detection of running in a container
DOTNET_RUNNING_IN_CONTAINER=true
# Install .NET Core
ENV DOTNET_VERSION 3.1.21
RUN curl -SL --output dotnet.tar.gz "https://dotnetcli.blob.core.windows.net/dotnet/Runtime/$DOTNET_VERSION/dotnet-runtime-$DOTNET_VERSION-linux-arm.tar.gz" \
&& dotnet_sha512='9c3fb0f5f860f53ab4d15124c2c23a83412ea916ad6155c0f39f066057dcbb3ca6911ae26daf8a36dbfbc09c17d6565c425fbdf3db9114a28c66944382b71000' \
&& echo "$dotnet_sha512 dotnet.tar.gz" | sha512sum -c - \
&& mkdir -p /usr/share/dotnet \
&& tar -zxf dotnet.tar.gz -C /usr/share/dotnet \
&& rm dotnet.tar.gz \
&& ln -s /usr/share/dotnet/dotnet /usr/bin/dotnet
ENV ASPNETCORE_VERSION 3.1.21
RUN curl -SL --output aspnetcore.tar.gz "https://dotnetcli.blob.core.windows.net/dotnet/aspnetcore/Runtime/$ASPNETCORE_VERSION/aspnetcore-runtime-$ASPNETCORE_VERSION-linux-arm.tar.gz" \
&& aspnetcore_sha512='3f7e1839946c65c437a8b55f1f66b15f8faa729abd19874cb2507c10fb5ae6a572c7d4943141b8a450ee74082c3719d4f146c79f2fabf48716ff28be2720effa' \
&& echo "$aspnetcore_sha512 aspnetcore.tar.gz" | sha512sum -c - \
&& mkdir -p /usr/share/dotnet \
&& tar -zxf aspnetcore.tar.gz -C /usr/share/dotnet ./shared/Microsoft.AspNetCore.App \
&& rm aspnetcore.tar.gz
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/44e597e40f2010cdde15b3ba1e397aea3a5c5271/scripts/assets/tests/[email protected]" \
&& echo "Running test-stack@dotnet" \
&& chmod +x [email protected] \
&& bash [email protected] \
&& rm -rf [email protected]
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Ubuntu focal \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \ndotnet 3.1-aspnet \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh
|
apache-2.0
|
epishkin/scalatest-google-code
|
src/test/scala/org/scalatest/fixture/FixtureFeatureSpecSpec.scala
|
38866
|
/*
* Copyright 2001-2009 Artima, Inc.
*
* 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 org.scalatest.fixture
import org.scalatest._
import events.TestFailed
class FixtureFeatureSpecSpec extends org.scalatest.FunSpec with SharedHelpers {
describe("A FixtureFeatureSpec") {
it("should return the test names in order of registration from testNames") {
val a = new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) {}
scenario("should do that") { fixture =>
}
scenario("should do this") { fixture =>
}
}
expect(List("Scenario: should do that", "Scenario: should do this")) {
a.testNames.iterator.toList
}
val b = new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) {}
}
expect(List[String]()) {
b.testNames.iterator.toList
}
val c = new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) {}
scenario("should do this") { fixture =>
}
scenario("should do that") { fixture =>
}
}
expect(List("Scenario: should do this", "Scenario: should do that")) {
c.testNames.iterator.toList
}
}
it("should throw NotAllowedException if a duplicate scenario name registration is attempted") {
intercept[DuplicateTestNameException] {
new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) {}
scenario("test this") { fixture =>
}
scenario("test this") { fixture =>
}
}
}
intercept[DuplicateTestNameException] {
new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) {}
scenario("test this") { fixture =>
}
ignore("test this") { fixture =>
}
}
}
intercept[DuplicateTestNameException] {
new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) {}
ignore("test this") { fixture =>
}
ignore("test this") { fixture =>
}
}
}
intercept[DuplicateTestNameException] {
new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) {}
ignore("test this") { fixture =>
}
scenario("test this") { fixture =>
}
}
}
}
it("should pass in the fixture to every test method") {
val a = new FixtureFeatureSpec {
type FixtureParam = String
val hello = "Hello, world!"
def withFixture(test: OneArgTest) {
test(hello)
}
scenario("should do this") { fixture =>
assert(fixture === hello)
}
scenario("should do that") { fixture =>
assert(fixture === hello)
}
}
val rep = new EventRecordingReporter
a.run(None, rep, new Stopper {}, Filter(), Map(), None, new Tracker())
assert(!rep.eventsReceived.exists(_.isInstanceOf[TestFailed]))
}
it("should throw NullPointerException if a null test tag is provided") {
// scenario
intercept[NullPointerException] {
new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) {}
scenario("hi", null) { fixture => }
}
}
val caught = intercept[NullPointerException] {
new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) {}
scenario("hi", mytags.SlowAsMolasses, null) { fixture => }
}
}
assert(caught.getMessage === "a test tag was null")
intercept[NullPointerException] {
new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) {}
scenario("hi", mytags.SlowAsMolasses, null, mytags.WeakAsAKitten) { fixture => }
}
}
// ignore
intercept[NullPointerException] {
new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) {}
ignore("hi", null) { fixture => }
}
}
val caught2 = intercept[NullPointerException] {
new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) {}
ignore("hi", mytags.SlowAsMolasses, null) { fixture => }
}
}
assert(caught2.getMessage === "a test tag was null")
intercept[NullPointerException] {
new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) {}
ignore("hi", mytags.SlowAsMolasses, null, mytags.WeakAsAKitten) { fixture => }
}
}
}
it("should return a correct tags map from the tags method") {
val a = new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) {}
ignore("test this") { fixture => }
scenario("test that") { fixture => }
}
expect(Map("Scenario: test this" -> Set("org.scalatest.Ignore"))) {
a.testTags
}
val b = new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) {}
scenario("test this") { fixture => }
ignore("test that") { fixture => }
}
expect(Map("Scenario: test that" -> Set("org.scalatest.Ignore"))) {
b.testTags
}
val c = new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) {}
ignore("test this") { fixture => }
ignore("test that") { fixture => }
}
expect(Map("Scenario: test this" -> Set("org.scalatest.Ignore"), "Scenario: test that" -> Set("org.scalatest.Ignore"))) {
c.testTags
}
val d = new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) {}
scenario("test this", mytags.SlowAsMolasses) { fixture => }
ignore("test that", mytags.SlowAsMolasses) { fixture => }
}
expect(Map("Scenario: test this" -> Set("org.scalatest.SlowAsMolasses"), "Scenario: test that" -> Set("org.scalatest.Ignore", "org.scalatest.SlowAsMolasses"))) {
d.testTags
}
val e = new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) {}
}
expect(Map()) {
e.testTags
}
val f = new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) {}
scenario("test this", mytags.SlowAsMolasses, mytags.WeakAsAKitten) { fixture => }
scenario("test that", mytags.SlowAsMolasses) { fixture => }
}
expect(Map("Scenario: test this" -> Set("org.scalatest.SlowAsMolasses", "org.scalatest.WeakAsAKitten"), "Scenario: test that" -> Set("org.scalatest.SlowAsMolasses"))) {
f.testTags
}
}
class TestWasCalledSuite extends FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) { test("hi") }
var theTestThisCalled = false
var theTestThatCalled = false
scenario("this") { fixture => theTestThisCalled = true }
scenario("that") { fixture => theTestThatCalled = true }
}
it("should execute all tests when run is called with testName None") {
val b = new TestWasCalledSuite
b.run(None, SilentReporter, new Stopper {}, Filter(), Map(), None, new Tracker)
assert(b.theTestThisCalled)
assert(b.theTestThatCalled)
}
it("should execute one test when run is called with a defined testName") {
val a = new TestWasCalledSuite
a.run(Some("Scenario: this"), SilentReporter, new Stopper {}, Filter(), Map(), None, new Tracker)
assert(a.theTestThisCalled)
assert(!a.theTestThatCalled)
}
it("should report as ignored, and not run, tests marked ignored") {
val a = new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) { test("hi") }
var theTestThisCalled = false
var theTestThatCalled = false
scenario("test this") { fixture => theTestThisCalled = true }
scenario("test that") { fixture => theTestThatCalled = true }
}
val repA = new TestIgnoredTrackingReporter
a.run(None, repA, new Stopper {}, Filter(), Map(), None, new Tracker)
assert(!repA.testIgnoredReceived)
assert(a.theTestThisCalled)
assert(a.theTestThatCalled)
val b = new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) { test("hi") }
var theTestThisCalled = false
var theTestThatCalled = false
ignore("test this") { fixture => theTestThisCalled = true }
scenario("test that") { fixture => theTestThatCalled = true }
}
val repB = new TestIgnoredTrackingReporter
b.run(None, repB, new Stopper {}, Filter(), Map(), None, new Tracker)
assert(repB.testIgnoredReceived)
assert(repB.lastEvent.isDefined)
assert(repB.lastEvent.get.testName endsWith "test this")
assert(!b.theTestThisCalled)
assert(b.theTestThatCalled)
val c = new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) { test("hi") }
var theTestThisCalled = false
var theTestThatCalled = false
scenario("test this") { fixture => theTestThisCalled = true }
ignore("test that") { fixture => theTestThatCalled = true }
}
val repC = new TestIgnoredTrackingReporter
c.run(None, repC, new Stopper {}, Filter(), Map(), None, new Tracker)
assert(repC.testIgnoredReceived)
assert(repC.lastEvent.isDefined)
assert(repC.lastEvent.get.testName endsWith "test that", repC.lastEvent.get.testName)
assert(c.theTestThisCalled)
assert(!c.theTestThatCalled)
// The order I want is order of appearance in the file.
// Will try and implement that tomorrow. Subtypes will be able to change the order.
val d = new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) { test("hi") }
var theTestThisCalled = false
var theTestThatCalled = false
ignore("test this") { fixture => theTestThisCalled = true }
ignore("test that") { fixture => theTestThatCalled = true }
}
val repD = new TestIgnoredTrackingReporter
d.run(None, repD, new Stopper {}, Filter(), Map(), None, new Tracker)
assert(repD.testIgnoredReceived)
assert(repD.lastEvent.isDefined)
assert(repD.lastEvent.get.testName endsWith "test that") // last because should be in order of appearance
assert(!d.theTestThisCalled)
assert(!d.theTestThatCalled)
}
it("should ignore a test marked as ignored if run is invoked with that testName") {
// If I provide a specific testName to run, then it should ignore an Ignore on that test
// method and actually invoke it.
val e = new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) { test("hi") }
var theTestThisCalled = false
var theTestThatCalled = false
ignore("test this") { fixture => theTestThisCalled = true }
scenario("test that") { fixture => theTestThatCalled = true }
}
val repE = new TestIgnoredTrackingReporter
e.run(Some("Scenario: test this"), repE, new Stopper {}, Filter(), Map(), None, new Tracker)
assert(repE.testIgnoredReceived)
assert(!e.theTestThisCalled)
assert(!e.theTestThatCalled)
}
it("should run only those tests selected by the tags to include and exclude sets") {
// Nothing is excluded
val a = new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) { test("hi") }
var theTestThisCalled = false
var theTestThatCalled = false
scenario("test this", mytags.SlowAsMolasses) { fixture => theTestThisCalled = true }
scenario("test that") { fixture => theTestThatCalled = true }
}
val repA = new TestIgnoredTrackingReporter
a.run(None, repA, new Stopper {}, Filter(), Map(), None, new Tracker)
assert(!repA.testIgnoredReceived)
assert(a.theTestThisCalled)
assert(a.theTestThatCalled)
// SlowAsMolasses is included, one test should be excluded
val b = new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) { test("hi") }
var theTestThisCalled = false
var theTestThatCalled = false
scenario("test this", mytags.SlowAsMolasses) { fixture => theTestThisCalled = true }
scenario("test that") { fixture => theTestThatCalled = true }
}
val repB = new TestIgnoredTrackingReporter
b.run(None, repB, new Stopper {}, Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set()), Map(), None, new Tracker)
assert(!repB.testIgnoredReceived)
assert(b.theTestThisCalled)
assert(!b.theTestThatCalled)
// SlowAsMolasses is included, and both tests should be included
val c = new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) { test("hi") }
var theTestThisCalled = false
var theTestThatCalled = false
scenario("test this", mytags.SlowAsMolasses) { fixture => theTestThisCalled = true }
scenario("test that", mytags.SlowAsMolasses) { fixture => theTestThatCalled = true }
}
val repC = new TestIgnoredTrackingReporter
c.run(None, repB, new Stopper {}, Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set()), Map(), None, new Tracker)
assert(!repC.testIgnoredReceived)
assert(c.theTestThisCalled)
assert(c.theTestThatCalled)
// SlowAsMolasses is included. both tests should be included but one ignored
val d = new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) { test("hi") }
var theTestThisCalled = false
var theTestThatCalled = false
ignore("test this", mytags.SlowAsMolasses) { fixture => theTestThisCalled = true }
scenario("test that", mytags.SlowAsMolasses) { fixture => theTestThatCalled = true }
}
val repD = new TestIgnoredTrackingReporter
d.run(None, repD, new Stopper {}, Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set("org.scalatest.Ignore")), Map(), None, new Tracker)
assert(repD.testIgnoredReceived)
assert(!d.theTestThisCalled)
assert(d.theTestThatCalled)
// SlowAsMolasses included, FastAsLight excluded
val e = new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) { test("hi") }
var theTestThisCalled = false
var theTestThatCalled = false
var theTestTheOtherCalled = false
scenario("test this", mytags.SlowAsMolasses, mytags.FastAsLight) { fixture => theTestThisCalled = true }
scenario("test that", mytags.SlowAsMolasses) { fixture => theTestThatCalled = true }
scenario("test the other") { fixture => theTestTheOtherCalled = true }
}
val repE = new TestIgnoredTrackingReporter
e.run(None, repE, new Stopper {}, Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set("org.scalatest.FastAsLight")),
Map(), None, new Tracker)
assert(!repE.testIgnoredReceived)
assert(!e.theTestThisCalled)
assert(e.theTestThatCalled)
assert(!e.theTestTheOtherCalled)
// An Ignored test that was both included and excluded should not generate a TestIgnored event
val f = new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) { test("hi") }
var theTestThisCalled = false
var theTestThatCalled = false
var theTestTheOtherCalled = false
ignore("test this", mytags.SlowAsMolasses, mytags.FastAsLight) { fixture => theTestThisCalled = true }
scenario("test that", mytags.SlowAsMolasses) { fixture => theTestThatCalled = true }
scenario("test the other") { fixture => theTestTheOtherCalled = true }
}
val repF = new TestIgnoredTrackingReporter
f.run(None, repF, new Stopper {}, Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set("org.scalatest.FastAsLight")),
Map(), None, new Tracker)
assert(!repF.testIgnoredReceived)
assert(!f.theTestThisCalled)
assert(f.theTestThatCalled)
assert(!f.theTestTheOtherCalled)
// An Ignored test that was not included should not generate a TestIgnored event
val g = new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) { test("hi") }
var theTestThisCalled = false
var theTestThatCalled = false
var theTestTheOtherCalled = false
scenario("test this", mytags.SlowAsMolasses, mytags.FastAsLight) { fixture => theTestThisCalled = true }
scenario("test that", mytags.SlowAsMolasses) { fixture => theTestThatCalled = true }
ignore("test the other") { fixture => theTestTheOtherCalled = true }
}
val repG = new TestIgnoredTrackingReporter
g.run(None, repG, new Stopper {}, Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set("org.scalatest.FastAsLight")),
Map(), None, new Tracker)
assert(!repG.testIgnoredReceived)
assert(!g.theTestThisCalled)
assert(g.theTestThatCalled)
assert(!g.theTestTheOtherCalled)
// No tagsToInclude set, FastAsLight excluded
val h = new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) { test("hi") }
var theTestThisCalled = false
var theTestThatCalled = false
var theTestTheOtherCalled = false
scenario("test this", mytags.SlowAsMolasses, mytags.FastAsLight) { fixture => theTestThisCalled = true }
scenario("test that", mytags.SlowAsMolasses) { fixture => theTestThatCalled = true }
scenario("test the other") { fixture => theTestTheOtherCalled = true }
}
val repH = new TestIgnoredTrackingReporter
h.run(None, repH, new Stopper {}, Filter(None, Set("org.scalatest.FastAsLight")), Map(), None, new Tracker)
assert(!repH.testIgnoredReceived)
assert(!h.theTestThisCalled)
assert(h.theTestThatCalled)
assert(h.theTestTheOtherCalled)
// No tagsToInclude set, SlowAsMolasses excluded
val i = new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) { test("hi") }
var theTestThisCalled = false
var theTestThatCalled = false
var theTestTheOtherCalled = false
scenario("test this", mytags.SlowAsMolasses, mytags.FastAsLight) { fixture => theTestThisCalled = true }
scenario("test that", mytags.SlowAsMolasses) { fixture => theTestThatCalled = true }
scenario("test the other") { fixture => theTestTheOtherCalled = true }
}
val repI = new TestIgnoredTrackingReporter
i.run(None, repI, new Stopper {}, Filter(None, Set("org.scalatest.SlowAsMolasses")), Map(), None, new Tracker)
assert(!repI.testIgnoredReceived)
assert(!i.theTestThisCalled)
assert(!i.theTestThatCalled)
assert(i.theTestTheOtherCalled)
// No tagsToInclude set, SlowAsMolasses excluded, TestIgnored should not be received on excluded ones
val j = new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) { test("hi") }
var theTestThisCalled = false
var theTestThatCalled = false
var theTestTheOtherCalled = false
ignore("test this", mytags.SlowAsMolasses, mytags.FastAsLight) { fixture => theTestThisCalled = true }
ignore("test that", mytags.SlowAsMolasses) { fixture => theTestThatCalled = true }
scenario("test the other") { fixture => theTestTheOtherCalled = true }
}
val repJ = new TestIgnoredTrackingReporter
j.run(None, repJ, new Stopper {}, Filter(None, Set("org.scalatest.SlowAsMolasses")), Map(), None, new Tracker)
assert(!repI.testIgnoredReceived)
assert(!j.theTestThisCalled)
assert(!j.theTestThatCalled)
assert(j.theTestTheOtherCalled)
// Same as previous, except Ignore specifically mentioned in excludes set
val k = new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) { test("hi") }
var theTestThisCalled = false
var theTestThatCalled = false
var theTestTheOtherCalled = false
ignore("test this", mytags.SlowAsMolasses, mytags.FastAsLight) { fixture => theTestThisCalled = true }
ignore("test that", mytags.SlowAsMolasses) { fixture => theTestThatCalled = true }
ignore("test the other") { fixture => theTestTheOtherCalled = true }
}
val repK = new TestIgnoredTrackingReporter
k.run(None, repK, new Stopper {}, Filter(None, Set("org.scalatest.SlowAsMolasses", "org.scalatest.Ignore")), Map(), None, new Tracker)
assert(repK.testIgnoredReceived)
assert(!k.theTestThisCalled)
assert(!k.theTestThatCalled)
assert(!k.theTestTheOtherCalled)
}
it("should return the correct test count from its expectedTestCount method") {
val a = new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) { test("hi") }
scenario("test this") { fixture => }
scenario("test that") { fixture => }
}
assert(a.expectedTestCount(Filter()) === 2)
val b = new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) { test("hi") }
ignore("test this") { fixture => }
scenario("test that") { fixture => }
}
assert(b.expectedTestCount(Filter()) === 1)
val c = new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) { test("hi") }
scenario("test this", mytags.FastAsLight) { fixture => }
scenario("test that") { fixture => }
}
assert(c.expectedTestCount(Filter(Some(Set("org.scalatest.FastAsLight")), Set())) === 1)
assert(c.expectedTestCount(Filter(None, Set("org.scalatest.FastAsLight"))) === 1)
val d = new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) { test("hi") }
scenario("test this", mytags.FastAsLight, mytags.SlowAsMolasses) { fixture => }
scenario("test that", mytags.SlowAsMolasses) { fixture => }
scenario("test the other thing") { fixture => }
}
assert(d.expectedTestCount(Filter(Some(Set("org.scalatest.FastAsLight")), Set())) === 1)
assert(d.expectedTestCount(Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set("org.scalatest.FastAsLight"))) === 1)
assert(d.expectedTestCount(Filter(None, Set("org.scalatest.SlowAsMolasses"))) === 1)
assert(d.expectedTestCount(Filter()) === 3)
val e = new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) { test("hi") }
scenario("test this", mytags.FastAsLight, mytags.SlowAsMolasses) { fixture => }
scenario("test that", mytags.SlowAsMolasses) { fixture => }
ignore("test the other thing") { fixture => }
}
assert(e.expectedTestCount(Filter(Some(Set("org.scalatest.FastAsLight")), Set())) === 1)
assert(e.expectedTestCount(Filter(Some(Set("org.scalatest.SlowAsMolasses")), Set("org.scalatest.FastAsLight"))) === 1)
assert(e.expectedTestCount(Filter(None, Set("org.scalatest.SlowAsMolasses"))) === 0)
assert(e.expectedTestCount(Filter()) === 2)
val f = new Suites(a, b, c, d, e)
assert(f.expectedTestCount(Filter()) === 10)
}
it("should generate a TestPending message when the test body is (pending)") {
val a = new FixtureFeatureSpec {
type FixtureParam = String
val hello = "Hello, world!"
def withFixture(test: OneArgTest) {
test(hello)
}
scenario("should do this") (pending)
scenario("should do that") { fixture =>
assert(fixture === hello)
}
scenario("should do something else") { fixture =>
assert(fixture === hello)
pending
}
}
val rep = new EventRecordingReporter
a.run(None, rep, new Stopper {}, Filter(), Map(), None, new Tracker())
val tp = rep.testPendingEventsReceived
assert(tp.size === 2)
}
it("should generate a test failure if a Throwable, or an Error other than direct Error subtypes " +
"known in JDK 1.5, excluding AssertionError") {
val a = new FixtureFeatureSpec {
type FixtureParam = String
val hello = "Hello, world!"
def withFixture(test: OneArgTest) {
test(hello)
}
scenario("throws AssertionError") { s => throw new AssertionError }
scenario("throws plain old Error") { s => throw new Error }
scenario("throws Throwable") { s => throw new Throwable }
}
val rep = new EventRecordingReporter
a.run(None, rep, new Stopper {}, Filter(), Map(), None, new Tracker())
val tf = rep.testFailedEventsReceived
assert(tf.size === 3)
}
it("should propagate out Errors that are direct subtypes of Error in JDK 1.5, other than " +
"AssertionError, causing Suites and Runs to abort.") {
val a = new FixtureFeatureSpec {
type FixtureParam = String
val hello = "Hello, world!"
def withFixture(test: OneArgTest) {
test(hello)
}
scenario("throws AssertionError") { s => throw new OutOfMemoryError }
}
intercept[OutOfMemoryError] {
a.run(None, SilentReporter, new Stopper {}, Filter(), Map(), None, new Tracker())
}
}
it("should send InfoProvided events with aboutAPendingTest set to true for info " +
"calls made from a test that is pending") {
val a = new FixtureFeatureSpec with GivenWhenThen {
type FixtureParam = String
val hello = "Hello, world!"
def withFixture(test: OneArgTest) {
test(hello)
}
scenario("should do something else") { s =>
given("two integers")
when("one is subracted from the other")
then("the result is the difference between the two numbers")
pending
}
}
val rep = new EventRecordingReporter
a.run(None, rep, new Stopper {}, Filter(), Map(), None, new Tracker())
val ip = rep.infoProvidedEventsReceived
assert(ip.size === 3)
for (event <- ip) {
assert(event.aboutAPendingTest.isDefined && event.aboutAPendingTest.get)
}
}
it("should send InfoProvided events with aboutAPendingTest set to false for info " +
"calls made from a test that is not pending") {
val a = new FixtureFeatureSpec with GivenWhenThen {
type FixtureParam = String
val hello = "Hello, world!"
def withFixture(test: OneArgTest) {
test(hello)
}
scenario("should do something else") { s =>
given("two integers")
when("one is subracted from the other")
then("the result is the difference between the two numbers")
assert(1 + 1 === 2)
}
}
val rep = new EventRecordingReporter
a.run(None, rep, new Stopper {}, Filter(), Map(), None, new Tracker())
val ip = rep.infoProvidedEventsReceived
assert(ip.size === 3)
for (event <- ip) {
assert(event.aboutAPendingTest.isDefined && !event.aboutAPendingTest.get)
}
}
it("should allow both tests that take fixtures and tests that don't") {
val a = new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) {
test("Hello, world!")
}
var takesNoArgsInvoked = false
scenario("take no args") { () =>
takesNoArgsInvoked = true
}
var takesAFixtureInvoked = false
scenario("takes a fixture") { s => takesAFixtureInvoked = true }
}
a.run(None, SilentReporter, new Stopper {}, Filter(), Map(), None, new Tracker())
assert(a.testNames.size === 2, a.testNames)
assert(a.takesNoArgsInvoked)
assert(a.takesAFixtureInvoked)
}
it("should work with test functions whose inferred result type is not Unit") {
val a = new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) {
test("Hello, world!")
}
var takesNoArgsInvoked = false
scenario("should take no args") { () =>
takesNoArgsInvoked = true; true
}
var takesAFixtureInvoked = false
scenario("should take a fixture") { s => takesAFixtureInvoked = true; true }
}
assert(!a.takesNoArgsInvoked)
assert(!a.takesAFixtureInvoked)
a.run(None, SilentReporter, new Stopper {}, Filter(), Map(), None, new Tracker())
assert(a.testNames.size === 2, a.testNames)
assert(a.takesNoArgsInvoked)
assert(a.takesAFixtureInvoked)
}
it("should work with ignored tests whose inferred result type is not Unit") {
val a = new FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) { test("hi") }
var theTestThisCalled = false
var theTestThatCalled = false
ignore("should test this") { () =>
theTestThisCalled = true; "hi"
}
ignore("should test that") { fixture => theTestThatCalled = true; 42 }
}
assert(!a.theTestThisCalled)
assert(!a.theTestThatCalled)
val reporter = new EventRecordingReporter
a.run(None, reporter, new Stopper {}, Filter(), Map(), None, new Tracker)
assert(reporter.testIgnoredEventsReceived.size === 2)
assert(!a.theTestThisCalled)
assert(!a.theTestThatCalled)
}
it("should pass a NoArgTest to withFixture for tests that take no fixture") {
class MySpec extends FixtureFeatureSpec {
type FixtureParam = String
var aNoArgTestWasPassed = false
var aOneArgTestWasPassed = false
override def withFixture(test: NoArgTest) {
aNoArgTestWasPassed = true
}
def withFixture(test: OneArgTest) {
aOneArgTestWasPassed = true
}
scenario("something") { () =>
assert(1 + 1 === 2)
}
}
val s = new MySpec
s.run(None, SilentReporter, new Stopper {}, Filter(), Map(), None, new Tracker())
assert(s.aNoArgTestWasPassed)
assert(!s.aOneArgTestWasPassed)
}
it("should not pass a NoArgTest to withFixture for tests that take a Fixture") {
class MySpec extends FixtureFeatureSpec {
type FixtureParam = String
var aNoArgTestWasPassed = false
var aOneArgTestWasPassed = false
override def withFixture(test: NoArgTest) {
aNoArgTestWasPassed = true
}
def withFixture(test: OneArgTest) {
aOneArgTestWasPassed = true
}
scenario("something") { fixture =>
assert(1 + 1 === 2)
}
}
val s = new MySpec
s.run(None, SilentReporter, new Stopper {}, Filter(), Map(), None, new Tracker())
assert(!s.aNoArgTestWasPassed)
assert(s.aOneArgTestWasPassed)
}
it("should pass a NoArgTest that invokes the no-arg test when the " +
"NoArgTest's no-arg apply method is invoked") {
class MySuite extends FixtureFeatureSpec {
type FixtureParam = String
var theNoArgTestWasInvoked = false
def withFixture(test: OneArgTest) {
// Shouldn't be called, but just in case don't invoke a OneArgTest
}
scenario("something") { () =>
theNoArgTestWasInvoked = true
}
}
val s = new MySuite
s.run(None, SilentReporter, new Stopper {}, Filter(), Map(), None, new Tracker())
assert(s.theNoArgTestWasInvoked)
}
describe("(when a nesting rule has been violated)") {
it("should, if they call a feature from within an scenario clause, result in a TestFailedException when running the test") {
class MySpec extends FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) { test("hi") }
scenario("should blow up") { fixture =>
feature("in the wrong place, at the wrong time") {
}
}
}
val spec = new MySpec
ensureTestFailedEventReceived(spec, "Scenario: should blow up")
}
it("should, if they call a feature with a nested it from within an it clause, result in a TestFailedException when running the test") {
class MySpec extends FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) { test("hi") }
scenario("should blow up") { fixture =>
feature("in the wrong place, at the wrong time") {
scenario("should never run") { fixture =>
assert(1 === 1)
}
}
}
}
val spec = new MySpec
ensureTestFailedEventReceived(spec, "Scenario: should blow up")
}
it("should, if they call a nested it from within an it clause, result in a TestFailedException when running the test") {
class MySpec extends FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) { test("hi") }
scenario("should blow up") { fixture =>
scenario("should never run") { fixture =>
assert(1 === 1)
}
}
}
val spec = new MySpec
ensureTestFailedEventReceived(spec, "Scenario: should blow up")
}
it("should, if they call a nested it with tags from within an it clause, result in a TestFailedException when running the test") {
class MySpec extends FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) { test("hi") }
scenario("should blow up") { fixture =>
scenario("should never run", mytags.SlowAsMolasses) { fixture =>
assert(1 === 1)
}
}
}
val spec = new MySpec
ensureTestFailedEventReceived(spec, "Scenario: should blow up")
}
it("should, if they call a feature with a nested ignore from within an it clause, result in a TestFailedException when running the test") {
class MySpec extends FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) { test("hi") }
scenario("should blow up") { fixture =>
feature("in the wrong place, at the wrong time") {
ignore("should never run") { fixture =>
assert(1 === 1)
}
}
}
}
val spec = new MySpec
ensureTestFailedEventReceived(spec, "Scenario: should blow up")
}
it("should, if they call a nested ignore from within an it clause, result in a TestFailedException when running the test") {
class MySpec extends FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) { test("hi") }
scenario("should blow up") { fixture =>
ignore("should never run") { fixture =>
assert(1 === 1)
}
}
}
val spec = new MySpec
ensureTestFailedEventReceived(spec, "Scenario: should blow up")
}
it("should, if they call a nested ignore with tags from within an it clause, result in a TestFailedException when running the test") {
class MySpec extends FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) { test("hi") }
scenario("should blow up") { fixture =>
ignore("should never run", mytags.SlowAsMolasses) { fixture =>
assert(1 === 1)
}
}
}
val spec = new MySpec
ensureTestFailedEventReceived(spec, "Scenario: should blow up")
}
it("should, if they call a nested feature from within a feature clause, result in a SuiteAborted event when constructing the FeatureSpec") {
class MySpec extends FixtureFeatureSpec {
type FixtureParam = String
def withFixture(test: OneArgTest) { test("hi") }
feature("should blow up") {
feature("should never run") {
}
}
}
val caught =
intercept[NotAllowedException] {
new MySpec
}
assert(caught.getMessage === "Feature clauses cannot be nested.")
}
}
}
it("should pass the correct test name in the OneArgTest passed to withFixture") {
val a = new FixtureFeatureSpec {
type FixtureParam = String
var correctTestNameWasPassed = false
def withFixture(test: OneArgTest) {
correctTestNameWasPassed = test.name == "Scenario: should do something"
test("hi")
}
scenario("should do something") { fixture => }
}
a.run(None, SilentReporter, new Stopper {}, Filter(), Map(), None, new Tracker())
assert(a.correctTestNameWasPassed)
}
it("should pass the correct config map in the OneArgTest passed to withFixture") {
val a = new FixtureFeatureSpec {
type FixtureParam = String
var correctConfigMapWasPassed = false
def withFixture(test: OneArgTest) {
correctConfigMapWasPassed = (test.configMap == Map("hi" -> 7))
test("hi")
}
scenario("should do something") { fixture => }
}
a.run(None, SilentReporter, new Stopper {}, Filter(), Map("hi" -> 7), None, new Tracker())
assert(a.correctConfigMapWasPassed)
}
}
|
apache-2.0
|
phenoxim/nova
|
nova/tests/functional/compute/test_instance_list.py
|
23474
|
# 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.
import datetime
from nova.compute import instance_list
from nova import context
from nova import db
from nova import exception
from nova import objects
from nova import test
from nova.tests import uuidsentinel as uuids
class InstanceListTestCase(test.TestCase):
NUMBER_OF_CELLS = 3
def setUp(self):
super(InstanceListTestCase, self).setUp()
self.context = context.RequestContext('fake', 'fake')
self.num_instances = 3
self.instances = []
start = datetime.datetime(1985, 10, 25, 1, 21, 0)
dt = start
spread = datetime.timedelta(minutes=10)
self.cells = objects.CellMappingList.get_all(self.context)
# Create three instances in each of the real cells. Leave the
# first cell empty to make sure we don't break with an empty
# one.
for cell in self.cells[1:]:
for i in range(0, self.num_instances):
with context.target_cell(self.context, cell) as cctx:
inst = objects.Instance(
context=cctx,
project_id=self.context.project_id,
user_id=self.context.user_id,
created_at=start,
launched_at=dt,
instance_type_id=i,
hostname='%s-inst%i' % (cell.name, i))
inst.create()
if i % 2 == 0:
# Make some faults for this instance
for n in range(0, i + 1):
msg = 'fault%i-%s' % (n, inst.hostname)
f = objects.InstanceFault(context=cctx,
instance_uuid=inst.uuid,
code=i,
message=msg,
details='fake',
host='fakehost')
f.create()
self.instances.append(inst)
im = objects.InstanceMapping(context=self.context,
project_id=inst.project_id,
user_id=inst.user_id,
instance_uuid=inst.uuid,
cell_mapping=cell)
im.create()
dt += spread
def test_get_sorted(self):
filters = {}
limit = None
marker = None
columns = []
sort_keys = ['uuid']
sort_dirs = ['asc']
insts = instance_list.get_instances_sorted(self.context, filters,
limit, marker, columns,
sort_keys, sort_dirs)
uuids = [inst['uuid'] for inst in insts]
self.assertEqual(sorted(uuids), uuids)
self.assertEqual(len(self.instances), len(uuids))
def test_get_sorted_descending(self):
filters = {}
limit = None
marker = None
columns = []
sort_keys = ['uuid']
sort_dirs = ['desc']
insts = instance_list.get_instances_sorted(self.context, filters,
limit, marker, columns,
sort_keys, sort_dirs)
uuids = [inst['uuid'] for inst in insts]
self.assertEqual(list(reversed(sorted(uuids))), uuids)
self.assertEqual(len(self.instances), len(uuids))
def test_get_sorted_with_filter(self):
filters = {'instance_type_id': 1}
limit = None
marker = None
columns = []
sort_keys = ['uuid']
sort_dirs = ['asc']
insts = instance_list.get_instances_sorted(self.context, filters,
limit, marker, columns,
sort_keys, sort_dirs)
uuids = [inst['uuid'] for inst in insts]
expected = [inst['uuid'] for inst in self.instances
if inst['instance_type_id'] == 1]
self.assertEqual(list(sorted(expected)), uuids)
def test_get_sorted_by_defaults(self):
filters = {}
limit = None
marker = None
columns = []
sort_keys = None
sort_dirs = None
insts = instance_list.get_instances_sorted(self.context, filters,
limit, marker, columns,
sort_keys, sort_dirs)
uuids = set([inst['uuid'] for inst in insts])
expected = set([inst['uuid'] for inst in self.instances])
self.assertEqual(expected, uuids)
def test_get_sorted_with_limit(self):
insts = instance_list.get_instances_sorted(self.context, {},
5, None,
[], ['uuid'], ['asc'])
uuids = [inst['uuid'] for inst in insts]
had_uuids = [inst.uuid for inst in self.instances]
self.assertEqual(sorted(had_uuids)[:5], uuids)
self.assertEqual(5, len(uuids))
def test_get_sorted_with_large_limit(self):
insts = instance_list.get_instances_sorted(self.context, {},
5000, None,
[], ['uuid'], ['asc'])
uuids = [inst['uuid'] for inst in insts]
self.assertEqual(sorted(uuids), uuids)
self.assertEqual(len(self.instances), len(uuids))
def _test_get_sorted_with_limit_marker(self, sort_by, pages=2, pagesize=2,
sort_dir='asc'):
"""Get multiple pages by a sort key and validate the results.
This requests $pages of $pagesize, followed by a final page with
no limit, and a final-final page which should be empty. It validates
that we got a consistent set of results no patter where the page
boundary is, that we got all the results after the unlimited query,
and that the final page comes back empty when we use the last
instance as a marker.
"""
insts = []
page = 0
while True:
if page >= pages:
# We've requested the specified number of limited (by pagesize)
# pages, so request a penultimate page with no limit which
# should always finish out the result.
limit = None
else:
# Request a limited-size page for the first $pages pages.
limit = pagesize
if insts:
# If we're not on the first page, use the last instance we
# received as the marker
marker = insts[-1]['uuid']
else:
# No marker for the first page
marker = None
batch = list(
instance_list.get_instances_sorted(self.context, {},
limit, marker,
[], [sort_by], [sort_dir]))
if not batch:
# This should only happen when we've pulled the last empty
# page because we used the marker of the last instance. If
# we end up with a non-deterministic ordering, we'd loop
# forever.
break
insts.extend(batch)
page += 1
if page > len(self.instances) * 2:
# Do this sanity check in case we introduce (or find) another
# repeating page bug like #1721791. Without this we loop
# until timeout, which is less obvious.
raise Exception('Infinite paging loop')
# We should have requested exactly (or one more unlimited) pages
self.assertIn(page, (pages, pages + 1))
# Make sure the full set matches what we know to be true
found = [x[sort_by] for x in insts]
had = [x[sort_by] for x in self.instances]
if sort_by in ('launched_at', 'created_at'):
# We're comparing objects and database entries, so we need to
# squash the tzinfo of the object ones so we can compare
had = [x.replace(tzinfo=None) for x in had]
self.assertEqual(len(had), len(found))
if sort_dir == 'asc':
self.assertEqual(sorted(had), found)
else:
self.assertEqual(list(reversed(sorted(had))), found)
def test_get_sorted_with_limit_marker_stable(self):
"""Test sorted by hostname.
This will be a stable sort that won't change on each run.
"""
self._test_get_sorted_with_limit_marker(sort_by='hostname')
def test_get_sorted_with_limit_marker_stable_reverse(self):
"""Test sorted by hostname.
This will be a stable sort that won't change on each run.
"""
self._test_get_sorted_with_limit_marker(sort_by='hostname',
sort_dir='desc')
def test_get_sorted_with_limit_marker_stable_different_pages(self):
"""Test sorted by hostname with different page sizes.
Just do the above with page seams in different places.
"""
self._test_get_sorted_with_limit_marker(sort_by='hostname',
pages=3, pagesize=1)
def test_get_sorted_with_limit_marker_stable_different_pages_reverse(self):
"""Test sorted by hostname with different page sizes.
Just do the above with page seams in different places.
"""
self._test_get_sorted_with_limit_marker(sort_by='hostname',
pages=3, pagesize=1,
sort_dir='desc')
def test_get_sorted_with_limit_marker_random(self):
"""Test sorted by uuid.
This will not be stable and the actual ordering will depend on
uuid generation and thus be different on each run. Do this in
addition to the stable sort above to keep us honest.
"""
self._test_get_sorted_with_limit_marker(sort_by='uuid')
def test_get_sorted_with_limit_marker_random_different_pages(self):
"""Test sorted by uuid with different page sizes.
Just do the above with page seams in different places.
"""
self._test_get_sorted_with_limit_marker(sort_by='uuid',
pages=3, pagesize=2)
def test_get_sorted_with_limit_marker_datetime(self):
"""Test sorted by launched_at.
This tests that we can do all of this, but with datetime
fields.
"""
self._test_get_sorted_with_limit_marker(sort_by='launched_at')
def test_get_sorted_with_limit_marker_datetime_same(self):
"""Test sorted by created_at.
This tests that we can do all of this, but with datetime
fields that are identical.
"""
self._test_get_sorted_with_limit_marker(sort_by='created_at')
def test_get_sorted_with_deleted_marker(self):
marker = self.instances[1]['uuid']
before = list(
instance_list.get_instances_sorted(self.context, {},
None, marker,
[], None, None))
db.instance_destroy(self.context, marker)
after = list(
instance_list.get_instances_sorted(self.context, {},
None, marker,
[], None, None))
self.assertEqual(before, after)
def test_get_sorted_with_invalid_marker(self):
self.assertRaises(exception.MarkerNotFound,
list, instance_list.get_instances_sorted(
self.context, {}, None, 'not-a-marker',
[], None, None))
def test_get_sorted_with_purged_instance(self):
"""Test that we handle a mapped but purged instance."""
im = objects.InstanceMapping(self.context,
instance_uuid=uuids.missing,
project_id=self.context.project_id,
user_id=self.context.user_id,
cell=self.cells[0])
im.create()
self.assertRaises(exception.MarkerNotFound,
list, instance_list.get_instances_sorted(
self.context, {}, None, uuids.missing,
[], None, None))
def _test_get_paginated_with_filter(self, filters):
found_uuids = []
marker = None
while True:
# Query for those instances, sorted by a different key in
# pages of one until we've consumed them all
batch = list(
instance_list.get_instances_sorted(self.context,
filters,
1, marker, [],
['hostname'],
['asc']))
if not batch:
break
found_uuids.extend([x['uuid'] for x in batch])
marker = found_uuids[-1]
return found_uuids
def test_get_paginated_with_uuid_filter(self):
"""Test getting pages with uuid filters.
This runs through the results of a uuid-filtered query in pages of
length one to ensure that we land on markers that are filtered out
of the query and are not accidentally returned.
"""
# Pick a set of the instances by uuid, when sorted by uuid
all_uuids = [x['uuid'] for x in self.instances]
filters = {'uuid': sorted(all_uuids)[:7]}
found_uuids = self._test_get_paginated_with_filter(filters)
# Make sure we found all (and only) the instances we asked for
self.assertEqual(set(found_uuids), set(filters['uuid']))
self.assertEqual(7, len(found_uuids))
def test_get_paginated_with_other_filter(self):
"""Test getting pages with another filter.
This runs through the results of a filtered query in pages of
length one to ensure we land on markers that are filtered out
of the query and are not accidentally returned.
"""
expected = [inst['uuid'] for inst in self.instances
if inst['instance_type_id'] == 1]
filters = {'instance_type_id': 1}
found_uuids = self._test_get_paginated_with_filter(filters)
self.assertEqual(set(expected), set(found_uuids))
def test_get_paginated_with_uuid_and_other_filter(self):
"""Test getting pages with a uuid and other type of filter.
We do this to make sure that we still find (but exclude) the
marker even if one of the other filters would have included
it.
"""
# Pick a set of the instances by uuid, when sorted by uuid
all_uuids = [x['uuid'] for x in self.instances]
filters = {'uuid': sorted(all_uuids)[:7],
'user_id': 'fake'}
found_uuids = self._test_get_paginated_with_filter(filters)
# Make sure we found all (and only) the instances we asked for
self.assertEqual(set(found_uuids), set(filters['uuid']))
self.assertEqual(7, len(found_uuids))
def test_get_sorted_with_faults(self):
"""Make sure we get faults when we ask for them."""
insts = list(
instance_list.get_instances_sorted(self.context, {},
None, None,
['fault'],
['hostname'], ['asc']))
# Two of the instances in each cell have faults (0th and 2nd)
expected_faults = self.NUMBER_OF_CELLS * 2
expected_no_fault = len(self.instances) - expected_faults
faults = [inst['fault'] for inst in insts]
self.assertEqual(expected_no_fault, faults.count(None))
def test_get_sorted_paginated_with_faults(self):
"""Get pages of one with faults.
Do this specifically so we make sure we land on faulted marker
instances to ensure we don't omit theirs.
"""
insts = []
while True:
if insts:
marker = insts[-1]['uuid']
else:
marker = None
batch = list(
instance_list.get_instances_sorted(self.context, {},
1, marker,
['fault'],
['hostname'], ['asc']))
if not batch:
break
insts.extend(batch)
self.assertEqual(len(self.instances), len(insts))
# Two of the instances in each cell have faults (0th and 2nd)
expected_faults = self.NUMBER_OF_CELLS * 2
expected_no_fault = len(self.instances) - expected_faults
faults = [inst['fault'] for inst in insts]
self.assertEqual(expected_no_fault, faults.count(None))
def test_instance_list_minimal_cells(self):
"""Get a list of instances with a subset of cell mappings."""
last_cell = self.cells[-1]
with context.target_cell(self.context, last_cell) as cctxt:
last_cell_instances = db.instance_get_all(cctxt)
last_cell_uuids = [inst['uuid'] for inst in last_cell_instances]
instances = list(
instance_list.get_instances_sorted(self.context, {},
None, None, [],
['uuid'], ['asc'],
cell_mappings=self.cells[:-1]))
found_uuids = [inst['hostname'] for inst in instances]
had_uuids = [inst['hostname'] for inst in self.instances
if inst['uuid'] not in last_cell_uuids]
self.assertEqual(sorted(had_uuids), sorted(found_uuids))
class TestInstanceListObjects(test.TestCase):
def setUp(self):
super(TestInstanceListObjects, self).setUp()
self.context = context.RequestContext('fake', 'fake')
self.num_instances = 3
self.instances = []
start = datetime.datetime(1985, 10, 25, 1, 21, 0)
dt = start
spread = datetime.timedelta(minutes=10)
cells = objects.CellMappingList.get_all(self.context)
# Create three instances in each of the real cells. Leave the
# first cell empty to make sure we don't break with an empty
# one
for cell in cells[1:]:
for i in range(0, self.num_instances):
with context.target_cell(self.context, cell) as cctx:
inst = objects.Instance(
context=cctx,
project_id=self.context.project_id,
user_id=self.context.user_id,
created_at=start,
launched_at=dt,
instance_type_id=i,
hostname='%s-inst%i' % (cell.name, i))
inst.create()
if i % 2 == 0:
# Make some faults for this instance
for n in range(0, i + 1):
msg = 'fault%i-%s' % (n, inst.hostname)
f = objects.InstanceFault(context=cctx,
instance_uuid=inst.uuid,
code=i,
message=msg,
details='fake',
host='fakehost')
f.create()
self.instances.append(inst)
im = objects.InstanceMapping(context=self.context,
project_id=inst.project_id,
user_id=inst.user_id,
instance_uuid=inst.uuid,
cell_mapping=cell)
im.create()
dt += spread
def test_get_instance_objects_sorted(self):
filters = {}
limit = None
marker = None
expected_attrs = []
sort_keys = ['uuid']
sort_dirs = ['asc']
insts = instance_list.get_instance_objects_sorted(
self.context, filters, limit, marker, expected_attrs,
sort_keys, sort_dirs)
found_uuids = [x.uuid for x in insts]
had_uuids = sorted([x['uuid'] for x in self.instances])
self.assertEqual(had_uuids, found_uuids)
# Make sure none of the instances have fault set
self.assertEqual(0, len([inst for inst in insts
if 'fault' in inst]))
def test_get_instance_objects_sorted_with_fault(self):
filters = {}
limit = None
marker = None
expected_attrs = ['fault']
sort_keys = ['uuid']
sort_dirs = ['asc']
insts = instance_list.get_instance_objects_sorted(
self.context, filters, limit, marker, expected_attrs,
sort_keys, sort_dirs)
found_uuids = [x.uuid for x in insts]
had_uuids = sorted([x['uuid'] for x in self.instances])
self.assertEqual(had_uuids, found_uuids)
# They should all have fault set, but only some have
# actual faults
self.assertEqual(2, len([inst for inst in insts
if inst.fault]))
def test_get_instance_objects_sorted_paged(self):
"""Query a full first page and ensure an empty second one.
This uses created_at which is enforced to be the same across
each instance by setUp(). This will help make sure we still
have a stable ordering, even when we only claim to care about
created_at.
"""
instp1 = instance_list.get_instance_objects_sorted(
self.context, {}, None, None, [],
['created_at'], ['asc'])
self.assertEqual(len(self.instances), len(instp1))
instp2 = instance_list.get_instance_objects_sorted(
self.context, {}, None, instp1[-1]['uuid'], [],
['created_at'], ['asc'])
self.assertEqual(0, len(instp2))
|
apache-2.0
|
jonathanqbo/jpa
|
src/main/java/bq/jpa/demo/lifecycle/domain/ContractEmployee.java
|
2171
|
/*
Copyright (c) 2014 (Jonathan Q. Bo)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package bq.jpa.demo.lifecycle.domain;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.PostPersist;
import javax.persistence.PrePersist;
/**
* <b> </b>
*
* <p> </p>
*
* @author Jonathan Q. Bo ([email protected])
*
* Created at Feb 10, 2014 9:18:29 PM
*
*/
@Entity(name="jpa_lifecycle_contract")
@DiscriminatorValue("contract")
@EntityListeners(ContractEmployeeListener.class)
public class ContractEmployee extends Employee{
private int dailyRate;
private int term;
@PrePersist
public void prePersit(){
System.out.println(ContractEmployee.class.getName() + " prePersist");
}
@PostPersist
public void postPersist(){
System.out.println(ContractEmployee.class.getName() + " postPersist");
}
public int getDailyRate() {
return dailyRate;
}
public void setDailyRate(int dailyRate) {
this.dailyRate = dailyRate;
}
public int getTerm() {
return term;
}
public void setTerm(int term) {
this.term = term;
}
}
|
apache-2.0
|
simon-whitehead/go-debug
|
utils.go
|
393
|
package godebug
import (
"regexp"
"strconv"
"strings"
)
func getFileDetails(stack string) (string, int) { // file name, line that called godebug.Break(), and a "preview line" to begin from
re, _ := regexp.Compile(`(?m)^(.*?)(:)(\d+)`)
res := re.FindAllStringSubmatch(stack, -1)
fn := strings.Trim(res[1][1], " \r\n\t")
breakLine, _ := strconv.Atoi(res[1][3])
return fn, breakLine
}
|
apache-2.0
|
beav/netty-ant
|
doc/xref/org/jboss/netty/handler/timeout/IdleStateHandler.html
|
60775
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de_DE" lang="de_DE">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>IdleStateHandler xref</title>
<link type="text/css" rel="stylesheet" href="../../../../../stylesheet.css" />
</head>
<body>
<div id="overview"><a href="../../../../../../api/org/jboss/netty/handler/timeout/IdleStateHandler.html">View Javadoc</a></div><pre>
<a class="jxr_linenumber" name="1" href="#1">1</a> <em class="jxr_comment">/*</em>
<a class="jxr_linenumber" name="2" href="#2">2</a> <em class="jxr_comment"> * Copyright 2011 The Netty Project</em>
<a class="jxr_linenumber" name="3" href="#3">3</a> <em class="jxr_comment"> *</em>
<a class="jxr_linenumber" name="4" href="#4">4</a> <em class="jxr_comment"> * The Netty Project licenses this file to you under the Apache License,</em>
<a class="jxr_linenumber" name="5" href="#5">5</a> <em class="jxr_comment"> * version 2.0 (the "License"); you may not use this file except in compliance</em>
<a class="jxr_linenumber" name="6" href="#6">6</a> <em class="jxr_comment"> * with the License. You may obtain a copy of the License at:</em>
<a class="jxr_linenumber" name="7" href="#7">7</a> <em class="jxr_comment"> *</em>
<a class="jxr_linenumber" name="8" href="#8">8</a> <em class="jxr_comment"> * <a href="http://www.apache.org/licenses/LICENSE-2.0" target="alexandria_uri">http://www.apache.org/licenses/LICENSE-2.0</a></em>
<a class="jxr_linenumber" name="9" href="#9">9</a> <em class="jxr_comment"> *</em>
<a class="jxr_linenumber" name="10" href="#10">10</a> <em class="jxr_comment"> * Unless required by applicable law or agreed to in writing, software</em>
<a class="jxr_linenumber" name="11" href="#11">11</a> <em class="jxr_comment"> * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT</em>
<a class="jxr_linenumber" name="12" href="#12">12</a> <em class="jxr_comment"> * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the</em>
<a class="jxr_linenumber" name="13" href="#13">13</a> <em class="jxr_comment"> * License for the specific language governing permissions and limitations</em>
<a class="jxr_linenumber" name="14" href="#14">14</a> <em class="jxr_comment"> * under the License.</em>
<a class="jxr_linenumber" name="15" href="#15">15</a> <em class="jxr_comment"> */</em>
<a class="jxr_linenumber" name="16" href="#16">16</a> <strong class="jxr_keyword">package</strong> org.jboss.netty.handler.timeout;
<a class="jxr_linenumber" name="17" href="#17">17</a>
<a class="jxr_linenumber" name="18" href="#18">18</a> <strong class="jxr_keyword">import</strong> <strong class="jxr_keyword">static</strong> org.jboss.netty.channel.Channels.*;
<a class="jxr_linenumber" name="19" href="#19">19</a>
<a class="jxr_linenumber" name="20" href="#20">20</a> <strong class="jxr_keyword">import</strong> java.util.concurrent.TimeUnit;
<a class="jxr_linenumber" name="21" href="#21">21</a>
<a class="jxr_linenumber" name="22" href="#22">22</a> <strong class="jxr_keyword">import</strong> org.jboss.netty.bootstrap.ServerBootstrap;
<a class="jxr_linenumber" name="23" href="#23">23</a> <strong class="jxr_keyword">import</strong> org.jboss.netty.channel.Channel;
<a class="jxr_linenumber" name="24" href="#24">24</a> <strong class="jxr_keyword">import</strong> org.jboss.netty.channel.ChannelHandler;
<a class="jxr_linenumber" name="25" href="#25">25</a> <strong class="jxr_keyword">import</strong> org.jboss.netty.channel.ChannelHandler.Sharable;
<a class="jxr_linenumber" name="26" href="#26">26</a> <strong class="jxr_keyword">import</strong> org.jboss.netty.channel.ChannelHandlerContext;
<a class="jxr_linenumber" name="27" href="#27">27</a> <strong class="jxr_keyword">import</strong> org.jboss.netty.channel.ChannelPipeline;
<a class="jxr_linenumber" name="28" href="#28">28</a> <strong class="jxr_keyword">import</strong> org.jboss.netty.channel.ChannelPipelineFactory;
<a class="jxr_linenumber" name="29" href="#29">29</a> <strong class="jxr_keyword">import</strong> org.jboss.netty.channel.ChannelStateEvent;
<a class="jxr_linenumber" name="30" href="#30">30</a> <strong class="jxr_keyword">import</strong> org.jboss.netty.channel.Channels;
<a class="jxr_linenumber" name="31" href="#31">31</a> <strong class="jxr_keyword">import</strong> org.jboss.netty.channel.LifeCycleAwareChannelHandler;
<a class="jxr_linenumber" name="32" href="#32">32</a> <strong class="jxr_keyword">import</strong> org.jboss.netty.channel.MessageEvent;
<a class="jxr_linenumber" name="33" href="#33">33</a> <strong class="jxr_keyword">import</strong> org.jboss.netty.channel.SimpleChannelUpstreamHandler;
<a class="jxr_linenumber" name="34" href="#34">34</a> <strong class="jxr_keyword">import</strong> org.jboss.netty.channel.WriteCompletionEvent;
<a class="jxr_linenumber" name="35" href="#35">35</a> <strong class="jxr_keyword">import</strong> org.jboss.netty.util.ExternalResourceReleasable;
<a class="jxr_linenumber" name="36" href="#36">36</a> <strong class="jxr_keyword">import</strong> org.jboss.netty.util.HashedWheelTimer;
<a class="jxr_linenumber" name="37" href="#37">37</a> <strong class="jxr_keyword">import</strong> org.jboss.netty.util.Timeout;
<a class="jxr_linenumber" name="38" href="#38">38</a> <strong class="jxr_keyword">import</strong> org.jboss.netty.util.Timer;
<a class="jxr_linenumber" name="39" href="#39">39</a> <strong class="jxr_keyword">import</strong> org.jboss.netty.util.TimerTask;
<a class="jxr_linenumber" name="40" href="#40">40</a>
<a class="jxr_linenumber" name="41" href="#41">41</a> <em class="jxr_javadoccomment">/**</em>
<a class="jxr_linenumber" name="42" href="#42">42</a> <em class="jxr_javadoccomment"> * Triggers an {@link IdleStateEvent} when a {@link Channel} has not performed</em>
<a class="jxr_linenumber" name="43" href="#43">43</a> <em class="jxr_javadoccomment"> * read, write, or both operation for a while.</em>
<a class="jxr_linenumber" name="44" href="#44">44</a> <em class="jxr_javadoccomment"> *</em>
<a class="jxr_linenumber" name="45" href="#45">45</a> <em class="jxr_javadoccomment"> * <h3>Supported idle states</h3></em>
<a class="jxr_linenumber" name="46" href="#46">46</a> <em class="jxr_javadoccomment"> * <table border="1"></em>
<a class="jxr_linenumber" name="47" href="#47">47</a> <em class="jxr_javadoccomment"> * <tr></em>
<a class="jxr_linenumber" name="48" href="#48">48</a> <em class="jxr_javadoccomment"> * <th>Property</th><th>Meaning</th></em>
<a class="jxr_linenumber" name="49" href="#49">49</a> <em class="jxr_javadoccomment"> * </tr></em>
<a class="jxr_linenumber" name="50" href="#50">50</a> <em class="jxr_javadoccomment"> * <tr></em>
<a class="jxr_linenumber" name="51" href="#51">51</a> <em class="jxr_javadoccomment"> * <td>{@code readerIdleTime}</td></em>
<a class="jxr_linenumber" name="52" href="#52">52</a> <em class="jxr_javadoccomment"> * <td>an {@link IdleStateEvent} whose state is {@link IdleState#READER_IDLE}</em>
<a class="jxr_linenumber" name="53" href="#53">53</a> <em class="jxr_javadoccomment"> * will be triggered when no read was performed for the specified period of</em>
<a class="jxr_linenumber" name="54" href="#54">54</a> <em class="jxr_javadoccomment"> * time. Specify {@code 0} to disable.</td></em>
<a class="jxr_linenumber" name="55" href="#55">55</a> <em class="jxr_javadoccomment"> * </tr></em>
<a class="jxr_linenumber" name="56" href="#56">56</a> <em class="jxr_javadoccomment"> * <tr></em>
<a class="jxr_linenumber" name="57" href="#57">57</a> <em class="jxr_javadoccomment"> * <td>{@code writerIdleTime}</td></em>
<a class="jxr_linenumber" name="58" href="#58">58</a> <em class="jxr_javadoccomment"> * <td>an {@link IdleStateEvent} whose state is {@link IdleState#WRITER_IDLE}</em>
<a class="jxr_linenumber" name="59" href="#59">59</a> <em class="jxr_javadoccomment"> * will be triggered when no write was performed for the specified period of</em>
<a class="jxr_linenumber" name="60" href="#60">60</a> <em class="jxr_javadoccomment"> * time. Specify {@code 0} to disable.</td></em>
<a class="jxr_linenumber" name="61" href="#61">61</a> <em class="jxr_javadoccomment"> * </tr></em>
<a class="jxr_linenumber" name="62" href="#62">62</a> <em class="jxr_javadoccomment"> * <tr></em>
<a class="jxr_linenumber" name="63" href="#63">63</a> <em class="jxr_javadoccomment"> * <td>{@code allIdleTime}</td></em>
<a class="jxr_linenumber" name="64" href="#64">64</a> <em class="jxr_javadoccomment"> * <td>an {@link IdleStateEvent} whose state is {@link IdleState#ALL_IDLE}</em>
<a class="jxr_linenumber" name="65" href="#65">65</a> <em class="jxr_javadoccomment"> * will be triggered when neither read nor write was performed for the</em>
<a class="jxr_linenumber" name="66" href="#66">66</a> <em class="jxr_javadoccomment"> * specified period of time. Specify {@code 0} to disable.</td></em>
<a class="jxr_linenumber" name="67" href="#67">67</a> <em class="jxr_javadoccomment"> * </tr></em>
<a class="jxr_linenumber" name="68" href="#68">68</a> <em class="jxr_javadoccomment"> * </table></em>
<a class="jxr_linenumber" name="69" href="#69">69</a> <em class="jxr_javadoccomment"> *</em>
<a class="jxr_linenumber" name="70" href="#70">70</a> <em class="jxr_javadoccomment"> * <pre></em>
<a class="jxr_linenumber" name="71" href="#71">71</a> <em class="jxr_javadoccomment"> * // An example that sends a ping message when there is no outbound traffic</em>
<a class="jxr_linenumber" name="72" href="#72">72</a> <em class="jxr_javadoccomment"> * // for 30 seconds. The connection is closed when there is no inbound traffic</em>
<a class="jxr_linenumber" name="73" href="#73">73</a> <em class="jxr_javadoccomment"> * // for 60 seconds.</em>
<a class="jxr_linenumber" name="74" href="#74">74</a> <em class="jxr_javadoccomment"> *</em>
<a class="jxr_linenumber" name="75" href="#75">75</a> <em class="jxr_javadoccomment"> * public class MyPipelineFactory implements {@link ChannelPipelineFactory} {</em>
<a class="jxr_linenumber" name="76" href="#76">76</a> <em class="jxr_javadoccomment"> *</em>
<a class="jxr_linenumber" name="77" href="#77">77</a> <em class="jxr_javadoccomment"> * private final {@link Timer} timer;</em>
<a class="jxr_linenumber" name="78" href="#78">78</a> <em class="jxr_javadoccomment"> * private final {@link ChannelHandler} idleStateHandler;</em>
<a class="jxr_linenumber" name="79" href="#79">79</a> <em class="jxr_javadoccomment"> *</em>
<a class="jxr_linenumber" name="80" href="#80">80</a> <em class="jxr_javadoccomment"> * public MyPipelineFactory({@link Timer} timer) {</em>
<a class="jxr_linenumber" name="81" href="#81">81</a> <em class="jxr_javadoccomment"> * this.timer = timer;</em>
<a class="jxr_linenumber" name="82" href="#82">82</a> <em class="jxr_javadoccomment"> * this.idleStateHandler = <b>new {@link IdleStateHandler}(timer, 60, 30, 0), // timer must be shared.</b></em>
<a class="jxr_linenumber" name="83" href="#83">83</a> <em class="jxr_javadoccomment"> * }</em>
<a class="jxr_linenumber" name="84" href="#84">84</a> <em class="jxr_javadoccomment"> *</em>
<a class="jxr_linenumber" name="85" href="#85">85</a> <em class="jxr_javadoccomment"> * public {@link ChannelPipeline} getPipeline() {</em>
<a class="jxr_linenumber" name="86" href="#86">86</a> <em class="jxr_javadoccomment"> * return {@link Channels}.pipeline(</em>
<a class="jxr_linenumber" name="87" href="#87">87</a> <em class="jxr_javadoccomment"> * idleStateHandler,</em>
<a class="jxr_linenumber" name="88" href="#88">88</a> <em class="jxr_javadoccomment"> * new MyHandler());</em>
<a class="jxr_linenumber" name="89" href="#89">89</a> <em class="jxr_javadoccomment"> * }</em>
<a class="jxr_linenumber" name="90" href="#90">90</a> <em class="jxr_javadoccomment"> * }</em>
<a class="jxr_linenumber" name="91" href="#91">91</a> <em class="jxr_javadoccomment"> *</em>
<a class="jxr_linenumber" name="92" href="#92">92</a> <em class="jxr_javadoccomment"> * // Handler should handle the {@link IdleStateEvent} triggered by {@link IdleStateHandler}.</em>
<a class="jxr_linenumber" name="93" href="#93">93</a> <em class="jxr_javadoccomment"> * public class MyHandler extends {@link IdleStateAwareChannelHandler} {</em>
<a class="jxr_linenumber" name="94" href="#94">94</a> <em class="jxr_javadoccomment"> *</em>
<a class="jxr_linenumber" name="95" href="#95">95</a> <em class="jxr_javadoccomment"> * {@code @Override}</em>
<a class="jxr_linenumber" name="96" href="#96">96</a> <em class="jxr_javadoccomment"> * public void channelIdle({@link ChannelHandlerContext} ctx, {@link IdleStateEvent} e) {</em>
<a class="jxr_linenumber" name="97" href="#97">97</a> <em class="jxr_javadoccomment"> * if (e.getState() == {@link IdleState}.READER_IDLE) {</em>
<a class="jxr_linenumber" name="98" href="#98">98</a> <em class="jxr_javadoccomment"> * e.getChannel().close();</em>
<a class="jxr_linenumber" name="99" href="#99">99</a> <em class="jxr_javadoccomment"> * } else if (e.getState() == {@link IdleState}.WRITER_IDLE) {</em>
<a class="jxr_linenumber" name="100" href="#100">100</a> <em class="jxr_javadoccomment"> * e.getChannel().write(new PingMessage());</em>
<a class="jxr_linenumber" name="101" href="#101">101</a> <em class="jxr_javadoccomment"> * }</em>
<a class="jxr_linenumber" name="102" href="#102">102</a> <em class="jxr_javadoccomment"> * }</em>
<a class="jxr_linenumber" name="103" href="#103">103</a> <em class="jxr_javadoccomment"> * }</em>
<a class="jxr_linenumber" name="104" href="#104">104</a> <em class="jxr_javadoccomment"> *</em>
<a class="jxr_linenumber" name="105" href="#105">105</a> <em class="jxr_javadoccomment"> * {@link ServerBootstrap} bootstrap = ...;</em>
<a class="jxr_linenumber" name="106" href="#106">106</a> <em class="jxr_javadoccomment"> * {@link Timer} timer = new {@link HashedWheelTimer}();</em>
<a class="jxr_linenumber" name="107" href="#107">107</a> <em class="jxr_javadoccomment"> * ...</em>
<a class="jxr_linenumber" name="108" href="#108">108</a> <em class="jxr_javadoccomment"> * bootstrap.setPipelineFactory(new MyPipelineFactory(timer));</em>
<a class="jxr_linenumber" name="109" href="#109">109</a> <em class="jxr_javadoccomment"> * ...</em>
<a class="jxr_linenumber" name="110" href="#110">110</a> <em class="jxr_javadoccomment"> * </pre></em>
<a class="jxr_linenumber" name="111" href="#111">111</a> <em class="jxr_javadoccomment"> *</em>
<a class="jxr_linenumber" name="112" href="#112">112</a> <em class="jxr_javadoccomment"> * The {@link Timer} which was specified when the {@link IdleStateHandler} is</em>
<a class="jxr_linenumber" name="113" href="#113">113</a> <em class="jxr_javadoccomment"> * created should be stopped manually by calling {@link #releaseExternalResources()}</em>
<a class="jxr_linenumber" name="114" href="#114">114</a> <em class="jxr_javadoccomment"> * or {@link Timer#stop()} when your application shuts down.</em>
<a class="jxr_linenumber" name="115" href="#115">115</a> <em class="jxr_javadoccomment"> * @see ReadTimeoutHandler</em>
<a class="jxr_linenumber" name="116" href="#116">116</a> <em class="jxr_javadoccomment"> * @see WriteTimeoutHandler</em>
<a class="jxr_linenumber" name="117" href="#117">117</a> <em class="jxr_javadoccomment"> *</em>
<a class="jxr_linenumber" name="118" href="#118">118</a> <em class="jxr_javadoccomment"> * @apiviz.landmark</em>
<a class="jxr_linenumber" name="119" href="#119">119</a> <em class="jxr_javadoccomment"> * @apiviz.uses org.jboss.netty.util.HashedWheelTimer</em>
<a class="jxr_linenumber" name="120" href="#120">120</a> <em class="jxr_javadoccomment"> * @apiviz.has org.jboss.netty.handler.timeout.IdleStateEvent oneway - - triggers</em>
<a class="jxr_linenumber" name="121" href="#121">121</a> <em class="jxr_javadoccomment"> */</em>
<a class="jxr_linenumber" name="122" href="#122">122</a> @Sharable
<a class="jxr_linenumber" name="123" href="#123">123</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">class</strong> <a href="../../../../../org/jboss/netty/handler/timeout/IdleStateHandler.html">IdleStateHandler</a> <strong class="jxr_keyword">extends</strong> <a href="../../../../../org/jboss/netty/channel/SimpleChannelUpstreamHandler.html">SimpleChannelUpstreamHandler</a>
<a class="jxr_linenumber" name="124" href="#124">124</a> <strong class="jxr_keyword">implements</strong> LifeCycleAwareChannelHandler,
<a class="jxr_linenumber" name="125" href="#125">125</a> <a href="../../../../../org/jboss/netty/util/ExternalResourceReleasable.html">ExternalResourceReleasable</a> {
<a class="jxr_linenumber" name="126" href="#126">126</a>
<a class="jxr_linenumber" name="127" href="#127">127</a> <strong class="jxr_keyword">final</strong> <a href="../../../../../org/jboss/netty/util/Timer.html">Timer</a> timer;
<a class="jxr_linenumber" name="128" href="#128">128</a>
<a class="jxr_linenumber" name="129" href="#129">129</a> <strong class="jxr_keyword">final</strong> <strong class="jxr_keyword">long</strong> readerIdleTimeMillis;
<a class="jxr_linenumber" name="130" href="#130">130</a> <strong class="jxr_keyword">final</strong> <strong class="jxr_keyword">long</strong> writerIdleTimeMillis;
<a class="jxr_linenumber" name="131" href="#131">131</a> <strong class="jxr_keyword">final</strong> <strong class="jxr_keyword">long</strong> allIdleTimeMillis;
<a class="jxr_linenumber" name="132" href="#132">132</a>
<a class="jxr_linenumber" name="133" href="#133">133</a> <em class="jxr_javadoccomment">/**</em>
<a class="jxr_linenumber" name="134" href="#134">134</a> <em class="jxr_javadoccomment"> * Creates a new instance.</em>
<a class="jxr_linenumber" name="135" href="#135">135</a> <em class="jxr_javadoccomment"> *</em>
<a class="jxr_linenumber" name="136" href="#136">136</a> <em class="jxr_javadoccomment"> * @param timer</em>
<a class="jxr_linenumber" name="137" href="#137">137</a> <em class="jxr_javadoccomment"> * the {@link Timer} that is used to trigger the scheduled event.</em>
<a class="jxr_linenumber" name="138" href="#138">138</a> <em class="jxr_javadoccomment"> * The recommended {@link Timer} implementation is {@link HashedWheelTimer}.</em>
<a class="jxr_linenumber" name="139" href="#139">139</a> <em class="jxr_javadoccomment"> * @param readerIdleTimeSeconds</em>
<a class="jxr_linenumber" name="140" href="#140">140</a> <em class="jxr_javadoccomment"> * an {@link IdleStateEvent} whose state is {@link IdleState#READER_IDLE}</em>
<a class="jxr_linenumber" name="141" href="#141">141</a> <em class="jxr_javadoccomment"> * will be triggered when no read was performed for the specified</em>
<a class="jxr_linenumber" name="142" href="#142">142</a> <em class="jxr_javadoccomment"> * period of time. Specify {@code 0} to disable.</em>
<a class="jxr_linenumber" name="143" href="#143">143</a> <em class="jxr_javadoccomment"> * @param writerIdleTimeSeconds</em>
<a class="jxr_linenumber" name="144" href="#144">144</a> <em class="jxr_javadoccomment"> * an {@link IdleStateEvent} whose state is {@link IdleState#WRITER_IDLE}</em>
<a class="jxr_linenumber" name="145" href="#145">145</a> <em class="jxr_javadoccomment"> * will be triggered when no write was performed for the specified</em>
<a class="jxr_linenumber" name="146" href="#146">146</a> <em class="jxr_javadoccomment"> * period of time. Specify {@code 0} to disable.</em>
<a class="jxr_linenumber" name="147" href="#147">147</a> <em class="jxr_javadoccomment"> * @param allIdleTimeSeconds</em>
<a class="jxr_linenumber" name="148" href="#148">148</a> <em class="jxr_javadoccomment"> * an {@link IdleStateEvent} whose state is {@link IdleState#ALL_IDLE}</em>
<a class="jxr_linenumber" name="149" href="#149">149</a> <em class="jxr_javadoccomment"> * will be triggered when neither read nor write was performed for</em>
<a class="jxr_linenumber" name="150" href="#150">150</a> <em class="jxr_javadoccomment"> * the specified period of time. Specify {@code 0} to disable.</em>
<a class="jxr_linenumber" name="151" href="#151">151</a> <em class="jxr_javadoccomment"> */</em>
<a class="jxr_linenumber" name="152" href="#152">152</a> <strong class="jxr_keyword">public</strong> <a href="../../../../../org/jboss/netty/handler/timeout/IdleStateHandler.html">IdleStateHandler</a>(
<a class="jxr_linenumber" name="153" href="#153">153</a> <a href="../../../../../org/jboss/netty/util/Timer.html">Timer</a> timer,
<a class="jxr_linenumber" name="154" href="#154">154</a> <strong class="jxr_keyword">int</strong> readerIdleTimeSeconds,
<a class="jxr_linenumber" name="155" href="#155">155</a> <strong class="jxr_keyword">int</strong> writerIdleTimeSeconds,
<a class="jxr_linenumber" name="156" href="#156">156</a> <strong class="jxr_keyword">int</strong> allIdleTimeSeconds) {
<a class="jxr_linenumber" name="157" href="#157">157</a>
<a class="jxr_linenumber" name="158" href="#158">158</a> <strong class="jxr_keyword">this</strong>(timer,
<a class="jxr_linenumber" name="159" href="#159">159</a> readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds,
<a class="jxr_linenumber" name="160" href="#160">160</a> TimeUnit.SECONDS);
<a class="jxr_linenumber" name="161" href="#161">161</a> }
<a class="jxr_linenumber" name="162" href="#162">162</a>
<a class="jxr_linenumber" name="163" href="#163">163</a> <em class="jxr_javadoccomment">/**</em>
<a class="jxr_linenumber" name="164" href="#164">164</a> <em class="jxr_javadoccomment"> * Creates a new instance.</em>
<a class="jxr_linenumber" name="165" href="#165">165</a> <em class="jxr_javadoccomment"> *</em>
<a class="jxr_linenumber" name="166" href="#166">166</a> <em class="jxr_javadoccomment"> * @param timer</em>
<a class="jxr_linenumber" name="167" href="#167">167</a> <em class="jxr_javadoccomment"> * the {@link Timer} that is used to trigger the scheduled event.</em>
<a class="jxr_linenumber" name="168" href="#168">168</a> <em class="jxr_javadoccomment"> * The recommended {@link Timer} implementation is {@link HashedWheelTimer}.</em>
<a class="jxr_linenumber" name="169" href="#169">169</a> <em class="jxr_javadoccomment"> * @param readerIdleTime</em>
<a class="jxr_linenumber" name="170" href="#170">170</a> <em class="jxr_javadoccomment"> * an {@link IdleStateEvent} whose state is {@link IdleState#READER_IDLE}</em>
<a class="jxr_linenumber" name="171" href="#171">171</a> <em class="jxr_javadoccomment"> * will be triggered when no read was performed for the specified</em>
<a class="jxr_linenumber" name="172" href="#172">172</a> <em class="jxr_javadoccomment"> * period of time. Specify {@code 0} to disable.</em>
<a class="jxr_linenumber" name="173" href="#173">173</a> <em class="jxr_javadoccomment"> * @param writerIdleTime</em>
<a class="jxr_linenumber" name="174" href="#174">174</a> <em class="jxr_javadoccomment"> * an {@link IdleStateEvent} whose state is {@link IdleState#WRITER_IDLE}</em>
<a class="jxr_linenumber" name="175" href="#175">175</a> <em class="jxr_javadoccomment"> * will be triggered when no write was performed for the specified</em>
<a class="jxr_linenumber" name="176" href="#176">176</a> <em class="jxr_javadoccomment"> * period of time. Specify {@code 0} to disable.</em>
<a class="jxr_linenumber" name="177" href="#177">177</a> <em class="jxr_javadoccomment"> * @param allIdleTime</em>
<a class="jxr_linenumber" name="178" href="#178">178</a> <em class="jxr_javadoccomment"> * an {@link IdleStateEvent} whose state is {@link IdleState#ALL_IDLE}</em>
<a class="jxr_linenumber" name="179" href="#179">179</a> <em class="jxr_javadoccomment"> * will be triggered when neither read nor write was performed for</em>
<a class="jxr_linenumber" name="180" href="#180">180</a> <em class="jxr_javadoccomment"> * the specified period of time. Specify {@code 0} to disable.</em>
<a class="jxr_linenumber" name="181" href="#181">181</a> <em class="jxr_javadoccomment"> * @param unit</em>
<a class="jxr_linenumber" name="182" href="#182">182</a> <em class="jxr_javadoccomment"> * the {@link TimeUnit} of {@code readerIdleTime},</em>
<a class="jxr_linenumber" name="183" href="#183">183</a> <em class="jxr_javadoccomment"> * {@code writeIdleTime}, and {@code allIdleTime}</em>
<a class="jxr_linenumber" name="184" href="#184">184</a> <em class="jxr_javadoccomment"> */</em>
<a class="jxr_linenumber" name="185" href="#185">185</a> <strong class="jxr_keyword">public</strong> <a href="../../../../../org/jboss/netty/handler/timeout/IdleStateHandler.html">IdleStateHandler</a>(
<a class="jxr_linenumber" name="186" href="#186">186</a> <a href="../../../../../org/jboss/netty/util/Timer.html">Timer</a> timer,
<a class="jxr_linenumber" name="187" href="#187">187</a> <strong class="jxr_keyword">long</strong> readerIdleTime, <strong class="jxr_keyword">long</strong> writerIdleTime, <strong class="jxr_keyword">long</strong> allIdleTime,
<a class="jxr_linenumber" name="188" href="#188">188</a> TimeUnit unit) {
<a class="jxr_linenumber" name="189" href="#189">189</a>
<a class="jxr_linenumber" name="190" href="#190">190</a> <strong class="jxr_keyword">if</strong> (timer == <strong class="jxr_keyword">null</strong>) {
<a class="jxr_linenumber" name="191" href="#191">191</a> <strong class="jxr_keyword">throw</strong> <strong class="jxr_keyword">new</strong> NullPointerException(<span class="jxr_string">"timer"</span>);
<a class="jxr_linenumber" name="192" href="#192">192</a> }
<a class="jxr_linenumber" name="193" href="#193">193</a> <strong class="jxr_keyword">if</strong> (unit == <strong class="jxr_keyword">null</strong>) {
<a class="jxr_linenumber" name="194" href="#194">194</a> <strong class="jxr_keyword">throw</strong> <strong class="jxr_keyword">new</strong> NullPointerException(<span class="jxr_string">"unit"</span>);
<a class="jxr_linenumber" name="195" href="#195">195</a> }
<a class="jxr_linenumber" name="196" href="#196">196</a>
<a class="jxr_linenumber" name="197" href="#197">197</a> <strong class="jxr_keyword">this</strong>.timer = timer;
<a class="jxr_linenumber" name="198" href="#198">198</a> <strong class="jxr_keyword">if</strong> (readerIdleTime <= 0) {
<a class="jxr_linenumber" name="199" href="#199">199</a> readerIdleTimeMillis = 0;
<a class="jxr_linenumber" name="200" href="#200">200</a> } <strong class="jxr_keyword">else</strong> {
<a class="jxr_linenumber" name="201" href="#201">201</a> readerIdleTimeMillis = Math.max(unit.toMillis(readerIdleTime), 1);
<a class="jxr_linenumber" name="202" href="#202">202</a> }
<a class="jxr_linenumber" name="203" href="#203">203</a> <strong class="jxr_keyword">if</strong> (writerIdleTime <= 0) {
<a class="jxr_linenumber" name="204" href="#204">204</a> writerIdleTimeMillis = 0;
<a class="jxr_linenumber" name="205" href="#205">205</a> } <strong class="jxr_keyword">else</strong> {
<a class="jxr_linenumber" name="206" href="#206">206</a> writerIdleTimeMillis = Math.max(unit.toMillis(writerIdleTime), 1);
<a class="jxr_linenumber" name="207" href="#207">207</a> }
<a class="jxr_linenumber" name="208" href="#208">208</a> <strong class="jxr_keyword">if</strong> (allIdleTime <= 0) {
<a class="jxr_linenumber" name="209" href="#209">209</a> allIdleTimeMillis = 0;
<a class="jxr_linenumber" name="210" href="#210">210</a> } <strong class="jxr_keyword">else</strong> {
<a class="jxr_linenumber" name="211" href="#211">211</a> allIdleTimeMillis = Math.max(unit.toMillis(allIdleTime), 1);
<a class="jxr_linenumber" name="212" href="#212">212</a> }
<a class="jxr_linenumber" name="213" href="#213">213</a> }
<a class="jxr_linenumber" name="214" href="#214">214</a>
<a class="jxr_linenumber" name="215" href="#215">215</a> <em class="jxr_javadoccomment">/**</em>
<a class="jxr_linenumber" name="216" href="#216">216</a> <em class="jxr_javadoccomment"> * Stops the {@link Timer} which was specified in the constructor of this</em>
<a class="jxr_linenumber" name="217" href="#217">217</a> <em class="jxr_javadoccomment"> * handler. You should not call this method if the {@link Timer} is in use</em>
<a class="jxr_linenumber" name="218" href="#218">218</a> <em class="jxr_javadoccomment"> * by other objects.</em>
<a class="jxr_linenumber" name="219" href="#219">219</a> <em class="jxr_javadoccomment"> */</em>
<a class="jxr_linenumber" name="220" href="#220">220</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> releaseExternalResources() {
<a class="jxr_linenumber" name="221" href="#221">221</a> timer.stop();
<a class="jxr_linenumber" name="222" href="#222">222</a> }
<a class="jxr_linenumber" name="223" href="#223">223</a>
<a class="jxr_linenumber" name="224" href="#224">224</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> beforeAdd(<a href="../../../../../org/jboss/netty/channel/ChannelHandlerContext.html">ChannelHandlerContext</a> ctx) <strong class="jxr_keyword">throws</strong> Exception {
<a class="jxr_linenumber" name="225" href="#225">225</a> <strong class="jxr_keyword">if</strong> (ctx.getPipeline().isAttached()) {
<a class="jxr_linenumber" name="226" href="#226">226</a> <em class="jxr_comment">// channelOpen event has been fired already, which means</em>
<a class="jxr_linenumber" name="227" href="#227">227</a> <em class="jxr_comment">// this.channelOpen() will not be invoked.</em>
<a class="jxr_linenumber" name="228" href="#228">228</a> <em class="jxr_comment">// We have to initialize here instead.</em>
<a class="jxr_linenumber" name="229" href="#229">229</a> initialize(ctx);
<a class="jxr_linenumber" name="230" href="#230">230</a> } <strong class="jxr_keyword">else</strong> {
<a class="jxr_linenumber" name="231" href="#231">231</a> <em class="jxr_comment">// channelOpen event has not been fired yet.</em>
<a class="jxr_linenumber" name="232" href="#232">232</a> <em class="jxr_comment">// this.channelOpen() will be invoked and initialization will occur there.</em>
<a class="jxr_linenumber" name="233" href="#233">233</a> }
<a class="jxr_linenumber" name="234" href="#234">234</a> }
<a class="jxr_linenumber" name="235" href="#235">235</a>
<a class="jxr_linenumber" name="236" href="#236">236</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> afterAdd(<a href="../../../../../org/jboss/netty/channel/ChannelHandlerContext.html">ChannelHandlerContext</a> ctx) <strong class="jxr_keyword">throws</strong> Exception {
<a class="jxr_linenumber" name="237" href="#237">237</a> <em class="jxr_comment">// NOOP</em>
<a class="jxr_linenumber" name="238" href="#238">238</a> }
<a class="jxr_linenumber" name="239" href="#239">239</a>
<a class="jxr_linenumber" name="240" href="#240">240</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> beforeRemove(<a href="../../../../../org/jboss/netty/channel/ChannelHandlerContext.html">ChannelHandlerContext</a> ctx) <strong class="jxr_keyword">throws</strong> Exception {
<a class="jxr_linenumber" name="241" href="#241">241</a> destroy(ctx);
<a class="jxr_linenumber" name="242" href="#242">242</a> }
<a class="jxr_linenumber" name="243" href="#243">243</a>
<a class="jxr_linenumber" name="244" href="#244">244</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> afterRemove(<a href="../../../../../org/jboss/netty/channel/ChannelHandlerContext.html">ChannelHandlerContext</a> ctx) <strong class="jxr_keyword">throws</strong> Exception {
<a class="jxr_linenumber" name="245" href="#245">245</a> <em class="jxr_comment">// NOOP</em>
<a class="jxr_linenumber" name="246" href="#246">246</a> }
<a class="jxr_linenumber" name="247" href="#247">247</a>
<a class="jxr_linenumber" name="248" href="#248">248</a> @Override
<a class="jxr_linenumber" name="249" href="#249">249</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> channelOpen(<a href="../../../../../org/jboss/netty/channel/ChannelHandlerContext.html">ChannelHandlerContext</a> ctx, <a href="../../../../../org/jboss/netty/channel/ChannelStateEvent.html">ChannelStateEvent</a> e)
<a class="jxr_linenumber" name="250" href="#250">250</a> <strong class="jxr_keyword">throws</strong> Exception {
<a class="jxr_linenumber" name="251" href="#251">251</a> <em class="jxr_comment">// This method will be invoked only if this handler was added</em>
<a class="jxr_linenumber" name="252" href="#252">252</a> <em class="jxr_comment">// before channelOpen event is fired. If a user adds this handler</em>
<a class="jxr_linenumber" name="253" href="#253">253</a> <em class="jxr_comment">// after the channelOpen event, initialize() will be called by beforeAdd().</em>
<a class="jxr_linenumber" name="254" href="#254">254</a> initialize(ctx);
<a class="jxr_linenumber" name="255" href="#255">255</a> ctx.sendUpstream(e);
<a class="jxr_linenumber" name="256" href="#256">256</a> }
<a class="jxr_linenumber" name="257" href="#257">257</a>
<a class="jxr_linenumber" name="258" href="#258">258</a> @Override
<a class="jxr_linenumber" name="259" href="#259">259</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> channelClosed(<a href="../../../../../org/jboss/netty/channel/ChannelHandlerContext.html">ChannelHandlerContext</a> ctx, <a href="../../../../../org/jboss/netty/channel/ChannelStateEvent.html">ChannelStateEvent</a> e)
<a class="jxr_linenumber" name="260" href="#260">260</a> <strong class="jxr_keyword">throws</strong> Exception {
<a class="jxr_linenumber" name="261" href="#261">261</a> destroy(ctx);
<a class="jxr_linenumber" name="262" href="#262">262</a> ctx.sendUpstream(e);
<a class="jxr_linenumber" name="263" href="#263">263</a> }
<a class="jxr_linenumber" name="264" href="#264">264</a>
<a class="jxr_linenumber" name="265" href="#265">265</a> @Override
<a class="jxr_linenumber" name="266" href="#266">266</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> messageReceived(<a href="../../../../../org/jboss/netty/channel/ChannelHandlerContext.html">ChannelHandlerContext</a> ctx, <a href="../../../../../org/jboss/netty/channel/MessageEvent.html">MessageEvent</a> e)
<a class="jxr_linenumber" name="267" href="#267">267</a> <strong class="jxr_keyword">throws</strong> Exception {
<a class="jxr_linenumber" name="268" href="#268">268</a> <a href="../../../../../org/jboss/netty/handler/timeout/ReadTimeoutHandler.html">State</a> state = (State) ctx.getAttachment();
<a class="jxr_linenumber" name="269" href="#269">269</a> state.lastReadTime = System.currentTimeMillis();
<a class="jxr_linenumber" name="270" href="#270">270</a> ctx.sendUpstream(e);
<a class="jxr_linenumber" name="271" href="#271">271</a> }
<a class="jxr_linenumber" name="272" href="#272">272</a>
<a class="jxr_linenumber" name="273" href="#273">273</a> @Override
<a class="jxr_linenumber" name="274" href="#274">274</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> writeComplete(<a href="../../../../../org/jboss/netty/channel/ChannelHandlerContext.html">ChannelHandlerContext</a> ctx, <a href="../../../../../org/jboss/netty/channel/WriteCompletionEvent.html">WriteCompletionEvent</a> e)
<a class="jxr_linenumber" name="275" href="#275">275</a> <strong class="jxr_keyword">throws</strong> Exception {
<a class="jxr_linenumber" name="276" href="#276">276</a> <strong class="jxr_keyword">if</strong> (e.getWrittenAmount() > 0) {
<a class="jxr_linenumber" name="277" href="#277">277</a> <a href="../../../../../org/jboss/netty/handler/timeout/ReadTimeoutHandler.html">State</a> state = (State) ctx.getAttachment();
<a class="jxr_linenumber" name="278" href="#278">278</a> state.lastWriteTime = System.currentTimeMillis();
<a class="jxr_linenumber" name="279" href="#279">279</a> }
<a class="jxr_linenumber" name="280" href="#280">280</a> ctx.sendUpstream(e);
<a class="jxr_linenumber" name="281" href="#281">281</a> }
<a class="jxr_linenumber" name="282" href="#282">282</a>
<a class="jxr_linenumber" name="283" href="#283">283</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">void</strong> initialize(<a href="../../../../../org/jboss/netty/channel/ChannelHandlerContext.html">ChannelHandlerContext</a> ctx) {
<a class="jxr_linenumber" name="284" href="#284">284</a> <a href="../../../../../org/jboss/netty/handler/timeout/ReadTimeoutHandler.html">State</a> state = <strong class="jxr_keyword">new</strong> <a href="../../../../../org/jboss/netty/handler/timeout/ReadTimeoutHandler.html">State</a>();
<a class="jxr_linenumber" name="285" href="#285">285</a> ctx.setAttachment(state);
<a class="jxr_linenumber" name="286" href="#286">286</a>
<a class="jxr_linenumber" name="287" href="#287">287</a> state.lastReadTime = state.lastWriteTime = System.currentTimeMillis();
<a class="jxr_linenumber" name="288" href="#288">288</a> <strong class="jxr_keyword">if</strong> (readerIdleTimeMillis > 0) {
<a class="jxr_linenumber" name="289" href="#289">289</a> state.readerIdleTimeout = timer.newTimeout(
<a class="jxr_linenumber" name="290" href="#290">290</a> <strong class="jxr_keyword">new</strong> <a href="../../../../../org/jboss/netty/handler/timeout/IdleStateHandler.html">ReaderIdleTimeoutTask</a>(ctx),
<a class="jxr_linenumber" name="291" href="#291">291</a> readerIdleTimeMillis, TimeUnit.MILLISECONDS);
<a class="jxr_linenumber" name="292" href="#292">292</a> }
<a class="jxr_linenumber" name="293" href="#293">293</a> <strong class="jxr_keyword">if</strong> (writerIdleTimeMillis > 0) {
<a class="jxr_linenumber" name="294" href="#294">294</a> state.writerIdleTimeout = timer.newTimeout(
<a class="jxr_linenumber" name="295" href="#295">295</a> <strong class="jxr_keyword">new</strong> <a href="../../../../../org/jboss/netty/handler/timeout/IdleStateHandler.html">WriterIdleTimeoutTask</a>(ctx),
<a class="jxr_linenumber" name="296" href="#296">296</a> writerIdleTimeMillis, TimeUnit.MILLISECONDS);
<a class="jxr_linenumber" name="297" href="#297">297</a> }
<a class="jxr_linenumber" name="298" href="#298">298</a> <strong class="jxr_keyword">if</strong> (allIdleTimeMillis > 0) {
<a class="jxr_linenumber" name="299" href="#299">299</a> state.allIdleTimeout = timer.newTimeout(
<a class="jxr_linenumber" name="300" href="#300">300</a> <strong class="jxr_keyword">new</strong> <a href="../../../../../org/jboss/netty/handler/timeout/IdleStateHandler.html">AllIdleTimeoutTask</a>(ctx),
<a class="jxr_linenumber" name="301" href="#301">301</a> allIdleTimeMillis, TimeUnit.MILLISECONDS);
<a class="jxr_linenumber" name="302" href="#302">302</a> }
<a class="jxr_linenumber" name="303" href="#303">303</a> }
<a class="jxr_linenumber" name="304" href="#304">304</a>
<a class="jxr_linenumber" name="305" href="#305">305</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">void</strong> destroy(<a href="../../../../../org/jboss/netty/channel/ChannelHandlerContext.html">ChannelHandlerContext</a> ctx) {
<a class="jxr_linenumber" name="306" href="#306">306</a> <a href="../../../../../org/jboss/netty/handler/timeout/ReadTimeoutHandler.html">State</a> state = (State) ctx.getAttachment();
<a class="jxr_linenumber" name="307" href="#307">307</a>
<a class="jxr_linenumber" name="308" href="#308">308</a> <em class="jxr_comment">// Check if the state was set before, it may not if the destroy method was called before the </em>
<a class="jxr_linenumber" name="309" href="#309">309</a> <em class="jxr_comment">// channelOpen(...) method. </em>
<a class="jxr_linenumber" name="310" href="#310">310</a> <em class="jxr_comment">//</em>
<a class="jxr_linenumber" name="311" href="#311">311</a> <em class="jxr_comment">// See #143</em>
<a class="jxr_linenumber" name="312" href="#312">312</a> <strong class="jxr_keyword">if</strong> (state != <strong class="jxr_keyword">null</strong>) {
<a class="jxr_linenumber" name="313" href="#313">313</a> <strong class="jxr_keyword">if</strong> (state.readerIdleTimeout != <strong class="jxr_keyword">null</strong>) {
<a class="jxr_linenumber" name="314" href="#314">314</a> state.readerIdleTimeout.cancel();
<a class="jxr_linenumber" name="315" href="#315">315</a> state.readerIdleTimeout = <strong class="jxr_keyword">null</strong>;
<a class="jxr_linenumber" name="316" href="#316">316</a> }
<a class="jxr_linenumber" name="317" href="#317">317</a> <strong class="jxr_keyword">if</strong> (state.writerIdleTimeout != <strong class="jxr_keyword">null</strong>) {
<a class="jxr_linenumber" name="318" href="#318">318</a> state.writerIdleTimeout.cancel();
<a class="jxr_linenumber" name="319" href="#319">319</a> state.writerIdleTimeout = <strong class="jxr_keyword">null</strong>;
<a class="jxr_linenumber" name="320" href="#320">320</a> }
<a class="jxr_linenumber" name="321" href="#321">321</a> <strong class="jxr_keyword">if</strong> (state.allIdleTimeout != <strong class="jxr_keyword">null</strong>) {
<a class="jxr_linenumber" name="322" href="#322">322</a> state.allIdleTimeout.cancel();
<a class="jxr_linenumber" name="323" href="#323">323</a> state.allIdleTimeout = <strong class="jxr_keyword">null</strong>;
<a class="jxr_linenumber" name="324" href="#324">324</a> }
<a class="jxr_linenumber" name="325" href="#325">325</a> }
<a class="jxr_linenumber" name="326" href="#326">326</a>
<a class="jxr_linenumber" name="327" href="#327">327</a> }
<a class="jxr_linenumber" name="328" href="#328">328</a>
<a class="jxr_linenumber" name="329" href="#329">329</a> <strong class="jxr_keyword">protected</strong> <strong class="jxr_keyword">void</strong> channelIdle(
<a class="jxr_linenumber" name="330" href="#330">330</a> <a href="../../../../../org/jboss/netty/channel/ChannelHandlerContext.html">ChannelHandlerContext</a> ctx, <a href="../../../../../org/jboss/netty/handler/timeout/IdleState.html">IdleState</a> state, <strong class="jxr_keyword">long</strong> lastActivityTimeMillis) <strong class="jxr_keyword">throws</strong> Exception {
<a class="jxr_linenumber" name="331" href="#331">331</a> ctx.sendUpstream(<strong class="jxr_keyword">new</strong> <a href="../../../../../org/jboss/netty/handler/timeout/DefaultIdleStateEvent.html">DefaultIdleStateEvent</a>(ctx.getChannel(), state, lastActivityTimeMillis));
<a class="jxr_linenumber" name="332" href="#332">332</a> }
<a class="jxr_linenumber" name="333" href="#333">333</a>
<a class="jxr_linenumber" name="334" href="#334">334</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">final</strong> <strong class="jxr_keyword">class</strong> <a href="../../../../../org/jboss/netty/handler/timeout/IdleStateHandler.html">ReaderIdleTimeoutTask</a> <strong class="jxr_keyword">implements</strong> <a href="../../../../../org/jboss/netty/util/TimerTask.html">TimerTask</a> {
<a class="jxr_linenumber" name="335" href="#335">335</a>
<a class="jxr_linenumber" name="336" href="#336">336</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">final</strong> <a href="../../../../../org/jboss/netty/channel/ChannelHandlerContext.html">ChannelHandlerContext</a> ctx;
<a class="jxr_linenumber" name="337" href="#337">337</a>
<a class="jxr_linenumber" name="338" href="#338">338</a> <a href="../../../../../org/jboss/netty/handler/timeout/IdleStateHandler.html">ReaderIdleTimeoutTask</a>(<a href="../../../../../org/jboss/netty/channel/ChannelHandlerContext.html">ChannelHandlerContext</a> ctx) {
<a class="jxr_linenumber" name="339" href="#339">339</a> <strong class="jxr_keyword">this</strong>.ctx = ctx;
<a class="jxr_linenumber" name="340" href="#340">340</a> }
<a class="jxr_linenumber" name="341" href="#341">341</a>
<a class="jxr_linenumber" name="342" href="#342">342</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> run(<a href="../../../../../org/jboss/netty/util/Timeout.html">Timeout</a> timeout) <strong class="jxr_keyword">throws</strong> Exception {
<a class="jxr_linenumber" name="343" href="#343">343</a> <strong class="jxr_keyword">if</strong> (timeout.isCancelled() || !ctx.getChannel().isOpen()) {
<a class="jxr_linenumber" name="344" href="#344">344</a> <strong class="jxr_keyword">return</strong>;
<a class="jxr_linenumber" name="345" href="#345">345</a> }
<a class="jxr_linenumber" name="346" href="#346">346</a>
<a class="jxr_linenumber" name="347" href="#347">347</a> <a href="../../../../../org/jboss/netty/handler/timeout/ReadTimeoutHandler.html">State</a> state = (State) ctx.getAttachment();
<a class="jxr_linenumber" name="348" href="#348">348</a> <strong class="jxr_keyword">long</strong> currentTime = System.currentTimeMillis();
<a class="jxr_linenumber" name="349" href="#349">349</a> <strong class="jxr_keyword">long</strong> lastReadTime = state.lastReadTime;
<a class="jxr_linenumber" name="350" href="#350">350</a> <strong class="jxr_keyword">long</strong> nextDelay = readerIdleTimeMillis - (currentTime - lastReadTime);
<a class="jxr_linenumber" name="351" href="#351">351</a> <strong class="jxr_keyword">if</strong> (nextDelay <= 0) {
<a class="jxr_linenumber" name="352" href="#352">352</a> <em class="jxr_comment">// Reader is idle - set a new timeout and notify the callback.</em>
<a class="jxr_linenumber" name="353" href="#353">353</a> state.readerIdleTimeout =
<a class="jxr_linenumber" name="354" href="#354">354</a> timer.newTimeout(<strong class="jxr_keyword">this</strong>, readerIdleTimeMillis, TimeUnit.MILLISECONDS);
<a class="jxr_linenumber" name="355" href="#355">355</a> <strong class="jxr_keyword">try</strong> {
<a class="jxr_linenumber" name="356" href="#356">356</a> channelIdle(ctx, IdleState.READER_IDLE, lastReadTime);
<a class="jxr_linenumber" name="357" href="#357">357</a> } <strong class="jxr_keyword">catch</strong> (Throwable t) {
<a class="jxr_linenumber" name="358" href="#358">358</a> fireExceptionCaught(ctx, t);
<a class="jxr_linenumber" name="359" href="#359">359</a> }
<a class="jxr_linenumber" name="360" href="#360">360</a> } <strong class="jxr_keyword">else</strong> {
<a class="jxr_linenumber" name="361" href="#361">361</a> <em class="jxr_comment">// Read occurred before the timeout - set a new timeout with shorter delay.</em>
<a class="jxr_linenumber" name="362" href="#362">362</a> state.readerIdleTimeout =
<a class="jxr_linenumber" name="363" href="#363">363</a> timer.newTimeout(<strong class="jxr_keyword">this</strong>, nextDelay, TimeUnit.MILLISECONDS);
<a class="jxr_linenumber" name="364" href="#364">364</a> }
<a class="jxr_linenumber" name="365" href="#365">365</a> }
<a class="jxr_linenumber" name="366" href="#366">366</a>
<a class="jxr_linenumber" name="367" href="#367">367</a> }
<a class="jxr_linenumber" name="368" href="#368">368</a>
<a class="jxr_linenumber" name="369" href="#369">369</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">final</strong> <strong class="jxr_keyword">class</strong> <a href="../../../../../org/jboss/netty/handler/timeout/IdleStateHandler.html">WriterIdleTimeoutTask</a> <strong class="jxr_keyword">implements</strong> <a href="../../../../../org/jboss/netty/util/TimerTask.html">TimerTask</a> {
<a class="jxr_linenumber" name="370" href="#370">370</a>
<a class="jxr_linenumber" name="371" href="#371">371</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">final</strong> <a href="../../../../../org/jboss/netty/channel/ChannelHandlerContext.html">ChannelHandlerContext</a> ctx;
<a class="jxr_linenumber" name="372" href="#372">372</a>
<a class="jxr_linenumber" name="373" href="#373">373</a> <a href="../../../../../org/jboss/netty/handler/timeout/IdleStateHandler.html">WriterIdleTimeoutTask</a>(<a href="../../../../../org/jboss/netty/channel/ChannelHandlerContext.html">ChannelHandlerContext</a> ctx) {
<a class="jxr_linenumber" name="374" href="#374">374</a> <strong class="jxr_keyword">this</strong>.ctx = ctx;
<a class="jxr_linenumber" name="375" href="#375">375</a> }
<a class="jxr_linenumber" name="376" href="#376">376</a>
<a class="jxr_linenumber" name="377" href="#377">377</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> run(<a href="../../../../../org/jboss/netty/util/Timeout.html">Timeout</a> timeout) <strong class="jxr_keyword">throws</strong> Exception {
<a class="jxr_linenumber" name="378" href="#378">378</a> <strong class="jxr_keyword">if</strong> (timeout.isCancelled() || !ctx.getChannel().isOpen()) {
<a class="jxr_linenumber" name="379" href="#379">379</a> <strong class="jxr_keyword">return</strong>;
<a class="jxr_linenumber" name="380" href="#380">380</a> }
<a class="jxr_linenumber" name="381" href="#381">381</a>
<a class="jxr_linenumber" name="382" href="#382">382</a> <a href="../../../../../org/jboss/netty/handler/timeout/ReadTimeoutHandler.html">State</a> state = (State) ctx.getAttachment();
<a class="jxr_linenumber" name="383" href="#383">383</a> <strong class="jxr_keyword">long</strong> currentTime = System.currentTimeMillis();
<a class="jxr_linenumber" name="384" href="#384">384</a> <strong class="jxr_keyword">long</strong> lastWriteTime = state.lastWriteTime;
<a class="jxr_linenumber" name="385" href="#385">385</a> <strong class="jxr_keyword">long</strong> nextDelay = writerIdleTimeMillis - (currentTime - lastWriteTime);
<a class="jxr_linenumber" name="386" href="#386">386</a> <strong class="jxr_keyword">if</strong> (nextDelay <= 0) {
<a class="jxr_linenumber" name="387" href="#387">387</a> <em class="jxr_comment">// Writer is idle - set a new timeout and notify the callback.</em>
<a class="jxr_linenumber" name="388" href="#388">388</a> state.writerIdleTimeout =
<a class="jxr_linenumber" name="389" href="#389">389</a> timer.newTimeout(<strong class="jxr_keyword">this</strong>, writerIdleTimeMillis, TimeUnit.MILLISECONDS);
<a class="jxr_linenumber" name="390" href="#390">390</a> <strong class="jxr_keyword">try</strong> {
<a class="jxr_linenumber" name="391" href="#391">391</a> channelIdle(ctx, IdleState.WRITER_IDLE, lastWriteTime);
<a class="jxr_linenumber" name="392" href="#392">392</a> } <strong class="jxr_keyword">catch</strong> (Throwable t) {
<a class="jxr_linenumber" name="393" href="#393">393</a> fireExceptionCaught(ctx, t);
<a class="jxr_linenumber" name="394" href="#394">394</a> }
<a class="jxr_linenumber" name="395" href="#395">395</a> } <strong class="jxr_keyword">else</strong> {
<a class="jxr_linenumber" name="396" href="#396">396</a> <em class="jxr_comment">// Write occurred before the timeout - set a new timeout with shorter delay.</em>
<a class="jxr_linenumber" name="397" href="#397">397</a> state.writerIdleTimeout =
<a class="jxr_linenumber" name="398" href="#398">398</a> timer.newTimeout(<strong class="jxr_keyword">this</strong>, nextDelay, TimeUnit.MILLISECONDS);
<a class="jxr_linenumber" name="399" href="#399">399</a> }
<a class="jxr_linenumber" name="400" href="#400">400</a> }
<a class="jxr_linenumber" name="401" href="#401">401</a> }
<a class="jxr_linenumber" name="402" href="#402">402</a>
<a class="jxr_linenumber" name="403" href="#403">403</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">final</strong> <strong class="jxr_keyword">class</strong> <a href="../../../../../org/jboss/netty/handler/timeout/IdleStateHandler.html">AllIdleTimeoutTask</a> <strong class="jxr_keyword">implements</strong> <a href="../../../../../org/jboss/netty/util/TimerTask.html">TimerTask</a> {
<a class="jxr_linenumber" name="404" href="#404">404</a>
<a class="jxr_linenumber" name="405" href="#405">405</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">final</strong> <a href="../../../../../org/jboss/netty/channel/ChannelHandlerContext.html">ChannelHandlerContext</a> ctx;
<a class="jxr_linenumber" name="406" href="#406">406</a>
<a class="jxr_linenumber" name="407" href="#407">407</a> <a href="../../../../../org/jboss/netty/handler/timeout/IdleStateHandler.html">AllIdleTimeoutTask</a>(<a href="../../../../../org/jboss/netty/channel/ChannelHandlerContext.html">ChannelHandlerContext</a> ctx) {
<a class="jxr_linenumber" name="408" href="#408">408</a> <strong class="jxr_keyword">this</strong>.ctx = ctx;
<a class="jxr_linenumber" name="409" href="#409">409</a> }
<a class="jxr_linenumber" name="410" href="#410">410</a>
<a class="jxr_linenumber" name="411" href="#411">411</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> run(<a href="../../../../../org/jboss/netty/util/Timeout.html">Timeout</a> timeout) <strong class="jxr_keyword">throws</strong> Exception {
<a class="jxr_linenumber" name="412" href="#412">412</a> <strong class="jxr_keyword">if</strong> (timeout.isCancelled() || !ctx.getChannel().isOpen()) {
<a class="jxr_linenumber" name="413" href="#413">413</a> <strong class="jxr_keyword">return</strong>;
<a class="jxr_linenumber" name="414" href="#414">414</a> }
<a class="jxr_linenumber" name="415" href="#415">415</a>
<a class="jxr_linenumber" name="416" href="#416">416</a> <a href="../../../../../org/jboss/netty/handler/timeout/ReadTimeoutHandler.html">State</a> state = (State) ctx.getAttachment();
<a class="jxr_linenumber" name="417" href="#417">417</a> <strong class="jxr_keyword">long</strong> currentTime = System.currentTimeMillis();
<a class="jxr_linenumber" name="418" href="#418">418</a> <strong class="jxr_keyword">long</strong> lastIoTime = Math.max(state.lastReadTime, state.lastWriteTime);
<a class="jxr_linenumber" name="419" href="#419">419</a> <strong class="jxr_keyword">long</strong> nextDelay = allIdleTimeMillis - (currentTime - lastIoTime);
<a class="jxr_linenumber" name="420" href="#420">420</a> <strong class="jxr_keyword">if</strong> (nextDelay <= 0) {
<a class="jxr_linenumber" name="421" href="#421">421</a> <em class="jxr_comment">// Both reader and writer are idle - set a new timeout and</em>
<a class="jxr_linenumber" name="422" href="#422">422</a> <em class="jxr_comment">// notify the callback.</em>
<a class="jxr_linenumber" name="423" href="#423">423</a> state.allIdleTimeout =
<a class="jxr_linenumber" name="424" href="#424">424</a> timer.newTimeout(<strong class="jxr_keyword">this</strong>, allIdleTimeMillis, TimeUnit.MILLISECONDS);
<a class="jxr_linenumber" name="425" href="#425">425</a> <strong class="jxr_keyword">try</strong> {
<a class="jxr_linenumber" name="426" href="#426">426</a> channelIdle(ctx, IdleState.ALL_IDLE, lastIoTime);
<a class="jxr_linenumber" name="427" href="#427">427</a> } <strong class="jxr_keyword">catch</strong> (Throwable t) {
<a class="jxr_linenumber" name="428" href="#428">428</a> fireExceptionCaught(ctx, t);
<a class="jxr_linenumber" name="429" href="#429">429</a> }
<a class="jxr_linenumber" name="430" href="#430">430</a> } <strong class="jxr_keyword">else</strong> {
<a class="jxr_linenumber" name="431" href="#431">431</a> <em class="jxr_comment">// Either read or write occurred before the timeout - set a new</em>
<a class="jxr_linenumber" name="432" href="#432">432</a> <em class="jxr_comment">// timeout with shorter delay.</em>
<a class="jxr_linenumber" name="433" href="#433">433</a> state.allIdleTimeout =
<a class="jxr_linenumber" name="434" href="#434">434</a> timer.newTimeout(<strong class="jxr_keyword">this</strong>, nextDelay, TimeUnit.MILLISECONDS);
<a class="jxr_linenumber" name="435" href="#435">435</a> }
<a class="jxr_linenumber" name="436" href="#436">436</a> }
<a class="jxr_linenumber" name="437" href="#437">437</a> }
<a class="jxr_linenumber" name="438" href="#438">438</a>
<a class="jxr_linenumber" name="439" href="#439">439</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">static</strong> <strong class="jxr_keyword">final</strong> <strong class="jxr_keyword">class</strong> <a href="../../../../../org/jboss/netty/handler/timeout/ReadTimeoutHandler.html">State</a> {
<a class="jxr_linenumber" name="440" href="#440">440</a> <a href="../../../../../org/jboss/netty/handler/timeout/ReadTimeoutHandler.html">State</a>() {
<a class="jxr_linenumber" name="441" href="#441">441</a> <strong class="jxr_keyword">super</strong>();
<a class="jxr_linenumber" name="442" href="#442">442</a> }
<a class="jxr_linenumber" name="443" href="#443">443</a>
<a class="jxr_linenumber" name="444" href="#444">444</a> <strong class="jxr_keyword">volatile</strong> <a href="../../../../../org/jboss/netty/util/Timeout.html">Timeout</a> readerIdleTimeout;
<a class="jxr_linenumber" name="445" href="#445">445</a> <strong class="jxr_keyword">volatile</strong> <strong class="jxr_keyword">long</strong> lastReadTime;
<a class="jxr_linenumber" name="446" href="#446">446</a>
<a class="jxr_linenumber" name="447" href="#447">447</a> <strong class="jxr_keyword">volatile</strong> <a href="../../../../../org/jboss/netty/util/Timeout.html">Timeout</a> writerIdleTimeout;
<a class="jxr_linenumber" name="448" href="#448">448</a> <strong class="jxr_keyword">volatile</strong> <strong class="jxr_keyword">long</strong> lastWriteTime;
<a class="jxr_linenumber" name="449" href="#449">449</a>
<a class="jxr_linenumber" name="450" href="#450">450</a> <strong class="jxr_keyword">volatile</strong> <a href="../../../../../org/jboss/netty/util/Timeout.html">Timeout</a> allIdleTimeout;
<a class="jxr_linenumber" name="451" href="#451">451</a> }
<a class="jxr_linenumber" name="452" href="#452">452</a> }
</pre>
<hr/><div id="footer">This page was automatically generated by <a href="http://maven.apache.org/">Maven</a></div></body>
</html>
|
apache-2.0
|
xorware/android_frameworks_base
|
docs/html/sdk/api_diff/24/changes/java.util.logging.StreamHandler.html
|
5383
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "//www.w3.org/TR/html4/strict.dtd">
<HTML style="overflow:auto;">
<HEAD>
<meta name="generator" content="JDiff v1.1.0">
<!-- Generated by the JDiff Javadoc doclet -->
<!-- (http://www.jdiff.org) -->
<meta name="description" content="JDiff is a Javadoc doclet which generates an HTML report of all the packages, classes, constructors, methods, and fields which have been removed, added or changed in any way, including their documentation, when two APIs are compared.">
<meta name="keywords" content="diff, jdiff, javadiff, java diff, java difference, API difference, difference between two APIs, API diff, Javadoc, doclet">
<TITLE>
java.util.logging.StreamHandler
</TITLE>
<link href="../../../../assets/android-developer-docs.css" rel="stylesheet" type="text/css" />
<link href="../stylesheet-jdiff.css" rel="stylesheet" type="text/css" />
<noscript>
<style type="text/css">
body{overflow:auto;}
#body-content{position:relative; top:0;}
#doc-content{overflow:visible;border-left:3px solid #666;}
#side-nav{padding:0;}
#side-nav .toggle-list ul {display:block;}
#resize-packages-nav{border-bottom:3px solid #666;}
</style>
</noscript>
<style type="text/css">
</style>
</HEAD>
<BODY>
<!-- Start of nav bar -->
<a name="top"></a>
<div id="header" style="margin-bottom:0;padding-bottom:0;">
<div id="headerLeft">
<a href="../../../../index.html" tabindex="-1" target="_top"><img src="../../../../assets/images/bg_logo.png" alt="Android Developers" /></a>
</div>
<div id="headerRight">
<div id="headerLinks">
<!-- <img src="/assets/images/icon_world.jpg" alt="" /> -->
<span class="text">
<!-- <a href="#">English</a> | -->
<nobr><a href="//developer.android.com" target="_top">Android Developers</a> | <a href="//www.android.com" target="_top">Android.com</a></nobr>
</span>
</div>
<div class="and-diff-id" style="margin-top:6px;margin-right:8px;">
<table class="diffspectable">
<tr>
<td colspan="2" class="diffspechead">API Diff Specification</td>
</tr>
<tr>
<td class="diffspec" style="padding-top:.25em">To Level:</td>
<td class="diffvaluenew" style="padding-top:.25em">24</td>
</tr>
<tr>
<td class="diffspec">From Level:</td>
<td class="diffvalueold">23</td>
</tr>
<tr>
<td class="diffspec">Generated</td>
<td class="diffvalue">2016.06.13 13:31</td>
</tr>
</table>
</div><!-- End and-diff-id -->
<div class="and-diff-id" style="margin-right:8px;">
<table class="diffspectable">
<tr>
<td class="diffspec" colspan="2"><a href="jdiff_statistics.html">Statistics</a>
</tr>
</table>
</div> <!-- End and-diff-id -->
</div> <!-- End headerRight -->
</div> <!-- End header -->
<div id="body-content" xstyle="padding:12px;padding-right:18px;">
<div id="doc-content" style="position:relative;">
<div id="mainBodyFluid">
<H2>
Class java.util.logging.<A HREF="../../../../reference/java/util/logging/StreamHandler.html" target="_top"><font size="+2"><code>StreamHandler</code></font></A>
</H2>
<a NAME="constructors"></a>
<a NAME="methods"></a>
<p>
<a NAME="Changed"></a>
<TABLE summary="Changed Methods" WIDTH="100%">
<TR>
<TH VALIGN="TOP" COLSPAN=3>Changed Methods</FONT></TD>
</TH>
<TR BGCOLOR="#FFFFFF" CLASS="TableRowColor">
<TD VALIGN="TOP" WIDTH="25%">
<A NAME="java.util.logging.StreamHandler.close_changed()"></A>
<nobr><code>void</code> <A HREF="../../../../reference/java/util/logging/StreamHandler.html#close()" target="_top"><code>close</code></A>() </nobr>
</TD>
<TD VALIGN="TOP" WIDTH="30%">
Change in exceptions thrown from no exceptions to <code>java.lang.SecurityException</code>.<br>
</TD>
<TD> </TD>
</TR>
<TR BGCOLOR="#FFFFFF" CLASS="TableRowColor">
<TD VALIGN="TOP" WIDTH="25%">
<A NAME="java.util.logging.StreamHandler.setOutputStream_changed(java.io.OutputStream)"></A>
<nobr><code>void</code> <A HREF="../../../../reference/java/util/logging/StreamHandler.html#setOutputStream(java.io.OutputStream)" target="_top"><code>setOutputStream</code></A>(<code>OutputStream</code>) </nobr>
</TD>
<TD VALIGN="TOP" WIDTH="30%">
Change in exceptions thrown from no exceptions to <code>java.lang.SecurityException</code>.<br>
</TD>
<TD> </TD>
</TR>
</TABLE>
<a NAME="fields"></a>
</div>
<div id="footer">
<div id="copyright">
Except as noted, this content is licensed under
<a href="//creativecommons.org/licenses/by/2.5/"> Creative Commons Attribution 2.5</a>.
For details and restrictions, see the <a href="/license.html">Content License</a>.
</div>
<div id="footerlinks">
<p>
<a href="//www.android.com/terms.html">Site Terms of Service</a> -
<a href="//www.android.com/privacy.html">Privacy Policy</a> -
<a href="//www.android.com/branding.html">Brand Guidelines</a>
</p>
</div>
</div> <!-- end footer -->
</div><!-- end doc-content -->
</div> <!-- end body-content -->
<script src="//www.google-analytics.com/ga.js" type="text/javascript">
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-5831155-1");
pageTracker._setAllowAnchor(true);
pageTracker._initData();
pageTracker._trackPageview();
} catch(e) {}
</script>
</BODY>
</HTML>
|
apache-2.0
|
AlanJager/zstack
|
header/src/main/java/org/zstack/header/network/service/VirtualRouterAfterDetachNicExtensionPoint.java
|
243
|
package org.zstack.header.network.service;
import org.zstack.header.vm.VmNicInventory;
/**
* Created by yaohua.wu on 8/14/2019.
*/
public interface VirtualRouterAfterDetachNicExtensionPoint {
void afterDetachNic(VmNicInventory nic);
}
|
apache-2.0
|
seggcsont/HiitTimerWeb
|
public/editTraining.html
|
2008
|
<div class="row">
<div class="panel panel-default">
<h2>{{ training.title }}</h2>
<span class="text-danger not_remove" ng-show="is_changed">
Training has been changed! Don't forget to save it.
<button class="btn btn-danger btn-sm" type="button" ng-click="save()">Save</button>
</span>
<table class="table table-striped">
<thead>
<tr>
<th class="">Title</th>
<th class="text-center">Duration (sec)</th>
<th class="text-right">Actions</th>
</tr>
</thead>
<tr ng-repeat="exercise in training.exercises">
<td class="">
<label>{{ exercise.title }}</label>
</td>
<td class="text-center">
<label>{{ exercise.duration }}</label>
</td>
<td class="action-buttons">
<div class="btn-group pull-right">
<button class="btn btn-default" type="button" ng-disabled="$first" ng-click="moveUp($index)">
<span class="glyphicon glyphicon-arrow-up" aria-hidden="true"></span>
</button>
<button class="btn btn-default" type="button" ng-disabled="$last" ng-click="moveDown($index)">
<span class="glyphicon glyphicon-arrow-down" aria-hidden="true"></span>
</button>
<button class="btn btn-default" type="button" ng-click="deleteExercise($index)">
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
</button>
</div>
</td>
</tr>
<tr>
<td colspan="3">
<form class="table-row-form form-inline">
<input class="form-control" type="text" ng-model="formData.exercise.title" placeholder="Exercise name">
<input class="form-control" type="number" ng-model="formData.exercise.duration" placeholder="duration">
<button class="btn btn-default" type="button" ng-click="addExercise()">Add</button>
</form>
</td>
</tr>
</table>
</div>
</div>
|
apache-2.0
|
Tealium/nagios
|
recipes/pagerduty.rb
|
2473
|
#
# Author:: Jake Vanderdray <[email protected]>
# Cookbook Name:: nagios
# Recipe:: pagerduty
#
# Copyright 2011, CustomInk LLC
#
# 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 "libwww-perl" do
case node["platform"]
when "redhat", "centos", "scientific", "fedora", "suse", "amazon"
package_name "perl-libwww-perl"
when "debian","ubuntu"
package_name "libwww-perl"
when "arch"
package_name "libwww-perl"
end
action :install
end
package "libcrypt-ssleay-perl" do
case node["platform"]
when "redhat", "centos", "scientific", "fedora", "suse", "amazon"
package_name "perl-Crypt-SSLeay"
when "debian","ubuntu"
package_name "libcrypt-ssleay-perl"
when "arch"
package_name "libcrypt-ssleay-perl"
end
action :install
end
# need to support
# multi-region VPC and non VPC for our not fully VPC prod env
# multi-region VPC for private clouds (currently single region, but could become multi sometime)
api_key = ''
if node['instance_role'] == 'vagrant'
api_key = "test"
else
# we really only want to do this for prod
region = node['ec2']['region']
# if its private only, its VPC so tack that on
unless node['cloud']['public_ipv4'].nil?
region = "#{region}-nonvpc"
end
key_bag = data_bag_item('pager_duty', node['app_environment'])
api_key = key_bag['keys'][region]
end
template "/etc/nagios3/conf.d/pagerduty_nagios.cfg" do
owner "nagios"
group "nagios"
mode 0644
source "pagerduty_nagios.cfg.erb"
variables :api_key => api_key
end
remote_file "#{node['nagios']['plugin_dir']}/pagerduty_nagios.pl" do
owner "root"
group "root"
mode 0755
source "https://raw.github.com/PagerDuty/pagerduty-nagios-pl/master/pagerduty_nagios.pl"
action :create_if_missing
end
cron "Flush Pagerduty" do
user "nagios"
command "#{node['nagios']['plugin_dir']}/pagerduty_nagios.pl flush"
minute "*"
hour "*"
day "*"
month "*"
weekday "*"
action :create
end
|
apache-2.0
|
swetland/m3dev
|
arch/arm-cm3/include/arch/cpu.h
|
308
|
#ifndef _CPU_H_
#define _CPU_H_
static inline void disable_interrupts(void) {
asm("cpsid i" : : : "memory");
}
static inline void enable_interrupts(void) {
asm("cpsie i" : : : "memory");
}
void irq_enable(unsigned n);
void irq_disable(unsigned n);
void irq_set_base(unsigned vector_table_addr);
#endif
|
apache-2.0
|
adaptris/interlok
|
interlok-core/src/test/java/com/adaptris/core/stubs/MockMessageProducer.java
|
3368
|
/*
* Copyright 2015 Adaptris Ltd.
*
* 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.adaptris.core.stubs;
import java.util.ArrayList;
import java.util.List;
import com.adaptris.core.AdaptrisMessage;
import com.adaptris.core.ClosedState;
import com.adaptris.core.ComponentState;
import com.adaptris.core.CoreException;
import com.adaptris.core.InitialisedState;
import com.adaptris.core.ProduceException;
import com.adaptris.core.ProduceOnlyProducerImp;
import com.adaptris.core.StartedState;
import com.adaptris.core.StateManagedComponent;
import com.adaptris.core.StoppedState;
import com.adaptris.interlok.util.Args;
/**
* <p>
* Mock implementation of <code>AdaptrisMessageProducer</code> for testing.
* Produces messages to a List which can be retrieved, thus allowing messages to
* be verified as split, etc., etc.
* </p>
*/
public class MockMessageProducer extends ProduceOnlyProducerImp implements
StateManagedComponent, MessageCounter {
private transient List<AdaptrisMessage> producedMessages;
private transient ComponentState state = ClosedState.getInstance();
public MockMessageProducer() {
producedMessages = new ArrayList<AdaptrisMessage>();
}
@Override
protected void doProduce(AdaptrisMessage msg, String endpoint) throws ProduceException {
Args.notNull(msg, "message");
producedMessages.add(msg);
}
@Override
public void prepare() throws CoreException {
}
/**
* <p>
* Returns the internal store of produced messages.
* </p>
*
* @return the internal store of produced messages
*/
@Override
public List<AdaptrisMessage> getMessages() {
return producedMessages;
}
@Override
public int messageCount() {
return producedMessages.size();
}
@Override
public void init() throws CoreException {
state = InitialisedState.getInstance();
}
@Override
public void start() throws CoreException {
state = StartedState.getInstance();
}
@Override
public void stop() {
state = StoppedState.getInstance();
}
@Override
public void close() {
state = ClosedState.getInstance();
}
@Override
public void changeState(ComponentState newState) {
state = newState;
}
@Override
public String getUniqueId() {
// TODO Auto-generated method stub
return null;
}
@Override
public void requestClose() {
state.requestClose(this);
}
@Override
public void requestInit() throws CoreException {
state.requestInit(this);
}
@Override
public void requestStart() throws CoreException {
state.requestStart(this);
}
@Override
public void requestStop() {
state.requestStop(this);
}
@Override
public ComponentState retrieveComponentState() {
return state;
}
@Override
public String endpoint(AdaptrisMessage msg) throws ProduceException {
return null;
}
}
|
apache-2.0
|
MAnbar/SearchEngine
|
Crawler/src/crawler/Main.java
|
5900
|
package crawler;
import java.beans.PropertyVetoException;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) throws SQLException, IOException, PropertyVetoException, InterruptedException
{
DatabaseManager MyDB=new DatabaseManager();//Create DB Object
Scanner sc =new Scanner(System.in);
BufferedReader consolereader = new BufferedReader (new InputStreamReader(System.in));
int X;
String InputRURL="";//RURL stands for restricted URL
do{//First Option List
//to store the user choice
System.out.println("Enter:\n1. to Add Restircted URLS \n2. to Start Crawling/Indexing \n3. to Reset Data \n4. to Exit \n>>");
X=sc.nextInt();
//Add Restricted URLs
if(X==1)
{
System.out.println("Enter a URL to Restrict:");
InputRURL=consolereader.readLine();
if(!MyDB.CheckRURL(InputRURL))//to make sure that that URL has not been added to the restricted URLs already
{
MyDB.AddRURL(InputRURL);
}
else
{
System.out.println("URL is Already Restricted");
}
}
//Reset data
else if(X==3)
{//Confirmation Check
System.out.println("Are You Sure You Want To Reset All Data (Enter 'reset' to confirm):");
if(consolereader.readLine().equals("reset"))
{
int MaxDownloadedID =MyDB.GetMaxDownloadedID();
try{
for(int i=1;i<=MaxDownloadedID;i++)
{
File file = new File(i+".html");
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}
}catch(Exception e){
e.printStackTrace();
}
MyDB.ResetDB();
System.out.println("Data Reseted");
}
else
{
System.out.println("Reset Aborted");
}
}
else if (X==4)
{
return;
}
}while(X!=2);
//Start crawling/indexing
System.out.println("Enter the Number of Crawler Threads (20 Max): ");
int ThreadNumber=sc.nextInt();
MyDB.AddSeeds();
//Run Crawlers
Thread[] CThreadArray=new Thread[ThreadNumber];
Thread[] IThreadArray=new Thread[20];
for(int i =0;i<ThreadNumber;i++)
{//Start Crawler Threads And Name Them
CThreadArray[i] = new Crawler(MyDB);
CThreadArray[i].setName ("Crawler "+ i);
}
for(int i=0;i<20;i++)
{
IThreadArray[i] =new Indexer(MyDB);
IThreadArray[i].setName("Indexer"+ i);
}
//System.out.println("Enter the 1 to Recrawl, 2 to Stop the Crawler \n>>");
for(int i =0;i<ThreadNumber;i++)
{//Start Crawler Threads And Name Them
CThreadArray[i].start();
}
for(int i=0;i<20;i++)
{
IThreadArray[i].start();
}
//Start Indexer Thread
do{//Second Option List (Available After Running The Crawlers)
System.out.println("Enter the 1 to Recrawl, 2 to Stop the Crawler \n>>");
X=sc.nextInt();
if(X==1)
{
MyDB.Recrawl();
System.out.println("Recrawling Successful");
}
else if (X==2)
{//Interrupt All Threads
System.out.println("Terminating Threads...Please Wait");
for(int i =0;i<ThreadNumber;i++)
{
CThreadArray[i].interrupt();
}
for(int i=0;i<20;i++)
{
IThreadArray[i].interrupt();
}
for(int i =0;i<ThreadNumber;i++)
{
CThreadArray[i].join();
}
for(int i=0;i<20;i++)
{
IThreadArray[i].join();
}
}
}while(X!=2);
System.out.println("Main Thread Terminated..");
}
// public static void main(String[] args) throws SQLException, IOException, PropertyVetoException, InterruptedException
// {
// DatabaseManager MyDB=new DatabaseManager();//Create DB Object
// Ranker R=new Ranker(MyDB,1);
// String W="gggfgfgfyfyfuhjhi game";
// ArrayList<URStruct> List=R.GetURLRankings(W);
//
// for(int i=0;i<List.size();i++)
// {
// System.out.println("URL: "+List.get(i).URL+" IF: "+List.get(i).IR);
// }
// }
// public static void main(String[] args) throws SQLException, IOException, PropertyVetoException, InterruptedException
// {
// DatabaseManager MyDB=new DatabaseManager();
// Scanner sc =new Scanner(System.in);
// BufferedReader consolereader = new BufferedReader (new InputStreamReader(System.in));
//
// String Word=consolereader.readLine();
// QueryProcessor QP = new QueryProcessor(Word,MyDB,1);
// ArrayList<ResultStruct> PTemp=new ArrayList<ResultStruct>();
// PTemp=QP.ProcessQuery(Word);
// if(PTemp==null)
// {
// System.out.println("Phrase Not Found");
// return;
// }
// for(int i=0;i<PTemp.size();i++)
// {
// System.out.println(PTemp.get(i).UID+" "+PTemp.get(i).URL+" "+PTemp.get(i).Rating);
// }
////System.out.println(QP.Stem("Footballers"));
// }
}
|
apache-2.0
|
amida-tech/blue-button-model
|
test/samples/unit/cda_email.js
|
320
|
"use strict";
var samples = {};
module.exports = samples;
samples.valid_0 = {
"address": "[email protected]",
"type": "work place"
};
samples.valid_1 = {
"address": "[email protected]"
};
samples.invalid_0 = {};
samples.invalid_1 = {
"address": "[email protected]",
"type": "work place",
"other": "na"
};
|
apache-2.0
|
chinhnc/floodlight
|
lib/apache-jena-2.10.1/javadoc-core/com/hp/hpl/jena/reasoner/rulesys/RuleContext.html
|
17319
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_21) on Sat May 11 22:07:15 BST 2013 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>RuleContext (Apache Jena)</title>
<meta name="date" content="2013-05-11">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="RuleContext (Apache Jena)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/RuleContext.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../com/hp/hpl/jena/reasoner/rulesys/Rule.ParserException.html" title="class in com.hp.hpl.jena.reasoner.rulesys"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../../com/hp/hpl/jena/reasoner/rulesys/RuleDerivation.html" title="class in com.hp.hpl.jena.reasoner.rulesys"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/hp/hpl/jena/reasoner/rulesys/RuleContext.html" target="_top">Frames</a></li>
<li><a href="RuleContext.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">com.hp.hpl.jena.reasoner.rulesys</div>
<h2 title="Interface RuleContext" class="title">Interface RuleContext</h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public interface <span class="strong">RuleContext</span></pre>
<div class="block">Interface used to convey context information from a rule engine
to the stack of procedural builtins. This gives access
to the triggering rule, the variable bindings and the set of
currently known triples.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/hp/hpl/jena/reasoner/rulesys/RuleContext.html#add(com.hp.hpl.jena.graph.Triple)">add</a></strong>(<a href="../../../../../../com/hp/hpl/jena/graph/Triple.html" title="class in com.hp.hpl.jena.graph">Triple</a> t)</code>
<div class="block">Assert a new triple in the deduction graph, triggering any consequent processing as appropriate.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/hp/hpl/jena/reasoner/rulesys/RuleContext.html#contains(com.hp.hpl.jena.graph.Node, com.hp.hpl.jena.graph.Node, com.hp.hpl.jena.graph.Node)">contains</a></strong>(<a href="../../../../../../com/hp/hpl/jena/graph/Node.html" title="class in com.hp.hpl.jena.graph">Node</a> s,
<a href="../../../../../../com/hp/hpl/jena/graph/Node.html" title="class in com.hp.hpl.jena.graph">Node</a> p,
<a href="../../../../../../com/hp/hpl/jena/graph/Node.html" title="class in com.hp.hpl.jena.graph">Node</a> o)</code>
<div class="block">Return true if the triple pattern is already in either the graph or the stack.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/hp/hpl/jena/reasoner/rulesys/RuleContext.html#contains(com.hp.hpl.jena.graph.Triple)">contains</a></strong>(<a href="../../../../../../com/hp/hpl/jena/graph/Triple.html" title="class in com.hp.hpl.jena.graph">Triple</a> t)</code>
<div class="block">Return true if the triple is already in either the graph or the stack.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>com.hp.hpl.jena.util.iterator.ClosableIterator<<a href="../../../../../../com/hp/hpl/jena/graph/Triple.html" title="class in com.hp.hpl.jena.graph">Triple</a>></code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/hp/hpl/jena/reasoner/rulesys/RuleContext.html#find(com.hp.hpl.jena.graph.Node, com.hp.hpl.jena.graph.Node, com.hp.hpl.jena.graph.Node)">find</a></strong>(<a href="../../../../../../com/hp/hpl/jena/graph/Node.html" title="class in com.hp.hpl.jena.graph">Node</a> s,
<a href="../../../../../../com/hp/hpl/jena/graph/Node.html" title="class in com.hp.hpl.jena.graph">Node</a> p,
<a href="../../../../../../com/hp/hpl/jena/graph/Node.html" title="class in com.hp.hpl.jena.graph">Node</a> o)</code>
<div class="block">In some formulations the context includes deductions that are not yet
visible to the underlying graph but need to be checked for.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../com/hp/hpl/jena/reasoner/rulesys/BindingEnvironment.html" title="interface in com.hp.hpl.jena.reasoner.rulesys">BindingEnvironment</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/hp/hpl/jena/reasoner/rulesys/RuleContext.html#getEnv()">getEnv</a></strong>()</code>
<div class="block">Returns the current variable binding environment for the current rule.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../../com/hp/hpl/jena/reasoner/InfGraph.html" title="interface in com.hp.hpl.jena.reasoner">InfGraph</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/hp/hpl/jena/reasoner/rulesys/RuleContext.html#getGraph()">getGraph</a></strong>()</code>
<div class="block">Returns the parent inference graph.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../com/hp/hpl/jena/reasoner/rulesys/Rule.html" title="class in com.hp.hpl.jena.reasoner.rulesys">Rule</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/hp/hpl/jena/reasoner/rulesys/RuleContext.html#getRule()">getRule</a></strong>()</code>
<div class="block">Returns the rule.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/hp/hpl/jena/reasoner/rulesys/RuleContext.html#remove(com.hp.hpl.jena.graph.Triple)">remove</a></strong>(<a href="../../../../../../com/hp/hpl/jena/graph/Triple.html" title="class in com.hp.hpl.jena.graph">Triple</a> t)</code>
<div class="block">Remove a triple from the deduction graph (and the original graph if relevant).</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/hp/hpl/jena/reasoner/rulesys/RuleContext.html#setRule(com.hp.hpl.jena.reasoner.rulesys.Rule)">setRule</a></strong>(<a href="../../../../../../com/hp/hpl/jena/reasoner/rulesys/Rule.html" title="class in com.hp.hpl.jena.reasoner.rulesys">Rule</a> rule)</code>
<div class="block">Sets the rule.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/hp/hpl/jena/reasoner/rulesys/RuleContext.html#silentAdd(com.hp.hpl.jena.graph.Triple)">silentAdd</a></strong>(<a href="../../../../../../com/hp/hpl/jena/graph/Triple.html" title="class in com.hp.hpl.jena.graph">Triple</a> t)</code>
<div class="block">Assert a new triple in the deduction graph, bypassing any processing machinery.</div>
</td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="getEnv()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getEnv</h4>
<pre><a href="../../../../../../com/hp/hpl/jena/reasoner/rulesys/BindingEnvironment.html" title="interface in com.hp.hpl.jena.reasoner.rulesys">BindingEnvironment</a> getEnv()</pre>
<div class="block">Returns the current variable binding environment for the current rule.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>BindingEnvironment</dd></dl>
</li>
</ul>
<a name="getGraph()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getGraph</h4>
<pre><a href="../../../../../../com/hp/hpl/jena/reasoner/InfGraph.html" title="interface in com.hp.hpl.jena.reasoner">InfGraph</a> getGraph()</pre>
<div class="block">Returns the parent inference graph.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>InfGraph</dd></dl>
</li>
</ul>
<a name="getRule()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getRule</h4>
<pre><a href="../../../../../../com/hp/hpl/jena/reasoner/rulesys/Rule.html" title="class in com.hp.hpl.jena.reasoner.rulesys">Rule</a> getRule()</pre>
<div class="block">Returns the rule.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>Rule</dd></dl>
</li>
</ul>
<a name="setRule(com.hp.hpl.jena.reasoner.rulesys.Rule)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setRule</h4>
<pre>void setRule(<a href="../../../../../../com/hp/hpl/jena/reasoner/rulesys/Rule.html" title="class in com.hp.hpl.jena.reasoner.rulesys">Rule</a> rule)</pre>
<div class="block">Sets the rule.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>rule</code> - The rule to set</dd></dl>
</li>
</ul>
<a name="contains(com.hp.hpl.jena.graph.Triple)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>contains</h4>
<pre>boolean contains(<a href="../../../../../../com/hp/hpl/jena/graph/Triple.html" title="class in com.hp.hpl.jena.graph">Triple</a> t)</pre>
<div class="block">Return true if the triple is already in either the graph or the stack.
I.e. it has already been deduced.</div>
</li>
</ul>
<a name="contains(com.hp.hpl.jena.graph.Node, com.hp.hpl.jena.graph.Node, com.hp.hpl.jena.graph.Node)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>contains</h4>
<pre>boolean contains(<a href="../../../../../../com/hp/hpl/jena/graph/Node.html" title="class in com.hp.hpl.jena.graph">Node</a> s,
<a href="../../../../../../com/hp/hpl/jena/graph/Node.html" title="class in com.hp.hpl.jena.graph">Node</a> p,
<a href="../../../../../../com/hp/hpl/jena/graph/Node.html" title="class in com.hp.hpl.jena.graph">Node</a> o)</pre>
<div class="block">Return true if the triple pattern is already in either the graph or the stack.
I.e. it has already been deduced.</div>
</li>
</ul>
<a name="find(com.hp.hpl.jena.graph.Node, com.hp.hpl.jena.graph.Node, com.hp.hpl.jena.graph.Node)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>find</h4>
<pre>com.hp.hpl.jena.util.iterator.ClosableIterator<<a href="../../../../../../com/hp/hpl/jena/graph/Triple.html" title="class in com.hp.hpl.jena.graph">Triple</a>> find(<a href="../../../../../../com/hp/hpl/jena/graph/Node.html" title="class in com.hp.hpl.jena.graph">Node</a> s,
<a href="../../../../../../com/hp/hpl/jena/graph/Node.html" title="class in com.hp.hpl.jena.graph">Node</a> p,
<a href="../../../../../../com/hp/hpl/jena/graph/Node.html" title="class in com.hp.hpl.jena.graph">Node</a> o)</pre>
<div class="block">In some formulations the context includes deductions that are not yet
visible to the underlying graph but need to be checked for.</div>
</li>
</ul>
<a name="silentAdd(com.hp.hpl.jena.graph.Triple)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>silentAdd</h4>
<pre>void silentAdd(<a href="../../../../../../com/hp/hpl/jena/graph/Triple.html" title="class in com.hp.hpl.jena.graph">Triple</a> t)</pre>
<div class="block">Assert a new triple in the deduction graph, bypassing any processing machinery.</div>
</li>
</ul>
<a name="add(com.hp.hpl.jena.graph.Triple)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>add</h4>
<pre>void add(<a href="../../../../../../com/hp/hpl/jena/graph/Triple.html" title="class in com.hp.hpl.jena.graph">Triple</a> t)</pre>
<div class="block">Assert a new triple in the deduction graph, triggering any consequent processing as appropriate.</div>
</li>
</ul>
<a name="remove(com.hp.hpl.jena.graph.Triple)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>remove</h4>
<pre>void remove(<a href="../../../../../../com/hp/hpl/jena/graph/Triple.html" title="class in com.hp.hpl.jena.graph">Triple</a> t)</pre>
<div class="block">Remove a triple from the deduction graph (and the original graph if relevant).</div>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/RuleContext.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../com/hp/hpl/jena/reasoner/rulesys/Rule.ParserException.html" title="class in com.hp.hpl.jena.reasoner.rulesys"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../../com/hp/hpl/jena/reasoner/rulesys/RuleDerivation.html" title="class in com.hp.hpl.jena.reasoner.rulesys"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/hp/hpl/jena/reasoner/rulesys/RuleContext.html" target="_top">Frames</a></li>
<li><a href="RuleContext.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Licenced under the Apache License, Version 2.0</small></p>
</body>
</html>
|
apache-2.0
|
mdoering/backbone
|
life/Fungi/Ascomycota/Eurotiomycetes/Eurotiales/Trichocomaceae/Penicillium/Penicillium inusitatum/README.md
|
264
|
# Penicillium inusitatum D.B. Scott, 1968 SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Mycopath. Mycol. appl. 36: 20 (1968)
#### Original name
Penicillium inusitatum D.B. Scott, 1968
### Remarks
null
|
apache-2.0
|
nodekit-io/nodekit-windows
|
src/nodekit/NKScripting/common/engines/chakra/Engine/Native_uwp.cs
|
24924
|
#if WINDOWS_UWP
namespace io.nodekit.NKScripting.Engines.Chakra
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
/// <summary>
/// Native interfaces.
/// </summary>
public static class Native
{
/// <summary>
/// Throws if a native method returns an error code.
/// </summary>
/// <param name="error">The error.</param>
internal static void ThrowIfError(JavaScriptErrorCode error)
{
if (error != JavaScriptErrorCode.NoError)
{
switch (error)
{
case JavaScriptErrorCode.InvalidArgument:
throw new JavaScriptUsageException(error, "Invalid argument.");
case JavaScriptErrorCode.NullArgument:
throw new JavaScriptUsageException(error, "Null argument.");
case JavaScriptErrorCode.NoCurrentContext:
throw new JavaScriptUsageException(error, "No current context.");
case JavaScriptErrorCode.InExceptionState:
throw new JavaScriptUsageException(error, "Runtime is in exception state.");
case JavaScriptErrorCode.NotImplemented:
throw new JavaScriptUsageException(error, "Method is not implemented.");
case JavaScriptErrorCode.WrongThread:
throw new JavaScriptUsageException(error, "Runtime is active on another thread.");
case JavaScriptErrorCode.RuntimeInUse:
throw new JavaScriptUsageException(error, "Runtime is in use.");
case JavaScriptErrorCode.BadSerializedScript:
throw new JavaScriptUsageException(error, "Bad serialized script.");
case JavaScriptErrorCode.InDisabledState:
throw new JavaScriptUsageException(error, "Runtime is disabled.");
case JavaScriptErrorCode.CannotDisableExecution:
throw new JavaScriptUsageException(error, "Cannot disable execution.");
case JavaScriptErrorCode.AlreadyDebuggingContext:
throw new JavaScriptUsageException(error, "Context is already in debug mode.");
case JavaScriptErrorCode.HeapEnumInProgress:
throw new JavaScriptUsageException(error, "Heap enumeration is in progress.");
case JavaScriptErrorCode.ArgumentNotObject:
throw new JavaScriptUsageException(error, "Argument is not an object.");
case JavaScriptErrorCode.InProfileCallback:
throw new JavaScriptUsageException(error, "In a profile callback.");
case JavaScriptErrorCode.InThreadServiceCallback:
throw new JavaScriptUsageException(error, "In a thread service callback.");
case JavaScriptErrorCode.CannotSerializeDebugScript:
throw new JavaScriptUsageException(error, "Cannot serialize a debug script.");
case JavaScriptErrorCode.AlreadyProfilingContext:
throw new JavaScriptUsageException(error, "Already profiling this context.");
case JavaScriptErrorCode.IdleNotEnabled:
throw new JavaScriptUsageException(error, "Idle is not enabled.");
case JavaScriptErrorCode.OutOfMemory:
throw new JavaScriptEngineException(error, "Out of memory.");
case JavaScriptErrorCode.ScriptException:
{
JavaScriptValue errorObject;
JavaScriptErrorCode innerError = JsGetAndClearException(out errorObject);
if (innerError != JavaScriptErrorCode.NoError)
{
throw new JavaScriptFatalException(innerError);
}
throw new JavaScriptScriptException(error, errorObject, "Script threw an exception.");
}
case JavaScriptErrorCode.ScriptCompile:
{
JavaScriptValue errorObject;
JavaScriptErrorCode innerError = JsGetAndClearException(out errorObject);
if (innerError != JavaScriptErrorCode.NoError)
{
throw new JavaScriptFatalException(innerError);
}
throw new JavaScriptScriptException(error, errorObject, "Compile error.");
}
case JavaScriptErrorCode.ScriptTerminated:
throw new JavaScriptScriptException(error, JavaScriptValue.Invalid, "Script was terminated.");
case JavaScriptErrorCode.ScriptEvalDisabled:
throw new JavaScriptScriptException(error, JavaScriptValue.Invalid, "Eval of strings is disabled in this runtime.");
case JavaScriptErrorCode.Fatal:
throw new JavaScriptFatalException(error);
default:
throw new JavaScriptFatalException(error);
}
}
}
const string DllName = "Chakra.dll";
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateRuntime(JavaScriptRuntimeAttributes attributes, JavaScriptThreadServiceCallback threadService, out JavaScriptRuntime runtime);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCollectGarbage(JavaScriptRuntime handle);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsDisposeRuntime(JavaScriptRuntime handle);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetRuntimeMemoryUsage(JavaScriptRuntime runtime, out UIntPtr memoryUsage);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetRuntimeMemoryLimit(JavaScriptRuntime runtime, out UIntPtr memoryLimit);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsSetRuntimeMemoryLimit(JavaScriptRuntime runtime, UIntPtr memoryLimit);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsSetRuntimeMemoryAllocationCallback(JavaScriptRuntime runtime, IntPtr callbackState, JavaScriptMemoryAllocationCallback allocationCallback);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsSetRuntimeBeforeCollectCallback(JavaScriptRuntime runtime, IntPtr callbackState, JavaScriptBeforeCollectCallback beforeCollectCallback);
[DllImport(DllName, EntryPoint = "JsAddRef")]
internal static extern JavaScriptErrorCode JsContextAddRef(JavaScriptContext reference, out uint count);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsAddRef(JavaScriptValue reference, out uint count);
[DllImport(DllName, EntryPoint = "JsRelease")]
internal static extern JavaScriptErrorCode JsContextRelease(JavaScriptContext reference, out uint count);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsRelease(JavaScriptValue reference, out uint count);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateContext(JavaScriptRuntime runtime, out JavaScriptContext newContext);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetCurrentContext(out JavaScriptContext currentContext);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsSetCurrentContext(JavaScriptContext context);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetRuntime(JavaScriptContext context, out JavaScriptRuntime runtime);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsStartDebugging();
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsIdle(out uint nextIdleTick);
[DllImport(DllName, CharSet = CharSet.Unicode)]
internal static extern JavaScriptErrorCode JsParseScript(string script, JavaScriptSourceContext sourceContext, string sourceUrl, out JavaScriptValue result);
[DllImport(DllName, CharSet = CharSet.Unicode)]
internal static extern JavaScriptErrorCode JsRunScript(string script, JavaScriptSourceContext sourceContext, string sourceUrl, out JavaScriptValue result);
[DllImport(DllName, CharSet = CharSet.Unicode)]
internal static extern JavaScriptErrorCode JsSerializeScript(string script, byte[] buffer, ref ulong bufferSize);
[DllImport(DllName, CharSet = CharSet.Unicode)]
internal static extern JavaScriptErrorCode JsParseSerializedScript(string script, byte[] buffer, JavaScriptSourceContext sourceContext, string sourceUrl, out JavaScriptValue result);
[DllImport(DllName, CharSet = CharSet.Unicode)]
internal static extern JavaScriptErrorCode JsRunSerializedScript(string script, byte[] buffer, JavaScriptSourceContext sourceContext, string sourceUrl, out JavaScriptValue result);
[DllImport(DllName, CharSet = CharSet.Unicode)]
internal static extern JavaScriptErrorCode JsGetPropertyIdFromName(string name, out JavaScriptPropertyId propertyId);
[DllImport(DllName, CharSet = CharSet.Unicode)]
internal static extern JavaScriptErrorCode JsGetPropertyNameFromId(JavaScriptPropertyId propertyId, out string name);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetUndefinedValue(out JavaScriptValue undefinedValue);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetNullValue(out JavaScriptValue nullValue);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetTrueValue(out JavaScriptValue trueValue);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetFalseValue(out JavaScriptValue falseValue);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsBoolToBoolean(bool value, out JavaScriptValue booleanValue);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsBooleanToBool(JavaScriptValue booleanValue, out bool boolValue);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsConvertValueToBoolean(JavaScriptValue value, out JavaScriptValue booleanValue);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetValueType(JavaScriptValue value, out JavaScriptValueType type);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsDoubleToNumber(double doubleValue, out JavaScriptValue value);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsIntToNumber(int intValue, out JavaScriptValue value);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsNumberToDouble(JavaScriptValue value, out double doubleValue);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsConvertValueToNumber(JavaScriptValue value, out JavaScriptValue numberValue);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetStringLength(JavaScriptValue sringValue, out int length);
[DllImport(DllName, CharSet = CharSet.Unicode)]
internal static extern JavaScriptErrorCode JsPointerToString(string value, UIntPtr stringLength, out JavaScriptValue stringValue);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsStringToPointer(JavaScriptValue value, out IntPtr stringValue, out UIntPtr stringLength);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsConvertValueToString(JavaScriptValue value, out JavaScriptValue stringValue);
[DllImport(DllName)]
#pragma warning disable CS0618 // Type or member is obsolete
internal static extern JavaScriptErrorCode JsVariantToValue([MarshalAs(UnmanagedType.Struct)] ref object var, out JavaScriptValue value);
#pragma warning restore CS0618 // Type or member is obsolete
[DllImport(DllName)]
#pragma warning disable CS0618 // Type or member is obsolete
internal static extern JavaScriptErrorCode JsValueToVariant(JavaScriptValue obj, [MarshalAs(UnmanagedType.Struct)] out object var);
#pragma warning restore CS0618 // Type or member is obsolete
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetGlobalObject(out JavaScriptValue globalObject);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateObject(out JavaScriptValue obj);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateExternalObject(IntPtr data, JavaScriptObjectFinalizeCallback finalizeCallback, out JavaScriptValue obj);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsConvertValueToObject(JavaScriptValue value, out JavaScriptValue obj);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetPrototype(JavaScriptValue obj, out JavaScriptValue prototypeObject);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsSetPrototype(JavaScriptValue obj, JavaScriptValue prototypeObject);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetExtensionAllowed(JavaScriptValue obj, out bool value);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsPreventExtension(JavaScriptValue obj);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetProperty(JavaScriptValue obj, JavaScriptPropertyId propertyId, out JavaScriptValue value);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetOwnPropertyDescriptor(JavaScriptValue obj, JavaScriptPropertyId propertyId, out JavaScriptValue propertyDescriptor);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetOwnPropertyNames(JavaScriptValue obj, out JavaScriptValue propertyNames);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsSetProperty(JavaScriptValue obj, JavaScriptPropertyId propertyId, JavaScriptValue value, bool useStrictRules);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsHasProperty(JavaScriptValue obj, JavaScriptPropertyId propertyId, out bool hasProperty);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsDeleteProperty(JavaScriptValue obj, JavaScriptPropertyId propertyId, bool useStrictRules, out JavaScriptValue result);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsDefineProperty(JavaScriptValue obj, JavaScriptPropertyId propertyId, JavaScriptValue propertyDescriptor, out bool result);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsHasIndexedProperty(JavaScriptValue obj, JavaScriptValue index, out bool result);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetIndexedProperty(JavaScriptValue obj, JavaScriptValue index, out JavaScriptValue result);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsSetIndexedProperty(JavaScriptValue obj, JavaScriptValue index, JavaScriptValue value);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsDeleteIndexedProperty(JavaScriptValue obj, JavaScriptValue index);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsEquals(JavaScriptValue obj1, JavaScriptValue obj2, out bool result);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsStrictEquals(JavaScriptValue obj1, JavaScriptValue obj2, out bool result);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsHasExternalData(JavaScriptValue obj, out bool value);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetExternalData(JavaScriptValue obj, out IntPtr externalData);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsSetExternalData(JavaScriptValue obj, IntPtr externalData);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateArray(uint length, out JavaScriptValue result);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCallFunction(JavaScriptValue function, JavaScriptValue[] arguments, ushort argumentCount, out JavaScriptValue result);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsConstructObject(JavaScriptValue function, JavaScriptValue[] arguments, ushort argumentCount, out JavaScriptValue result);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateFunction(JavaScriptNativeFunction nativeFunction, IntPtr externalData, out JavaScriptValue function);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateError(JavaScriptValue message, out JavaScriptValue error);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateRangeError(JavaScriptValue message, out JavaScriptValue error);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateReferenceError(JavaScriptValue message, out JavaScriptValue error);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateSyntaxError(JavaScriptValue message, out JavaScriptValue error);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateTypeError(JavaScriptValue message, out JavaScriptValue error);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateURIError(JavaScriptValue message, out JavaScriptValue error);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsHasException(out bool hasException);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetAndClearException(out JavaScriptValue exception);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsSetException(JavaScriptValue exception);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsDisableRuntimeExecution(JavaScriptRuntime runtime);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsEnableRuntimeExecution(JavaScriptRuntime runtime);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsIsRuntimeExecutionDisabled(JavaScriptRuntime runtime, out bool isDisabled);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsSetObjectBeforeCollectCallback(JavaScriptValue reference, IntPtr callbackState, JavaScriptObjectBeforeCollectCallback beforeCollectCallback);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateNamedFunction(JavaScriptValue name, JavaScriptNativeFunction nativeFunction, IntPtr callbackState, out JavaScriptValue function);
[DllImport(DllName, CharSet = CharSet.Unicode)]
internal static extern JavaScriptErrorCode JsProjectWinRTNamespace(string namespaceName);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsInspectableToObject([MarshalAs(UnmanagedType.IInspectable)] System.Object inspectable, out JavaScriptValue value);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsSetProjectionEnqueueCallback(JavaScriptProjectionEnqueueCallback projectionEnqueueCallback, IntPtr context);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsSetPromiseContinuationCallback(JavaScriptPromiseContinuationCallback promiseContinuationCallback, IntPtr callbackState);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateArrayBuffer(uint byteLength, out JavaScriptValue result);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateTypedArray(JavaScriptTypedArrayType arrayType, JavaScriptValue arrayBuffer, uint byteOffset,
uint elementLength, out JavaScriptValue result);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateDataView(JavaScriptValue arrayBuffer, uint byteOffset, uint byteOffsetLength, out JavaScriptValue result);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetArrayBufferStorage(JavaScriptValue arrayBuffer, out byte[] buffer, out uint bufferLength);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetTypedArrayStorage(JavaScriptValue typedArray, out byte[] buffer, out uint bufferLength, out JavaScriptTypedArrayType arrayType, out int elementSize);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetDataViewStorage(JavaScriptValue dataView, out byte[] buffer, out uint bufferLength);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetPropertyIdType(JavaScriptPropertyId propertyId, out JavaSciptPropertyIdType propertyIdType);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateSymbol(JavaScriptValue description, out JavaScriptValue symbol);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetSymbolFromPropertyId(JavaScriptPropertyId propertyId, out JavaScriptValue symbol);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetPropertyIdFromSymbol(JavaScriptValue symbol, out JavaScriptPropertyId propertyId);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetOwnPropertySymbols(JavaScriptValue obj, out JavaScriptValue propertySymbols);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsNumberToInt(JavaScriptValue value, out int intValue);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsSetIndexedPropertiesToExternalData(JavaScriptValue obj, IntPtr data, JavaScriptTypedArrayType arrayType, uint elementLength);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetIndexedPropertiesExternalData(JavaScriptValue obj, IntPtr data, out JavaScriptTypedArrayType arrayType, out uint elementLength);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsHasIndexedPropertiesExternalData(JavaScriptValue obj, out bool value);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsInstanceOf(JavaScriptValue obj, JavaScriptValue constructor, out bool result);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsCreateExternalArrayBuffer(IntPtr data, uint byteLength, JavaScriptObjectFinalizeCallback finalizeCallback, IntPtr callbackState, out bool result);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetTypedArrayInfo(JavaScriptValue typedArray, out JavaScriptTypedArrayType arrayType, out JavaScriptValue arrayBuffer, out uint byteOffset, out uint byteLength);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetContextOfObject(JavaScriptValue obj, out JavaScriptContext context);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsGetContextData(JavaScriptContext context, out IntPtr data);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsSetContextData(JavaScriptContext context, IntPtr data);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsParseSerializedScriptWithCallback(JavaScriptSerializedScriptLoadSourceCallback scriptLoadCallback,
JavaScriptSerializedScriptUnloadCallback scriptUnloadCallback, byte[] buffer, JavaScriptSourceContext sourceContext, string sourceUrl, out JavaScriptValue result);
[DllImport(DllName)]
internal static extern JavaScriptErrorCode JsRunSerializedScriptWithCallback(JavaScriptSerializedScriptLoadSourceCallback scriptLoadCallback,
JavaScriptSerializedScriptUnloadCallback scriptUnloadCallback, byte[] buffer, JavaScriptSourceContext sourceContext, string sourceUrl, out JavaScriptValue result);
}
}
#endif
|
apache-2.0
|
Vilsol/NMSWrapper
|
src/main/java/me/vilsol/nmswrapper/wraps/unparsed/NMSCommandBlockListenerAbstract.java
|
5334
|
package me.vilsol.nmswrapper.wraps.unparsed;
import me.vilsol.nmswrapper.NMSWrapper;
import me.vilsol.nmswrapper.reflections.ReflectiveClass;
import me.vilsol.nmswrapper.reflections.ReflectiveMethod;
import me.vilsol.nmswrapper.wraps.NMSWrap;
import org.bukkit.command.CommandSender;
@ReflectiveClass(name = "CommandBlockListenerAbstract")
public class NMSCommandBlockListenerAbstract extends NMSWrap implements NMSICommandListener {
public NMSCommandBlockListenerAbstract(Object nmsObject){
super(nmsObject);
}
/**
* TODO Find correct name
* @see net.minecraft.server.v1_9_R1.CommandBlockListenerAbstract#a(net.minecraft.server.v1_9_R1.EntityHuman)
*/
@ReflectiveMethod(name = "a", types = {NMSEntityHuman.class})
public boolean a(NMSEntityHuman entityHuman){
return (boolean) NMSWrapper.getInstance().exec(nmsObject, entityHuman);
}
/**
* TODO Find correct name
* @see net.minecraft.server.v1_9_R1.CommandBlockListenerAbstract#b(net.minecraft.server.v1_9_R1.IChatBaseComponent)
*/
@ReflectiveMethod(name = "b", types = {NMSIChatBaseComponent.class})
public void b(NMSIChatBaseComponent iChatBaseComponent){
NMSWrapper.getInstance().exec(nmsObject, iChatBaseComponent);
}
/**
* @see net.minecraft.server.v1_9_R1.CommandBlockListenerAbstract#executeCommand(net.minecraft.server.v1_9_R1.ICommandListener, org.bukkit.command.CommandSender, java.lang.String)
*/
@ReflectiveMethod(name = "executeCommand", types = {NMSICommandListener.class, CommandSender.class, String.class})
public int executeCommand(NMSICommandListener iCommandListener, CommandSender commandSender, String s){
return (int) NMSWrapper.getInstance().exec(nmsObject, iCommandListener, commandSender, s);
}
/**
* @see net.minecraft.server.v1_9_R1.CommandBlockListenerAbstract#getCommand()
*/
@ReflectiveMethod(name = "getCommand", types = {})
public String getCommand(){
return (String) NMSWrapper.getInstance().exec(nmsObject);
}
/**
* @see net.minecraft.server.v1_9_R1.CommandBlockListenerAbstract#getName()
*/
@ReflectiveMethod(name = "getName", types = {})
public String getName(){
return (String) NMSWrapper.getInstance().exec(nmsObject);
}
/**
* @see net.minecraft.server.v1_9_R1.CommandBlockListenerAbstract#getScoreboardDisplayName()
*/
@ReflectiveMethod(name = "getScoreboardDisplayName", types = {})
public NMSIChatBaseComponent getScoreboardDisplayName(){
return (NMSIChatBaseComponent) NMSWrapper.getInstance().createApplicableObject(NMSWrapper.getInstance().exec(nmsObject));
}
/**
* @see net.minecraft.server.v1_9_R1.CommandBlockListenerAbstract#getSendCommandFeedback()
*/
@ReflectiveMethod(name = "getSendCommandFeedback", types = {})
public boolean getSendCommandFeedback(){
return (boolean) NMSWrapper.getInstance().exec(nmsObject);
}
/**
* TODO Find correct name
* @see net.minecraft.server.v1_9_R1.CommandBlockListenerAbstract#h()
*/
@ReflectiveMethod(name = "h", types = {})
public void h(){
NMSWrapper.getInstance().exec(nmsObject);
}
/**
* TODO Find correct name
* @see net.minecraft.server.v1_9_R1.CommandBlockListenerAbstract#j()
*/
@ReflectiveMethod(name = "j", types = {})
public int j(){
return (int) NMSWrapper.getInstance().exec(nmsObject);
}
/**
* TODO Find correct name
* @see net.minecraft.server.v1_9_R1.CommandBlockListenerAbstract#k()
*/
@ReflectiveMethod(name = "k", types = {})
public NMSIChatBaseComponent k(){
return (NMSIChatBaseComponent) NMSWrapper.getInstance().createApplicableObject(NMSWrapper.getInstance().exec(nmsObject));
}
/**
* TODO Find correct name
* @see net.minecraft.server.v1_9_R1.CommandBlockListenerAbstract#m()
*/
@ReflectiveMethod(name = "m", types = {})
public boolean m(){
return (boolean) NMSWrapper.getInstance().exec(nmsObject);
}
/**
* TODO Find correct name
* @see net.minecraft.server.v1_9_R1.CommandBlockListenerAbstract#n()
*/
@ReflectiveMethod(name = "n", types = {})
public NMSCommandObjectiveExecutor n(){
return new NMSCommandObjectiveExecutor(NMSWrapper.getInstance().exec(nmsObject));
}
/**
* @see net.minecraft.server.v1_9_R1.CommandBlockListenerAbstract#sendMessage(net.minecraft.server.v1_9_R1.IChatBaseComponent)
*/
@ReflectiveMethod(name = "sendMessage", types = {NMSIChatBaseComponent.class})
public void sendMessage(NMSIChatBaseComponent iChatBaseComponent){
NMSWrapper.getInstance().exec(nmsObject, iChatBaseComponent);
}
/**
* @see net.minecraft.server.v1_9_R1.CommandBlockListenerAbstract#setCommand(java.lang.String)
*/
@ReflectiveMethod(name = "setCommand", types = {String.class})
public void setCommand(String s){
NMSWrapper.getInstance().exec(nmsObject, s);
}
/**
* @see net.minecraft.server.v1_9_R1.CommandBlockListenerAbstract#setName(java.lang.String)
*/
@ReflectiveMethod(name = "setName", types = {String.class})
public void setName(String s){
NMSWrapper.getInstance().exec(nmsObject, s);
}
}
|
apache-2.0
|
duanzhenglong/xianchufang
|
xianchufang/xianchufang/Class/ShoppingCart/Controller/LJShoppingCartViewController.h
|
818
|
//
// LJFoodCircleViewController.h
// meishimeike
//
// Created by zhenglong duan on 11/02/2017.
// Copyright © 2017 zhenglong duan. All rights reserved.
//
#import "LJBaseViewController.h"
@interface LJShoppingCartViewController : LJBaseViewController
/*** 结算按钮 ***/
@property (nonatomic,strong) UIButton *settlementBtn;
/*** 金额L ***/
@property (nonatomic,strong) UILabel *priceLabel;
/*** 暂时计算的金额 ***/
@property (nonatomic,assign) CGFloat Allprice;
/*** 最终要结算的金额 ***/
@property (nonatomic,assign) CGFloat totalPrice;
/*** 合计一系列背景 ***/
@property (nonatomic,strong) UIView *view1;
/*** 底部标签栏 ***/
@property (nonatomic,strong) UIView *bottomViewBg;
/*** 是否从商品详情页面进入 ***/
@property (nonatomic,assign) BOOL isOtherPage;
@end
|
apache-2.0
|
glammedia/phoenix
|
phoenix-core/src/main/java/org/apache/phoenix/compile/DeleteCompiler.java
|
30200
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.phoenix.compile;
import java.sql.ParameterMetaData;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.phoenix.cache.ServerCacheClient.ServerCache;
import org.apache.phoenix.compile.GroupByCompiler.GroupBy;
import org.apache.phoenix.compile.OrderByCompiler.OrderBy;
import org.apache.phoenix.coprocessor.BaseScannerRegionObserver;
import org.apache.phoenix.coprocessor.MetaDataProtocol.MetaDataMutationResult;
import org.apache.phoenix.exception.SQLExceptionCode;
import org.apache.phoenix.exception.SQLExceptionInfo;
import org.apache.phoenix.execute.AggregatePlan;
import org.apache.phoenix.execute.BaseQueryPlan;
import org.apache.phoenix.execute.MutationState;
import org.apache.phoenix.filter.SkipScanFilter;
import org.apache.phoenix.hbase.index.util.ImmutableBytesPtr;
import org.apache.phoenix.index.IndexMetaDataCacheClient;
import org.apache.phoenix.index.PhoenixIndexCodec;
import org.apache.phoenix.iterate.ResultIterator;
import org.apache.phoenix.jdbc.PhoenixConnection;
import org.apache.phoenix.jdbc.PhoenixResultSet;
import org.apache.phoenix.jdbc.PhoenixStatement;
import org.apache.phoenix.optimize.QueryOptimizer;
import org.apache.phoenix.parse.AliasedNode;
import org.apache.phoenix.parse.DeleteStatement;
import org.apache.phoenix.parse.HintNode;
import org.apache.phoenix.parse.HintNode.Hint;
import org.apache.phoenix.parse.NamedTableNode;
import org.apache.phoenix.parse.ParseNode;
import org.apache.phoenix.parse.ParseNodeFactory;
import org.apache.phoenix.parse.SelectStatement;
import org.apache.phoenix.query.ConnectionQueryServices;
import org.apache.phoenix.query.KeyRange;
import org.apache.phoenix.query.QueryConstants;
import org.apache.phoenix.query.QueryServices;
import org.apache.phoenix.query.QueryServicesOptions;
import org.apache.phoenix.schema.MetaDataClient;
import org.apache.phoenix.schema.MetaDataEntityNotFoundException;
import org.apache.phoenix.schema.PColumn;
import org.apache.phoenix.schema.PIndexState;
import org.apache.phoenix.schema.PName;
import org.apache.phoenix.schema.PRow;
import org.apache.phoenix.schema.PTable;
import org.apache.phoenix.schema.PTableKey;
import org.apache.phoenix.schema.PTableType;
import org.apache.phoenix.schema.ReadOnlyTableException;
import org.apache.phoenix.schema.SortOrder;
import org.apache.phoenix.schema.TableRef;
import org.apache.phoenix.schema.tuple.Tuple;
import org.apache.phoenix.schema.types.PLong;
import org.apache.phoenix.util.MetaDataUtil;
import org.apache.phoenix.util.ScanUtil;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.sun.istack.NotNull;
public class DeleteCompiler {
private static ParseNodeFactory FACTORY = new ParseNodeFactory();
private final PhoenixStatement statement;
public DeleteCompiler(PhoenixStatement statement) {
this.statement = statement;
}
private static MutationState deleteRows(PhoenixStatement statement, TableRef targetTableRef, TableRef indexTableRef, ResultIterator iterator, RowProjector projector, TableRef sourceTableRef) throws SQLException {
PTable table = targetTableRef.getTable();
PhoenixConnection connection = statement.getConnection();
PName tenantId = connection.getTenantId();
byte[] tenantIdBytes = null;
if (tenantId != null) {
tenantId = ScanUtil.padTenantIdIfNecessary(table.getRowKeySchema(), table.getBucketNum() != null, tenantId);
tenantIdBytes = tenantId.getBytes();
}
final boolean isAutoCommit = connection.getAutoCommit();
ConnectionQueryServices services = connection.getQueryServices();
final int maxSize = services.getProps().getInt(QueryServices.MAX_MUTATION_SIZE_ATTRIB,QueryServicesOptions.DEFAULT_MAX_MUTATION_SIZE);
final int batchSize = Math.min(connection.getMutateBatchSize(), maxSize);
Map<ImmutableBytesPtr,Map<PColumn,byte[]>> mutations = Maps.newHashMapWithExpectedSize(batchSize);
Map<ImmutableBytesPtr,Map<PColumn,byte[]>> indexMutations = null;
// If indexTableRef is set, we're deleting the rows from both the index table and
// the data table through a single query to save executing an additional one.
if (indexTableRef != null) {
indexMutations = Maps.newHashMapWithExpectedSize(batchSize);
}
try {
List<PColumn> pkColumns = table.getPKColumns();
boolean isMultiTenant = table.isMultiTenant() && tenantIdBytes != null;
boolean isSharedViewIndex = table.getViewIndexId() != null;
int offset = (table.getBucketNum() == null ? 0 : 1);
byte[][] values = new byte[pkColumns.size()][];
if (isMultiTenant) {
values[offset++] = tenantIdBytes;
}
if (isSharedViewIndex) {
values[offset++] = MetaDataUtil.getViewIndexIdDataType().toBytes(table.getViewIndexId());
}
PhoenixResultSet rs = new PhoenixResultSet(iterator, projector, statement);
int rowCount = 0;
while (rs.next()) {
ImmutableBytesPtr ptr = new ImmutableBytesPtr(); // allocate new as this is a key in a Map
// Use tuple directly, as projector would not have all the PK columns from
// our index table inside of our projection. Since the tables are equal,
// there's no transation required.
if (sourceTableRef.equals(targetTableRef)) {
rs.getCurrentRow().getKey(ptr);
} else {
for (int i = offset; i < values.length; i++) {
byte[] byteValue = rs.getBytes(i+1-offset);
// The ResultSet.getBytes() call will have inverted it - we need to invert it back.
// TODO: consider going under the hood and just getting the bytes
if (pkColumns.get(i).getSortOrder() == SortOrder.DESC) {
byte[] tempByteValue = Arrays.copyOf(byteValue, byteValue.length);
byteValue = SortOrder.invert(byteValue, 0, tempByteValue, 0, byteValue.length);
}
values[i] = byteValue;
}
table.newKey(ptr, values);
}
mutations.put(ptr, PRow.DELETE_MARKER);
if (indexTableRef != null) {
ImmutableBytesPtr indexPtr = new ImmutableBytesPtr(); // allocate new as this is a key in a Map
rs.getCurrentRow().getKey(indexPtr);
indexMutations.put(indexPtr, PRow.DELETE_MARKER);
}
if (mutations.size() > maxSize) {
throw new IllegalArgumentException("MutationState size of " + mutations.size() + " is bigger than max allowed size of " + maxSize);
}
rowCount++;
// Commit a batch if auto commit is true and we're at our batch size
if (isAutoCommit && rowCount % batchSize == 0) {
MutationState state = new MutationState(targetTableRef, mutations, 0, maxSize, connection);
connection.getMutationState().join(state);
if (indexTableRef != null) {
MutationState indexState = new MutationState(indexTableRef, indexMutations, 0, maxSize, connection);
connection.getMutationState().join(indexState);
}
connection.commit();
mutations.clear();
if (indexMutations != null) {
indexMutations.clear();
}
}
}
// If auto commit is true, this last batch will be committed upon return
int nCommittedRows = rowCount / batchSize * batchSize;
MutationState state = new MutationState(targetTableRef, mutations, nCommittedRows, maxSize, connection);
if (indexTableRef != null) {
// To prevent the counting of these index rows, we have a negative for remainingRows.
MutationState indexState = new MutationState(indexTableRef, indexMutations, 0, maxSize, connection);
state.join(indexState);
}
return state;
} finally {
iterator.close();
}
}
private static class DeletingParallelIteratorFactory extends MutatingParallelIteratorFactory {
private RowProjector projector;
private TableRef targetTableRef;
private TableRef indexTableRef;
private TableRef sourceTableRef;
private DeletingParallelIteratorFactory(PhoenixConnection connection) {
super(connection);
}
@Override
protected MutationState mutate(StatementContext context, ResultIterator iterator, PhoenixConnection connection) throws SQLException {
PhoenixStatement statement = new PhoenixStatement(connection);
return deleteRows(statement, targetTableRef, indexTableRef, iterator, projector, sourceTableRef);
}
public void setTargetTableRef(TableRef tableRef) {
this.targetTableRef = tableRef;
}
public void setSourceTableRef(TableRef tableRef) {
this.sourceTableRef = tableRef;
}
public void setRowProjector(RowProjector projector) {
this.projector = projector;
}
public void setIndexTargetTableRef(TableRef indexTableRef) {
this.indexTableRef = indexTableRef;
}
}
private Set<PTable> getNonDisabledImmutableIndexes(TableRef tableRef) {
PTable table = tableRef.getTable();
if (table.isImmutableRows() && !table.getIndexes().isEmpty()) {
Set<PTable> nonDisabledIndexes = Sets.newHashSetWithExpectedSize(table.getIndexes().size());
for (PTable index : table.getIndexes()) {
if (index.getIndexState() != PIndexState.DISABLE) {
nonDisabledIndexes.add(index);
}
}
return nonDisabledIndexes;
}
return Collections.emptySet();
}
private class MultiDeleteMutationPlan implements MutationPlan {
private final List<MutationPlan> plans;
private final MutationPlan firstPlan;
public MultiDeleteMutationPlan(@NotNull List<MutationPlan> plans) {
Preconditions.checkArgument(!plans.isEmpty());
this.plans = plans;
this.firstPlan = plans.get(0);
}
@Override
public StatementContext getContext() {
return firstPlan.getContext();
}
@Override
public ParameterMetaData getParameterMetaData() {
return firstPlan.getParameterMetaData();
}
@Override
public ExplainPlan getExplainPlan() throws SQLException {
return firstPlan.getExplainPlan();
}
@Override
public PhoenixConnection getConnection() {
return firstPlan.getConnection();
}
@Override
public MutationState execute() throws SQLException {
MutationState state = firstPlan.execute();
for (MutationPlan plan : plans.subList(1, plans.size())) {
plan.execute();
}
return state;
}
}
public MutationPlan compile(DeleteStatement delete) throws SQLException {
final PhoenixConnection connection = statement.getConnection();
final boolean isAutoCommit = connection.getAutoCommit();
final boolean hasLimit = delete.getLimit() != null;
final ConnectionQueryServices services = connection.getQueryServices();
List<QueryPlan> queryPlans;
NamedTableNode tableNode = delete.getTable();
String tableName = tableNode.getName().getTableName();
String schemaName = tableNode.getName().getSchemaName();
boolean retryOnce = !isAutoCommit;
TableRef tableRefToBe;
boolean noQueryReqd = false;
boolean runOnServer = false;
SelectStatement select = null;
Set<PTable> immutableIndex = Collections.emptySet();
DeletingParallelIteratorFactory parallelIteratorFactory = null;
while (true) {
try {
ColumnResolver resolver = FromCompiler.getResolverForMutation(delete, connection);
tableRefToBe = resolver.getTables().get(0);
PTable table = tableRefToBe.getTable();
if (table.getType() == PTableType.VIEW && table.getViewType().isReadOnly()) {
throw new ReadOnlyTableException(table.getSchemaName().getString(),table.getTableName().getString());
}
immutableIndex = getNonDisabledImmutableIndexes(tableRefToBe);
boolean mayHaveImmutableIndexes = !immutableIndex.isEmpty();
noQueryReqd = !hasLimit;
runOnServer = isAutoCommit && noQueryReqd;
HintNode hint = delete.getHint();
if (runOnServer && !delete.getHint().hasHint(Hint.USE_INDEX_OVER_DATA_TABLE)) {
hint = HintNode.create(hint, Hint.USE_DATA_OVER_INDEX_TABLE);
}
List<AliasedNode> aliasedNodes = Lists.newArrayListWithExpectedSize(table.getPKColumns().size());
boolean isSalted = table.getBucketNum() != null;
boolean isMultiTenant = connection.getTenantId() != null && table.isMultiTenant();
boolean isSharedViewIndex = table.getViewIndexId() != null;
for (int i = (isSalted ? 1 : 0) + (isMultiTenant ? 1 : 0) + (isSharedViewIndex ? 1 : 0); i < table.getPKColumns().size(); i++) {
PColumn column = table.getPKColumns().get(i);
aliasedNodes.add(FACTORY.aliasedNode(null, FACTORY.column(null, '"' + column.getName().getString() + '"', null)));
}
select = FACTORY.select(
delete.getTable(),
hint, false, aliasedNodes, delete.getWhere(),
Collections.<ParseNode>emptyList(), null,
delete.getOrderBy(), delete.getLimit(),
delete.getBindCount(), false, false, Collections.<SelectStatement>emptyList());
select = StatementNormalizer.normalize(select, resolver);
SelectStatement transformedSelect = SubqueryRewriter.transform(select, resolver, connection);
if (transformedSelect != select) {
resolver = FromCompiler.getResolverForQuery(transformedSelect, connection);
select = StatementNormalizer.normalize(transformedSelect, resolver);
}
parallelIteratorFactory = hasLimit ? null : new DeletingParallelIteratorFactory(connection);
QueryOptimizer optimizer = new QueryOptimizer(services);
queryPlans = Lists.newArrayList(mayHaveImmutableIndexes
? optimizer.getApplicablePlans(statement, select, resolver, Collections.<PColumn>emptyList(), parallelIteratorFactory)
: optimizer.getBestPlan(statement, select, resolver, Collections.<PColumn>emptyList(), parallelIteratorFactory));
if (mayHaveImmutableIndexes) { // FIXME: this is ugly
// Lookup the table being deleted from in the cache, as it's possible that the
// optimizer updated the cache if it found indexes that were out of date.
// If the index was marked as disabled, it should not be in the list
// of immutable indexes.
table = connection.getMetaDataCache().getTable(new PTableKey(table.getTenantId(), table.getName().getString()));
tableRefToBe.setTable(table);
immutableIndex = getNonDisabledImmutableIndexes(tableRefToBe);
}
} catch (MetaDataEntityNotFoundException e) {
// Catch column/column family not found exception, as our meta data may
// be out of sync. Update the cache once and retry if we were out of sync.
// Otherwise throw, as we'll just get the same error next time.
if (retryOnce) {
retryOnce = false;
MetaDataMutationResult result = new MetaDataClient(connection).updateCache(schemaName, tableName);
if (result.wasUpdated()) {
continue;
}
}
throw e;
}
break;
}
final boolean hasImmutableIndexes = !immutableIndex.isEmpty();
// tableRefs is parallel with queryPlans
TableRef[] tableRefs = new TableRef[hasImmutableIndexes ? immutableIndex.size() : 1];
if (hasImmutableIndexes) {
int i = 0;
Iterator<QueryPlan> plans = queryPlans.iterator();
while (plans.hasNext()) {
QueryPlan plan = plans.next();
PTable table = plan.getTableRef().getTable();
if (table.getType() == PTableType.INDEX) { // index plans
tableRefs[i++] = plan.getTableRef();
immutableIndex.remove(table);
} else { // data plan
/*
* If we have immutable indexes that we need to maintain, don't execute the data plan
* as we can save a query by piggy-backing on any of the other index queries, since the
* PK columns that we need are always in each index row.
*/
plans.remove();
}
}
/*
* If we have any immutable indexes remaining, then that means that the plan for that index got filtered out
* because it could not be executed. This would occur if a column in the where clause is not found in the
* immutable index.
*/
if (!immutableIndex.isEmpty()) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.INVALID_FILTER_ON_IMMUTABLE_ROWS).setSchemaName(tableRefToBe.getTable().getSchemaName().getString())
.setTableName(tableRefToBe.getTable().getTableName().getString()).build().buildException();
}
}
// Make sure the first plan is targeting deletion from the data table
// In the case of an immutable index, we'll also delete from the index.
tableRefs[0] = tableRefToBe;
/*
* Create a mutationPlan for each queryPlan. One plan will be for the deletion of the rows
* from the data table, while the others will be for deleting rows from immutable indexes.
*/
List<MutationPlan> mutationPlans = Lists.newArrayListWithExpectedSize(tableRefs.length);
for (int i = 0; i < tableRefs.length; i++) {
final TableRef tableRef = tableRefs[i];
final QueryPlan plan = queryPlans.get(i);
if (!plan.getTableRef().equals(tableRef) || !(plan instanceof BaseQueryPlan)) {
runOnServer = false;
noQueryReqd = false; // FIXME: why set this to false in this case?
}
final int maxSize = services.getProps().getInt(QueryServices.MAX_MUTATION_SIZE_ATTRIB,QueryServicesOptions.DEFAULT_MAX_MUTATION_SIZE);
final StatementContext context = plan.getContext();
// If we're doing a query for a set of rows with no where clause, then we don't need to contact the server at all.
// A simple check of the none existence of a where clause in the parse node is not sufficient, as the where clause
// may have been optimized out. Instead, we check that there's a single SkipScanFilter
if (noQueryReqd
&& (!context.getScan().hasFilter()
|| context.getScan().getFilter() instanceof SkipScanFilter)
&& context.getScanRanges().isPointLookup()) {
mutationPlans.add(new MutationPlan() {
@Override
public ParameterMetaData getParameterMetaData() {
return context.getBindManager().getParameterMetaData();
}
@Override
public MutationState execute() {
// We have a point lookup, so we know we have a simple set of fully qualified
// keys for our ranges
ScanRanges ranges = context.getScanRanges();
Iterator<KeyRange> iterator = ranges.getPointLookupKeyIterator();
Map<ImmutableBytesPtr,Map<PColumn,byte[]>> mutation = Maps.newHashMapWithExpectedSize(ranges.getPointLookupCount());
while (iterator.hasNext()) {
mutation.put(new ImmutableBytesPtr(iterator.next().getLowerRange()), PRow.DELETE_MARKER);
}
return new MutationState(tableRef, mutation, 0, maxSize, connection);
}
@Override
public ExplainPlan getExplainPlan() throws SQLException {
return new ExplainPlan(Collections.singletonList("DELETE SINGLE ROW"));
}
@Override
public PhoenixConnection getConnection() {
return connection;
}
@Override
public StatementContext getContext() {
return context;
}
});
} else if (runOnServer) {
// TODO: better abstraction
Scan scan = context.getScan();
scan.setAttribute(BaseScannerRegionObserver.DELETE_AGG, QueryConstants.TRUE);
// Build an ungrouped aggregate query: select COUNT(*) from <table> where <where>
// The coprocessor will delete each row returned from the scan
// Ignoring ORDER BY, since with auto commit on and no limit makes no difference
SelectStatement aggSelect = SelectStatement.create(SelectStatement.COUNT_ONE, delete.getHint());
final RowProjector projector = ProjectionCompiler.compile(context, aggSelect, GroupBy.EMPTY_GROUP_BY);
final QueryPlan aggPlan = new AggregatePlan(context, select, tableRef, projector, null, OrderBy.EMPTY_ORDER_BY, null, GroupBy.EMPTY_GROUP_BY, null);
mutationPlans.add(new MutationPlan() {
@Override
public PhoenixConnection getConnection() {
return connection;
}
@Override
public ParameterMetaData getParameterMetaData() {
return context.getBindManager().getParameterMetaData();
}
@Override
public StatementContext getContext() {
return context;
}
@Override
public MutationState execute() throws SQLException {
// TODO: share this block of code with UPSERT SELECT
ImmutableBytesWritable ptr = context.getTempPtr();
tableRef.getTable().getIndexMaintainers(ptr, context.getConnection());
ServerCache cache = null;
try {
if (ptr.getLength() > 0) {
IndexMetaDataCacheClient client = new IndexMetaDataCacheClient(connection, tableRef);
cache = client.addIndexMetadataCache(context.getScanRanges(), ptr);
byte[] uuidValue = cache.getId();
context.getScan().setAttribute(PhoenixIndexCodec.INDEX_UUID, uuidValue);
}
ResultIterator iterator = aggPlan.iterator();
try {
Tuple row = iterator.next();
final long mutationCount = (Long)projector.getColumnProjector(0).getValue(row, PLong.INSTANCE, ptr);
return new MutationState(maxSize, connection) {
@Override
public long getUpdateCount() {
return mutationCount;
}
};
} finally {
iterator.close();
}
} finally {
if (cache != null) {
cache.close();
}
}
}
@Override
public ExplainPlan getExplainPlan() throws SQLException {
List<String> queryPlanSteps = aggPlan.getExplainPlan().getPlanSteps();
List<String> planSteps = Lists.newArrayListWithExpectedSize(queryPlanSteps.size()+1);
planSteps.add("DELETE ROWS");
planSteps.addAll(queryPlanSteps);
return new ExplainPlan(planSteps);
}
});
} else {
final boolean deleteFromImmutableIndexToo = hasImmutableIndexes && !plan.getTableRef().equals(tableRef);
if (parallelIteratorFactory != null) {
parallelIteratorFactory.setRowProjector(plan.getProjector());
parallelIteratorFactory.setTargetTableRef(tableRef);
parallelIteratorFactory.setSourceTableRef(plan.getTableRef());
parallelIteratorFactory.setIndexTargetTableRef(deleteFromImmutableIndexToo ? plan.getTableRef() : null);
}
mutationPlans.add( new MutationPlan() {
@Override
public PhoenixConnection getConnection() {
return connection;
}
@Override
public ParameterMetaData getParameterMetaData() {
return context.getBindManager().getParameterMetaData();
}
@Override
public StatementContext getContext() {
return context;
}
@Override
public MutationState execute() throws SQLException {
ResultIterator iterator = plan.iterator();
if (!hasLimit) {
Tuple tuple;
long totalRowCount = 0;
while ((tuple=iterator.next()) != null) {// Runs query
Cell kv = tuple.getValue(0);
totalRowCount += PLong.INSTANCE.getCodec().decodeLong(kv.getValueArray(), kv.getValueOffset(), SortOrder.getDefault());
}
// Return total number of rows that have been delete. In the case of auto commit being off
// the mutations will all be in the mutation state of the current connection.
return new MutationState(maxSize, connection, totalRowCount);
} else {
return deleteRows(statement, tableRef, deleteFromImmutableIndexToo ? plan.getTableRef() : null, iterator, plan.getProjector(), plan.getTableRef());
}
}
@Override
public ExplainPlan getExplainPlan() throws SQLException {
List<String> queryPlanSteps = plan.getExplainPlan().getPlanSteps();
List<String> planSteps = Lists.newArrayListWithExpectedSize(queryPlanSteps.size()+1);
planSteps.add("DELETE ROWS");
planSteps.addAll(queryPlanSteps);
return new ExplainPlan(planSteps);
}
});
}
}
return mutationPlans.size() == 1 ? mutationPlans.get(0) : new MultiDeleteMutationPlan(mutationPlans);
}
}
|
apache-2.0
|
supershiro/Cancer
|
src/libs/const.js
|
1357
|
/**
* define global constant
*
* Created by Shiro on 16/12/20.
*/
const NAV = [
{name: 'Home', link: '/index'},
{name: 'Editor', link: '/editor'},
{name: 'Project', link: '/project', children: [
{name: 'RMSP', link: '/project/rmsp'},
{name: 'test', link: '/project/'},
{name: 'test', link: '/project/'}
]},
{name: 'Css', link: '/css'}
];
export {NAV};
const TITLEMAP = {
login: '登录'
};
export {TITLEMAP};
const MAP = {
sex: ['女', '男'],
zodiac: [
{zh: '鼠', emoji: '🐹'},
{zh: '牛', emoji: '🐮'},
{zh: '虎', emoji: '🐯'},
{zh: '兔', emoji: '🐰'},
{zh: '龙', emoji: '🐲'},
{zh: '蛇', emoji: '🐍'},
{zh: '马', emoji: '🦄'},
{zh: '羊', emoji: '🐑'},
{zh: '猴', emoji: '🐒'},
{zh: '鸡', emoji: '🐣'},
{zh: '狗', emoji: '🐶'},
{zh: '猪', emoji: '🐷'}
],
constellation: [
{zh: '白羊座', emoji: '♈'},
{zh: '金牛座', emoji: '♉'},
{zh: '双子座', emoji: '♊'},
{zh: '巨蟹座', emoji: '♋'},
{zh: '狮子座', emoji: '♌'},
{zh: '处女座', emoji: '♍'},
{zh: '天秤座', emoji: '♎'},
{zh: '天蝎座', emoji: '♏'},
{zh: '射手座', emoji: '♐'},
{zh: '摩羯座', emoji: '♑'},
{zh: '水瓶座', emoji: '♒'},
{zh: '双鱼座', emoji: '♓'}
]
};
export {MAP}
|
apache-2.0
|
Hexworks/zircon
|
docs/2020.2.0-RELEASE-KOTLIN/zircon.core/zircon.core/org.hexworks.zircon.internal.resource/-built-in-c-p437-tileset-resource/-c-o-o-z_16-x16/name.html
|
3593
|
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" charset="UTF-8">
<title>name</title>
<link href="../../../../images/logo-icon.svg" rel="icon" type="image/svg">
<script>var pathToRoot = "../../../../";</script>
<script type="text/javascript" src="../../../../scripts/sourceset_dependencies.js" async="async"></script>
<link href="../../../../styles/style.css" rel="Stylesheet">
<link href="../../../../styles/logo-styles.css" rel="Stylesheet">
<link href="../../../../styles/jetbrains-mono.css" rel="Stylesheet">
<link href="../../../../styles/main.css" rel="Stylesheet">
<script type="text/javascript" src="../../../../scripts/clipboard.js" async="async"></script>
<script type="text/javascript" src="../../../../scripts/navigation-loader.js" async="async"></script>
<script type="text/javascript" src="../../../../scripts/platform-content-handler.js" async="async"></script>
<script type="text/javascript" src="../../../../scripts/main.js" async="async"></script>
</head>
<body>
<div id="container">
<div id="leftColumn">
<div id="logo"></div>
<div id="paneSearch"></div>
<div id="sideMenu"></div>
</div>
<div id="main">
<div id="leftToggler"><span class="icon-toggler"></span></div>
<script type="text/javascript" src="../../../../scripts/pages.js"></script>
<script type="text/javascript" src="../../../../scripts/main.js"></script>
<div class="main-content" id="content" pageIds="org.hexworks.zircon.internal.resource/BuiltInCP437TilesetResource.COOZ_16X16/name/#/PointingToDeclaration//-828656838">
<div class="navigation-wrapper" id="navigation-wrapper">
<div class="breadcrumbs"><a href="../../../index.html">zircon.core</a>/<a href="../../index.html">org.hexworks.zircon.internal.resource</a>/<a href="../index.html">BuiltInCP437TilesetResource</a>/<a href="index.html">COOZ_16X16</a>/<a href="name.html">name</a></div>
<div class="pull-right d-flex">
<div class="filter-section" id="filter-section"><button class="platform-tag platform-selector common-like" data-active="" data-filter=":zircon.core:dokkaHtml/commonMain">common</button></div>
<div id="searchBar"></div>
</div>
</div>
<div class="cover ">
<h1 class="cover"><span>name</span></h1>
</div>
<div class="divergent-group" data-filterable-current=":zircon.core:dokkaHtml/commonMain" data-filterable-set=":zircon.core:dokkaHtml/commonMain"><div class="with-platform-tags"><span class="pull-right"></span></div>
<div>
<div class="platform-hinted " data-platform-hinted="data-platform-hinted"><div class="content sourceset-depenent-content" data-active="" data-togglable=":zircon.core:dokkaHtml/commonMain"><div class="symbol monospace">val <a href="name.html">name</a>: <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html">String</a><span class="top-right-position"><span class="copy-icon"></span><div class="copy-popup-wrapper popup-to-left"><span class="copy-popup-icon"></span><span>Content copied to clipboard</span></div></span></div></div></div>
</div>
</div>
</div>
<div class="footer"><span class="go-to-top-icon"><a href="#content"></a></span><span>© 2020 Copyright</span><span class="pull-right"><span>Sponsored and developed by dokka</span><a href="https://github.com/Kotlin/dokka"><span class="padded-icon"></span></a></span></div>
</div>
</div>
</body>
</html>
|
apache-2.0
|
skremp/pictura-io
|
servlet/src/main/java/io/pictura/servlet/CacheControlHandler.java
|
2439
|
/**
* Copyright 2015 Steffen Kremp
*
* 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 io.pictura.servlet;
import java.net.HttpURLConnection;
import javax.servlet.http.HttpServletResponse;
/**
* A handler to provide cache control directives for the value of the HTTP
* response header.
* <p>
* For example, to set a general max-age of 60 seconds, the implementation looks
* like:
*
* <pre>
* public class DefaultCacheControlHandler implements CacheControlHandler {
*
* public String getDirective(String path) {
* if (path != null) {
* return "public, max-age=60";
* }
* return null;
* }
*
* }
* </pre>
*
* @author Steffen Kremp
*
* @since 1.0
*/
public interface CacheControlHandler {
/**
* Gets the cache control directive for the specified resource path. If
* there is no directive available for the requested resource, the method
* returns <code>null</code>. Also a directive will only set in cases of an
* {@link HttpServletResponse#SC_OK} status code.
* <p>
* If the resource is located on a remote server and the used
* {@link RequestProcessor} uses an {@link HttpURLConnection} to fetch the
* resource the origin cache control header will be overwritten with the
* directive by this implementation, however not if there was no custom
* directive found.
* </p>
* <p>
* If the directive contains a <code>max-age</code>, the value of the
* maximum age is also used to calculate and set the <code>Expires</code>
* header, where the value of the expiration date is <code>System.currentTimeMillis() +
* (max-age * 1000)</code>.
* </p>
*
* @param path The resource path.
*
* @return The cache control directive or <code>null</code> if there was no
* directive found for the given resource path.
*/
public String getDirective(String path);
}
|
apache-2.0
|
GIP-RECIA/esco-grouper-ui
|
ext/bundles/myfaces-api/src/main/java/javax/faces/event/FacesListener.java
|
2038
|
/**
* Copyright (C) 2009 GIP RECIA http://www.recia.fr
* @Author (C) 2009 GIP RECIA <[email protected]>
* @Contributor (C) 2009 SOPRA http://www.sopragroup.com/
* @Contributor (C) 2011 Pierre Legay <[email protected]>
*
* 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.
*/
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 javax.faces.event;
import java.util.EventListener;
/**
* see Javadoc of <a href="http://java.sun.com/j2ee/javaserverfaces/1.1_01/docs/api/index.html">JSF Specification</a>
*
* @author Thomas Spiegl (latest modification by $Author: grantsmith $)
* @version $Revision: 472558 $ $Date: 2006-11-08 18:36:53 +0100 (Mi, 08 Nov 2006) $
*/
public interface FacesListener
extends EventListener
{
}
|
apache-2.0
|
atelierspierrot/patterns
|
src/Patterns/Interfaces/OptionableInterface.php
|
1567
|
<?php
/**
* This file is part of the Patterns package.
*
* Copyright (c) 2013-2016 Pierre Cassat <[email protected]> and contributors
*
* 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.
*
* The source code of this package is available online at
* <http://github.com/atelierspierrot/patterns>.
*/
namespace Patterns\Interfaces;
/**
* A simple interface to manage a set of options
*
* @author piwi <[email protected]>
*/
interface OptionableInterface
{
/**
* Set an array of options
* @param array $options
*/
public function setOptions(array $options);
/**
* Set the value of a specific option
* @param string $name
* @param mixed $value
*/
public function setOption($name, $value);
/**
* Get the array of options
* @return array
*/
public function getOptions();
/**
* Get the value of a specific option
* @param string $name
* @param mixed $default
* @return mixed
*/
public function getOption($name, $default = null);
}
|
apache-2.0
|
wildfly-swarm/wildfly-swarm-javadocs
|
2017.12.1/apidocs/org/wildfly/swarm/config/management/access/class-use/RoleMappingConsumer.html
|
12296
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_151) on Wed Dec 13 10:32:43 MST 2017 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Interface org.wildfly.swarm.config.management.access.RoleMappingConsumer (BOM: * : All 2017.12.1 API)</title>
<meta name="date" content="2017-12-13">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface org.wildfly.swarm.config.management.access.RoleMappingConsumer (BOM: * : All 2017.12.1 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/wildfly/swarm/config/management/access/RoleMappingConsumer.html" title="interface in org.wildfly.swarm.config.management.access">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2017.12.1</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/wildfly/swarm/config/management/access/class-use/RoleMappingConsumer.html" target="_top">Frames</a></li>
<li><a href="RoleMappingConsumer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Interface org.wildfly.swarm.config.management.access.RoleMappingConsumer" class="title">Uses of Interface<br>org.wildfly.swarm.config.management.access.RoleMappingConsumer</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../../org/wildfly/swarm/config/management/access/RoleMappingConsumer.html" title="interface in org.wildfly.swarm.config.management.access">RoleMappingConsumer</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.wildfly.swarm.config.management">org.wildfly.swarm.config.management</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#org.wildfly.swarm.config.management.access">org.wildfly.swarm.config.management.access</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.wildfly.swarm.config.management">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../org/wildfly/swarm/config/management/access/RoleMappingConsumer.html" title="interface in org.wildfly.swarm.config.management.access">RoleMappingConsumer</a> in <a href="../../../../../../../org/wildfly/swarm/config/management/package-summary.html">org.wildfly.swarm.config.management</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../org/wildfly/swarm/config/management/package-summary.html">org.wildfly.swarm.config.management</a> with parameters of type <a href="../../../../../../../org/wildfly/swarm/config/management/access/RoleMappingConsumer.html" title="interface in org.wildfly.swarm.config.management.access">RoleMappingConsumer</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../org/wildfly/swarm/config/management/AuthorizationAccess.html" title="type parameter in AuthorizationAccess">T</a></code></td>
<td class="colLast"><span class="typeNameLabel">AuthorizationAccess.</span><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/management/AuthorizationAccess.html#roleMapping-java.lang.String-org.wildfly.swarm.config.management.access.RoleMappingConsumer-">roleMapping</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> childKey,
<a href="../../../../../../../org/wildfly/swarm/config/management/access/RoleMappingConsumer.html" title="interface in org.wildfly.swarm.config.management.access">RoleMappingConsumer</a> consumer)</code>
<div class="block">Create and configure a RoleMapping object to the list of subresources</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.wildfly.swarm.config.management.access">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../org/wildfly/swarm/config/management/access/RoleMappingConsumer.html" title="interface in org.wildfly.swarm.config.management.access">RoleMappingConsumer</a> in <a href="../../../../../../../org/wildfly/swarm/config/management/access/package-summary.html">org.wildfly.swarm.config.management.access</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../org/wildfly/swarm/config/management/access/package-summary.html">org.wildfly.swarm.config.management.access</a> that return <a href="../../../../../../../org/wildfly/swarm/config/management/access/RoleMappingConsumer.html" title="interface in org.wildfly.swarm.config.management.access">RoleMappingConsumer</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>default <a href="../../../../../../../org/wildfly/swarm/config/management/access/RoleMappingConsumer.html" title="interface in org.wildfly.swarm.config.management.access">RoleMappingConsumer</a><<a href="../../../../../../../org/wildfly/swarm/config/management/access/RoleMappingConsumer.html" title="type parameter in RoleMappingConsumer">T</a>></code></td>
<td class="colLast"><span class="typeNameLabel">RoleMappingConsumer.</span><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/management/access/RoleMappingConsumer.html#andThen-org.wildfly.swarm.config.management.access.RoleMappingConsumer-">andThen</a></span>(<a href="../../../../../../../org/wildfly/swarm/config/management/access/RoleMappingConsumer.html" title="interface in org.wildfly.swarm.config.management.access">RoleMappingConsumer</a><<a href="../../../../../../../org/wildfly/swarm/config/management/access/RoleMappingConsumer.html" title="type parameter in RoleMappingConsumer">T</a>> after)</code> </td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../org/wildfly/swarm/config/management/access/package-summary.html">org.wildfly.swarm.config.management.access</a> with parameters of type <a href="../../../../../../../org/wildfly/swarm/config/management/access/RoleMappingConsumer.html" title="interface in org.wildfly.swarm.config.management.access">RoleMappingConsumer</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>default <a href="../../../../../../../org/wildfly/swarm/config/management/access/RoleMappingConsumer.html" title="interface in org.wildfly.swarm.config.management.access">RoleMappingConsumer</a><<a href="../../../../../../../org/wildfly/swarm/config/management/access/RoleMappingConsumer.html" title="type parameter in RoleMappingConsumer">T</a>></code></td>
<td class="colLast"><span class="typeNameLabel">RoleMappingConsumer.</span><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/management/access/RoleMappingConsumer.html#andThen-org.wildfly.swarm.config.management.access.RoleMappingConsumer-">andThen</a></span>(<a href="../../../../../../../org/wildfly/swarm/config/management/access/RoleMappingConsumer.html" title="interface in org.wildfly.swarm.config.management.access">RoleMappingConsumer</a><<a href="../../../../../../../org/wildfly/swarm/config/management/access/RoleMappingConsumer.html" title="type parameter in RoleMappingConsumer">T</a>> after)</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/wildfly/swarm/config/management/access/RoleMappingConsumer.html" title="interface in org.wildfly.swarm.config.management.access">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2017.12.1</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/wildfly/swarm/config/management/access/class-use/RoleMappingConsumer.html" target="_top">Frames</a></li>
<li><a href="RoleMappingConsumer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2017 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
|
apache-2.0
|
stryker-mutator/stryker
|
packages/jest-runner/test/unit/config-loaders/custom-config-loader.spec.ts
|
5452
|
import fs from 'fs';
import path from 'path';
import { expect } from 'chai';
import sinon from 'sinon';
import { factory } from '@stryker-mutator/test-helpers';
import * as utils from '@stryker-mutator/util';
import type { Config } from '@jest/types';
import { CustomJestConfigLoader } from '../../../src/config-loaders/custom-jest-config-loader';
import { createJestRunnerOptionsWithStrykerOptions } from '../../helpers/producers';
import { JestRunnerOptionsWithStrykerOptions } from '../../../src/jest-runner-options-with-stryker-options';
describe(CustomJestConfigLoader.name, () => {
let sut: CustomJestConfigLoader;
const projectRoot = process.cwd();
let readFileSyncStub: sinon.SinonStub;
let fileExistsSyncStub: sinon.SinonStub;
let requireStub: sinon.SinonStub;
let readConfig: Config.InitialOptions;
let options: JestRunnerOptionsWithStrykerOptions;
beforeEach(() => {
readFileSyncStub = sinon.stub(fs, 'readFileSync');
fileExistsSyncStub = sinon.stub(fs, 'existsSync');
requireStub = sinon.stub(utils, 'requireResolve');
readConfig = { testMatch: ['exampleJestConfigValue'] };
readFileSyncStub.callsFake(() => `{ "jest": ${JSON.stringify(readConfig)}}`);
requireStub.returns(readConfig);
options = createJestRunnerOptionsWithStrykerOptions();
sut = new CustomJestConfigLoader(factory.logger(), options);
});
it('should load the Jest configuration from the jest.config.js', () => {
fileExistsSyncStub.returns(true);
const config = sut.loadConfig();
expect(requireStub).calledWith(path.join(projectRoot, 'jest.config.js'));
expect(config).to.deep.contains(readConfig);
});
it('should set the rootDir when no rootDir was configured jest.config.js', () => {
fileExistsSyncStub.returns(true);
const config = sut.loadConfig();
expect(requireStub).calledWith(path.join(projectRoot, 'jest.config.js'));
expect(config).to.deep.contains({ rootDir: projectRoot });
});
it('should override the rootDir when a rootDir was configured jest.config.js', () => {
readConfig.rootDir = 'lib';
fileExistsSyncStub.returns(true);
const config = sut.loadConfig();
expect(requireStub).calledWith(path.join(projectRoot, 'jest.config.js'));
expect(config).to.deep.contains({ rootDir: path.resolve(projectRoot, 'lib') });
});
it('should allow users to configure a jest.config.json file as "configFile"', () => {
// Arrange
fileExistsSyncStub.returns(true);
options.jest.configFile = path.resolve(projectRoot, 'jest.config.json');
// Act
const config = sut.loadConfig();
// Assert
expect(requireStub).calledWith(path.join(projectRoot, 'jest.config.json'));
expect(config).to.deep.contain(readConfig);
});
it('should allow users to configure a package.json file as "configFile"', () => {
// Arrange
fileExistsSyncStub
.withArgs(path.resolve(projectRoot, 'jest.config.js'))
.returns(false)
.withArgs(path.resolve(projectRoot, 'package.json'))
.returns(true);
options.jest.configFile = path.resolve(projectRoot, 'package.json');
// Act
const config = sut.loadConfig();
// Assert
expect(readFileSyncStub).calledWith(path.join(projectRoot, 'package.json'), 'utf8');
expect(config).to.deep.contain(readConfig);
});
it("should fail when configured jest.config.js file doesn't exist", () => {
const expectedError = new Error("File doesn't exist");
fileExistsSyncStub.returns(false);
requireStub.throws(expectedError);
options.jest.configFile = 'my-custom-jest.config.js';
expect(sut.loadConfig.bind(sut)).throws(expectedError);
});
it("should fail when configured package.json file doesn't exist", () => {
const expectedError = new Error("File doesn't exist");
fileExistsSyncStub.returns(false);
readFileSyncStub.throws(expectedError);
options.jest.configFile = 'client/package.json';
expect(sut.loadConfig.bind(sut)).throws(expectedError);
});
it('should fallback and load the Jest configuration from the package.json when jest.config.js is not present in the project', () => {
// Arrange
fileExistsSyncStub
.withArgs(path.resolve(projectRoot, 'jest.config.js'))
.returns(false)
.withArgs(path.resolve(projectRoot, 'package.json'))
.returns(true);
// Act
const config = sut.loadConfig();
// Assert
expect(readFileSyncStub).calledWith(path.join(projectRoot, 'package.json'), 'utf8');
expect(config).to.deep.contain(readConfig);
});
it('should set the rootDir when reading config from package.json', () => {
// Arrange
options.jest.configFile = 'client/package.json';
fileExistsSyncStub
.withArgs(path.resolve(projectRoot, 'jest.config.js'))
.returns(false)
.withArgs(path.resolve(projectRoot, 'client', 'package.json'))
.returns(true);
// Act
const config = sut.loadConfig();
// Assert
expect(readFileSyncStub).calledWith(path.join(projectRoot, 'client', 'package.json'), 'utf8');
expect(config).to.deep.contain(readConfig);
});
it('should load the default Jest configuration if there is no package.json config or jest.config.js', () => {
requireStub.throws(Error('ENOENT: no such file or directory, open package.json'));
readFileSyncStub.returns('{ }'); // note, no `jest` key here!
const config = sut.loadConfig();
expect(config).to.deep.equal({});
});
});
|
apache-2.0
|
lixinjian/MyFirstWinner
|
app/src/main/java/com/xinjian/winner/di/qualifier/VtexUrl.java
|
334
|
package com.xinjian.winner.di.qualifier;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import javax.inject.Qualifier;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Created by codeest on 2017/2/26.
*/
@Qualifier
@Documented
@Retention(RUNTIME)
public @interface VtexUrl {
}
|
apache-2.0
|
wilfriedcomte/centreon-plugins
|
hardware/ups/powerware/snmp/mode/outputsource.pm
|
4126
|
#
# Copyright 2018 Centreon (http://www.centreon.com/)
#
# Centreon is a full-fledged industry-strength solution that meets
# the needs in IT infrastructure and application monitoring for
# service performance.
#
# 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 hardware::ups::powerware::snmp::mode::outputsource;
use base qw(centreon::plugins::mode);
use strict;
use warnings;
my $oid_xupsOutputSource = '.1.3.6.1.4.1.534.1.4.5.0';
my $thresholds = {
osource => [
['normal', 'OK'],
['.*', 'CRITICAL'],
],
};
my %map_osource_status = (
1 => 'other',
2 => 'none',
3 => 'normal',
4 => 'bypass',
5 => 'battery',
6 => 'booster',
7 => 'reducer',
8 => 'parallelCapacity',
9 => 'parallelRedundant',
10 => 'highEfficiencyMode',
11 => 'maintenanceBypass',
);
sub new {
my ($class, %options) = @_;
my $self = $class->SUPER::new(package => __PACKAGE__, %options);
bless $self, $class;
$self->{version} = '1.0';
$options{options}->add_options(arguments =>
{
"threshold-overload:s@" => { name => 'threshold_overload' },
});
return $self;
}
sub check_options {
my ($self, %options) = @_;
$self->SUPER::init(%options);
$self->{overload_th} = {};
foreach my $val (@{$self->{option_results}->{threshold_overload}}) {
if ($val !~ /^(.*?),(.*)$/) {
$self->{output}->add_option_msg(short_msg => "Wrong threshold-overload option '" . $val . "'.");
$self->{output}->option_exit();
}
my ($section, $status, $filter) = ('osource', $1, $2);
if ($self->{output}->is_litteral_status(status => $status) == 0) {
$self->{output}->add_option_msg(short_msg => "Wrong threshold-overload status '" . $val . "'.");
$self->{output}->option_exit();
}
$self->{overload_th}->{$section} = [] if (!defined($self->{overload_th}->{$section}));
push @{$self->{overload_th}->{$section}}, {filter => $filter, status => $status};
}
}
sub run {
my ($self, %options) = @_;
$self->{snmp} = $options{snmp};
my $result = $self->{snmp}->get_leef(oids => [$oid_xupsOutputSource], nothing_quit => 1);
my $exit = $self->get_severity(section => 'osource', value => $map_osource_status{$result->{$oid_xupsOutputSource}});
$self->{output}->output_add(severity => $exit,
short_msg => sprintf("Output source status is %s",
$map_osource_status{$result->{$oid_xupsOutputSource}}));
$self->{output}->display();
$self->{output}->exit();
}
sub get_severity {
my ($self, %options) = @_;
my $status = 'UNKNOWN'; # default
if (defined($self->{overload_th}->{$options{section}})) {
foreach (@{$self->{overload_th}->{$options{section}}}) {
if ($options{value} =~ /$_->{filter}/i) {
$status = $_->{status};
return $status;
}
}
}
foreach (@{$thresholds->{$options{section}}}) {
if ($options{value} =~ /$$_[0]/i) {
$status = $$_[1];
return $status;
}
}
return $status;
}
1;
__END__
=head1 MODE
Check output source status (XUPS-MIB).
=over 8
=item B<--threshold-overload>
Set to overload default threshold values (syntax: status,regexp)
It used before default thresholds (order stays).
Example: --threshold-overload='WARNING,bypass|booster'
=back
=cut
|
apache-2.0
|
agileowl/tapestry-5
|
tapestry-jpa/src/test/java/org/apache/tapestry5/jpa/integration/app5/ExplicitPersistenceProviderClassTest.java
|
1014
|
// Copyright 2012 The Apache Software Foundation
//
// 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 org.apache.tapestry5.jpa.integration.app5;
import org.apache.tapestry5.test.SeleniumTestCase;
import org.testng.annotations.Test;
public class ExplicitPersistenceProviderClassTest extends SeleniumTestCase
{
@Test
public void check_entitymanager_class_name() throws Exception
{
open("/");
assertEquals(getText("//span"), DummyEntityManager.class.getName());
}
}
|
apache-2.0
|
debkh/jagen
|
client/components/create-menu/directives/documentsList.html
|
543
|
<ng-form name="vm.formSave">
<div layout="row">
<md-input-container flex="100">
<label>Document</label>
<md-select name="item" ng-model="vm.document" required>
<md-option ng-value="item" ng-repeat="item in vm.documents">{{item.title}}</md-option>
</md-select>
<div class="errors"
ng-messages="vm.formSave.item.$error"
ng-if="vm.formSave.item.$touched || vm.form.$submitted">
<div ng-message="required">Required</div>
</div>
</md-input-container>
</div>
</ng-form>
|
apache-2.0
|
driftyco/ionic-site
|
content/docs/v3/3.1.0/api/components/scroll/Scroll/index.md
|
2304
|
---
layout: "fluid/docs_base"
version: "3.1.0"
versionHref: "/docs/v3/3.1.0"
path: ""
category: api
id: "scroll"
title: "Scroll"
header_sub_title: "Ionic API Documentation"
doc: "Scroll"
docType: "class"
show_preview_device: true
preview_device_url: "/docs/v3/demos/src/scroll/www/"
angular_controller: APIDemoCtrl
---
<h1 class="api-title">
<a class="anchor" name="scroll" href="#scroll"></a>
Scroll
<h3><code>ion-scroll</code></h3>
</h1>
<a class="improve-v2-docs" href="http://github.com/ionic-team/ionic/edit/v3/src/components/scroll/scroll.ts#L2">
Improve this doc
</a>
<p>Scroll is a non-flexboxed scroll area that can scroll horizontally or vertically. <code>ion-Scroll</code> Can be used in places where you may not need a full page scroller, but a highly customized one, such as image scubber or comment scroller.</p>
<!-- @usage tag -->
<h2><a class="anchor" name="usage" href="#usage"></a>Usage</h2>
<pre><code class="lang-html"><ion-scroll scrollX="true">
</ion-scroll>
<ion-scroll scrollY="true">
</ion-scroll>
<ion-scroll scrollX="true" scrollY="true">
</ion-scroll>
</code></pre>
<!-- @property tags -->
<!-- instance methods on the class -->
<!-- input methods on the class -->
<h2><a class="anchor" name="input-properties" href="#input-properties"></a>Input Properties</h2>
<table class="table param-table" style="margin:0;">
<thead>
<tr>
<th>Attr</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr>
<td>maxZoom</td>
<td><code>number</code></td>
<td><p> Set the max zoom amount.</p>
</td>
</tr>
<tr>
<td>scrollX</td>
<td><code>boolean</code></td>
<td><p> If true, scrolling along the X axis is enabled.</p>
</td>
</tr>
<tr>
<td>scrollY</td>
<td><code>boolean</code></td>
<td><p> If true, scrolling along the Y axis is enabled; requires the following CSS declaration: ion-scroll { white-space: nowrap; }</p>
</td>
</tr>
<tr>
<td>zoom</td>
<td><code>boolean</code></td>
<td><p> If true, zooming is enabled.</p>
</td>
</tr>
</tbody>
</table>
<!-- related link --><!-- end content block -->
<!-- end body block -->
|
apache-2.0
|
harshavardhana/minio
|
cmd/api-router.go
|
15882
|
/*
* MinIO Cloud Storage, (C) 2016-2020 MinIO, Inc.
*
* 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 cmd
import (
"net/http"
"github.com/gorilla/mux"
xhttp "github.com/minio/minio/cmd/http"
)
func newHTTPServerFn() *xhttp.Server {
globalObjLayerMutex.Lock()
defer globalObjLayerMutex.Unlock()
return globalHTTPServer
}
func newObjectLayerWithoutSafeModeFn() ObjectLayer {
globalObjLayerMutex.Lock()
defer globalObjLayerMutex.Unlock()
return globalObjectAPI
}
func newObjectLayerFn() ObjectLayer {
globalObjLayerMutex.Lock()
defer globalObjLayerMutex.Unlock()
if globalSafeMode {
return nil
}
return globalObjectAPI
}
func newCachedObjectLayerFn() CacheObjectLayer {
globalObjLayerMutex.Lock()
defer globalObjLayerMutex.Unlock()
if globalSafeMode {
return nil
}
return globalCacheObjectAPI
}
// objectAPIHandler implements and provides http handlers for S3 API.
type objectAPIHandlers struct {
ObjectAPI func() ObjectLayer
CacheAPI func() CacheObjectLayer
// Returns true of handlers should interpret encryption.
EncryptionEnabled func() bool
// Returns true if handlers allow SSE-KMS encryption headers.
AllowSSEKMS func() bool
}
// registerAPIRouter - registers S3 compatible APIs.
func registerAPIRouter(router *mux.Router, encryptionEnabled, allowSSEKMS bool) {
// Initialize API.
api := objectAPIHandlers{
ObjectAPI: newObjectLayerFn,
CacheAPI: newCachedObjectLayerFn,
EncryptionEnabled: func() bool {
return encryptionEnabled
},
AllowSSEKMS: func() bool {
return allowSSEKMS
},
}
// API Router
apiRouter := router.PathPrefix(SlashSeparator).Subrouter()
var routers []*mux.Router
for _, domainName := range globalDomainNames {
routers = append(routers, apiRouter.Host("{bucket:.+}."+domainName).Subrouter())
routers = append(routers, apiRouter.Host("{bucket:.+}."+domainName+":{port:.*}").Subrouter())
}
routers = append(routers, apiRouter.PathPrefix("/{bucket}").Subrouter())
for _, bucket := range routers {
// Object operations
// HeadObject
bucket.Methods(http.MethodHead).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("headobject", httpTraceAll(api.HeadObjectHandler))))
// CopyObjectPart
bucket.Methods(http.MethodPut).Path("/{object:.+}").HeadersRegexp(xhttp.AmzCopySource, ".*?(\\/|%2F).*?").HandlerFunc(maxClients(collectAPIStats("copyobjectpart", httpTraceAll(api.CopyObjectPartHandler)))).Queries("partNumber", "{partNumber:[0-9]+}", "uploadId", "{uploadId:.*}")
// PutObjectPart
bucket.Methods(http.MethodPut).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("putobjectpart", httpTraceHdrs(api.PutObjectPartHandler)))).Queries("partNumber", "{partNumber:[0-9]+}", "uploadId", "{uploadId:.*}")
// ListObjectParts
bucket.Methods(http.MethodGet).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("listobjectparts", httpTraceAll(api.ListObjectPartsHandler)))).Queries("uploadId", "{uploadId:.*}")
// CompleteMultipartUpload
bucket.Methods(http.MethodPost).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("completemutipartupload", httpTraceAll(api.CompleteMultipartUploadHandler)))).Queries("uploadId", "{uploadId:.*}")
// NewMultipartUpload
bucket.Methods(http.MethodPost).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("newmultipartupload", httpTraceAll(api.NewMultipartUploadHandler)))).Queries("uploads", "")
// AbortMultipartUpload
bucket.Methods(http.MethodDelete).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("abortmultipartupload", httpTraceAll(api.AbortMultipartUploadHandler)))).Queries("uploadId", "{uploadId:.*}")
// GetObjectACL - this is a dummy call.
bucket.Methods(http.MethodGet).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("getobjectacl", httpTraceHdrs(api.GetObjectACLHandler)))).Queries("acl", "")
// PutObjectACL - this is a dummy call.
bucket.Methods(http.MethodPut).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("putobjectacl", httpTraceHdrs(api.PutObjectACLHandler)))).Queries("acl", "")
// GetObjectTagging
bucket.Methods(http.MethodGet).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("getobjecttagging", httpTraceHdrs(api.GetObjectTaggingHandler)))).Queries("tagging", "")
// PutObjectTagging
bucket.Methods(http.MethodPut).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("putobjecttagging", httpTraceHdrs(api.PutObjectTaggingHandler)))).Queries("tagging", "")
// DeleteObjectTagging
bucket.Methods(http.MethodDelete).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("deleteobjecttagging", httpTraceHdrs(api.DeleteObjectTaggingHandler)))).Queries("tagging", "")
// SelectObjectContent
bucket.Methods(http.MethodPost).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("selectobjectcontent", httpTraceHdrs(api.SelectObjectContentHandler)))).Queries("select", "").Queries("select-type", "2")
// GetObjectRetention
bucket.Methods(http.MethodGet).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("getobjectretention", httpTraceAll(api.GetObjectRetentionHandler)))).Queries("retention", "")
// GetObjectLegalHold
bucket.Methods(http.MethodGet).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("getobjectlegalhold", httpTraceAll(api.GetObjectLegalHoldHandler)))).Queries("legal-hold", "")
// GetObject
bucket.Methods(http.MethodGet).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("getobject", httpTraceHdrs(api.GetObjectHandler))))
// CopyObject
bucket.Methods(http.MethodPut).Path("/{object:.+}").HeadersRegexp(xhttp.AmzCopySource, ".*?(\\/|%2F).*?").HandlerFunc(maxClients(collectAPIStats("copyobject", httpTraceAll(api.CopyObjectHandler))))
// PutObjectRetention
bucket.Methods(http.MethodPut).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("putobjectretention", httpTraceAll(api.PutObjectRetentionHandler)))).Queries("retention", "")
// PutObjectLegalHold
bucket.Methods(http.MethodPut).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("putobjectlegalhold", httpTraceAll(api.PutObjectLegalHoldHandler)))).Queries("legal-hold", "")
// PutObject
bucket.Methods(http.MethodPut).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("putobject", httpTraceHdrs(api.PutObjectHandler))))
// DeleteObject
bucket.Methods(http.MethodDelete).Path("/{object:.+}").HandlerFunc(
maxClients(collectAPIStats("deleteobject", httpTraceAll(api.DeleteObjectHandler))))
/// Bucket operations
// GetBucketLocation
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("getbucketlocation", httpTraceAll(api.GetBucketLocationHandler)))).Queries("location", "")
// GetBucketPolicy
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("getbucketpolicy", httpTraceAll(api.GetBucketPolicyHandler)))).Queries("policy", "")
// GetBucketLifecycle
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("getbucketlifecycle", httpTraceAll(api.GetBucketLifecycleHandler)))).Queries("lifecycle", "")
// GetBucketEncryption
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("getbucketencryption", httpTraceAll(api.GetBucketEncryptionHandler)))).Queries("encryption", "")
// Dummy Bucket Calls
// GetBucketACL -- this is a dummy call.
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("getbucketacl", httpTraceAll(api.GetBucketACLHandler)))).Queries("acl", "")
// PutBucketACL -- this is a dummy call.
bucket.Methods(http.MethodPut).HandlerFunc(
maxClients(collectAPIStats("putbucketacl", httpTraceAll(api.PutBucketACLHandler)))).Queries("acl", "")
// GetBucketCors - this is a dummy call.
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("getbucketcors", httpTraceAll(api.GetBucketCorsHandler)))).Queries("cors", "")
// GetBucketWebsiteHandler - this is a dummy call.
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("getbucketwebsite", httpTraceAll(api.GetBucketWebsiteHandler)))).Queries("website", "")
// GetBucketAccelerateHandler - this is a dummy call.
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("getbucketaccelerate", httpTraceAll(api.GetBucketAccelerateHandler)))).Queries("accelerate", "")
// GetBucketRequestPaymentHandler - this is a dummy call.
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("getbucketrequestpayment", httpTraceAll(api.GetBucketRequestPaymentHandler)))).Queries("requestPayment", "")
// GetBucketLoggingHandler - this is a dummy call.
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("getbucketlogging", httpTraceAll(api.GetBucketLoggingHandler)))).Queries("logging", "")
// GetBucketLifecycleHandler - this is a dummy call.
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("getbucketlifecycle", httpTraceAll(api.GetBucketLifecycleHandler)))).Queries("lifecycle", "")
// GetBucketReplicationHandler - this is a dummy call.
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("getbucketreplication", httpTraceAll(api.GetBucketReplicationHandler)))).Queries("replication", "")
// GetBucketTaggingHandler
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("getbuckettagging", httpTraceAll(api.GetBucketTaggingHandler)))).Queries("tagging", "")
//DeleteBucketWebsiteHandler
bucket.Methods(http.MethodDelete).HandlerFunc(
maxClients(collectAPIStats("deletebucketwebsite", httpTraceAll(api.DeleteBucketWebsiteHandler)))).Queries("website", "")
// DeleteBucketTaggingHandler
bucket.Methods(http.MethodDelete).HandlerFunc(
maxClients(collectAPIStats("deletebuckettagging", httpTraceAll(api.DeleteBucketTaggingHandler)))).Queries("tagging", "")
// GetBucketObjectLockConfig
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("getbucketobjectlockconfiguration", httpTraceAll(api.GetBucketObjectLockConfigHandler)))).Queries("object-lock", "")
// GetBucketVersioning
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("getbucketversioning", httpTraceAll(api.GetBucketVersioningHandler)))).Queries("versioning", "")
// GetBucketNotification
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("getbucketnotification", httpTraceAll(api.GetBucketNotificationHandler)))).Queries("notification", "")
// ListenBucketNotification
bucket.Methods(http.MethodGet).HandlerFunc(collectAPIStats("listenbucketnotification", httpTraceAll(api.ListenBucketNotificationHandler))).Queries("events", "{events:.*}")
// ListMultipartUploads
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("listmultipartuploads", httpTraceAll(api.ListMultipartUploadsHandler)))).Queries("uploads", "")
// ListObjectsV2M
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("listobjectsv2M", httpTraceAll(api.ListObjectsV2MHandler)))).Queries("list-type", "2", "metadata", "true")
// ListObjectsV2
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("listobjectsv2", httpTraceAll(api.ListObjectsV2Handler)))).Queries("list-type", "2")
// ListBucketVersions
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("listbucketversions", httpTraceAll(api.ListBucketObjectVersionsHandler)))).Queries("versions", "")
// ListObjectsV1 (Legacy)
bucket.Methods(http.MethodGet).HandlerFunc(
maxClients(collectAPIStats("listobjectsv1", httpTraceAll(api.ListObjectsV1Handler))))
// PutBucketLifecycle
bucket.Methods(http.MethodPut).HandlerFunc(
maxClients(collectAPIStats("putbucketlifecycle", httpTraceAll(api.PutBucketLifecycleHandler)))).Queries("lifecycle", "")
// PutBucketEncryption
bucket.Methods(http.MethodPut).HandlerFunc(
maxClients(collectAPIStats("putbucketencryption", httpTraceAll(api.PutBucketEncryptionHandler)))).Queries("encryption", "")
// PutBucketPolicy
bucket.Methods(http.MethodPut).HandlerFunc(
maxClients(collectAPIStats("putbucketpolicy", httpTraceAll(api.PutBucketPolicyHandler)))).Queries("policy", "")
// PutBucketObjectLockConfig
bucket.Methods(http.MethodPut).HandlerFunc(
maxClients(collectAPIStats("putbucketobjectlockconfig", httpTraceAll(api.PutBucketObjectLockConfigHandler)))).Queries("object-lock", "")
// PutBucketTaggingHandler
bucket.Methods(http.MethodPut).HandlerFunc(
maxClients(collectAPIStats("putbuckettagging", httpTraceAll(api.PutBucketTaggingHandler)))).Queries("tagging", "")
// PutBucketVersioning
bucket.Methods(http.MethodPut).HandlerFunc(
maxClients(collectAPIStats("putbucketversioning", httpTraceAll(api.PutBucketVersioningHandler)))).Queries("versioning", "")
// PutBucketNotification
bucket.Methods(http.MethodPut).HandlerFunc(
maxClients(collectAPIStats("putbucketnotification", httpTraceAll(api.PutBucketNotificationHandler)))).Queries("notification", "")
// PutBucket
bucket.Methods(http.MethodPut).HandlerFunc(
maxClients(collectAPIStats("putbucket", httpTraceAll(api.PutBucketHandler))))
// HeadBucket
bucket.Methods(http.MethodHead).HandlerFunc(
maxClients(collectAPIStats("headbucket", httpTraceAll(api.HeadBucketHandler))))
// PostPolicy
bucket.Methods(http.MethodPost).HeadersRegexp(xhttp.ContentType, "multipart/form-data*").HandlerFunc(
maxClients(collectAPIStats("postpolicybucket", httpTraceHdrs(api.PostPolicyBucketHandler))))
// DeleteMultipleObjects
bucket.Methods(http.MethodPost).HandlerFunc(
maxClients(collectAPIStats("deletemultipleobjects", httpTraceAll(api.DeleteMultipleObjectsHandler)))).Queries("delete", "")
// DeleteBucketPolicy
bucket.Methods(http.MethodDelete).HandlerFunc(
maxClients(collectAPIStats("deletebucketpolicy", httpTraceAll(api.DeleteBucketPolicyHandler)))).Queries("policy", "")
// DeleteBucketLifecycle
bucket.Methods(http.MethodDelete).HandlerFunc(
maxClients(collectAPIStats("deletebucketlifecycle", httpTraceAll(api.DeleteBucketLifecycleHandler)))).Queries("lifecycle", "")
// DeleteBucketEncryption
bucket.Methods(http.MethodDelete).HandlerFunc(
maxClients(collectAPIStats("deletebucketencryption", httpTraceAll(api.DeleteBucketEncryptionHandler)))).Queries("encryption", "")
// DeleteBucket
bucket.Methods(http.MethodDelete).HandlerFunc(
maxClients(collectAPIStats("deletebucket", httpTraceAll(api.DeleteBucketHandler))))
}
/// Root operation
// ListBuckets
apiRouter.Methods(http.MethodGet).Path(SlashSeparator).HandlerFunc(
maxClients(collectAPIStats("listbuckets", httpTraceAll(api.ListBucketsHandler))))
// S3 browser with signature v4 adds '//' for ListBuckets request, so rather
// than failing with UnknownAPIRequest we simply handle it for now.
apiRouter.Methods(http.MethodGet).Path(SlashSeparator + SlashSeparator).HandlerFunc(
maxClients(collectAPIStats("listbuckets", httpTraceAll(api.ListBucketsHandler))))
// If none of the routes match add default error handler routes
apiRouter.NotFoundHandler = http.HandlerFunc(collectAPIStats("notfound", httpTraceAll(errorResponseHandler)))
apiRouter.MethodNotAllowedHandler = http.HandlerFunc(collectAPIStats("methodnotallowed", httpTraceAll(errorResponseHandler)))
}
|
apache-2.0
|
VVSilinenko/java_first
|
addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/appmanager/ContactHelper.java
|
5422
|
package ru.stqa.pft.addressbook.appmanager;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import ru.stqa.pft.addressbook.model.ContactData;
import java.util.ArrayList;
import java.util.List;
/**
* Created by ВВС on 14.04.2017.
*/
public class ContactHelper extends HelperBase {
public ContactHelper(WebDriver wd) {
super(wd);
}
public void fillContactForm(ContactData contactData/*, boolean creation*/) {
type(By.name("firstname"), contactData.getFirstname());
type(By.name("lastname"), contactData.getLastname());
type(By.name("address"), contactData.getAddress());
type(By.name("home"), contactData.getHome());
type(By.name("email"), contactData.getEmail());
/*
if (creation) {
new Select(wd.findElement(By.name("new_group"))).selectByVisibleText(contactData.getGroup());
} else {
Assert.assertFalse(isElementPresent(By.name("new_group")));
}
*/
}
//Метод, нажимающий на кнопку подтверждения создания объекта
public void submitCreateContact() {
click(By.name("submit"));
}
//Метод, проверяющий наличие кнопки редактирования объекта
public boolean xpathIsPresent() {
try {
wd.findElement(By.xpath("//table[@id='maintable']/tbody/tr[2]/td[8]/a/img"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
//Метод, проверяющий наличие кнопки редактирования контакта. Если таковой нет, то метод создает новый контакт
public void editContactButton(ContactData contact){
if( ! xpathIsPresent() == true){
goToAddNewContactPage();
fillContactForm(contact);
submitCreateContact();
new NavigationHelper(wd).goToHome();
}
}
public void clickEditContact(int index) {
if (index < 0) {
click(By.xpath("//table[@id='maintable']/tbody/tr[2]/td[8]/a/img"));
} else {
click(By.xpath("//table[@id='maintable']/tbody/tr[" + (index+2) + "]/td[8]/a/img"));
}
}
public void updateContactButton() {
if (isElementPresent(By.tagName("h1"))
&& wd.findElement(By.tagName("h1")).getText().equals("Edit / add address book entry")
&& isElementPresent(By.name("update"))) {
return;
}
click(By.name("update"));
}
public boolean elementIsPresent() {
try {
wd.findElement(By.name("selected[]"));
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public void selectContactButton(ContactData contact) {
if (! elementIsPresent() == true) {
goToAddNewContactPage();
fillContactForm(contact);
submitCreateContact();
new NavigationHelper(wd).goToHome();
}
}
public void clickDeleteContact(int index) {
wd.findElements(By.name("selected[]")).get(index).click();
}
public void deleteContactButton () {
click(By.xpath("//div[@id='content']/form[2]/div[2]/input"));
}
public void goToAddNewContactPage() {
if (isElementPresent(By.tagName("h1"))
&& wd.findElement(By.tagName("h1")).getText().equals("Edit / add address book entry")
&& (isElementPresent(By.name("submit")))) {
return;
}
click(By.linkText("add new"));
}
//Метод, который высчитывает кол-во контактов в тестах создания и удаления контактов
public int getContactCount() {
return wd.findElements(By.name("selected[]")).size();
}
//Метод, который высчитывает кол-во контактов в тесте модификации контактов
public int getContactCountXpath() {
int m = 0;
for (int i = 2; i < 10; i++) {
int y = wd.findElements(By.xpath("//table[@id='maintable']/tbody/tr[" + i + "]/td[8]/a/img")).size();
m = m + y;
}
return m;
}
public List<ContactData> getContactList() {
List<ContactData> contacts = new ArrayList<ContactData>();
int size = wd.findElements(By.name("selected[]")).size();
for (int i = 2; i < (size + 2); i++){
List<WebElement> elements = wd.findElements(By.xpath("//*[@id=\"maintable\"]/tbody/tr[" + i + "]"));
for (WebElement element : elements){
String firstname = element.findElement(By.xpath("//*[@id=\"maintable\"]/tbody/tr[" + i + "]/td[3]")).getText();
String lastname = element.findElement(By.xpath("//*[@id=\"maintable\"]/tbody/tr[" + i + "]/td[2]")).getText();
int id = Integer.parseInt(element.findElement(By.tagName("input")).getAttribute("value"));
ContactData contact = new ContactData(id, firstname, lastname, null );
contacts.add(contact);
}
}
return contacts;
}
}
|
apache-2.0
|
wichtounet/jtheque-core
|
jtheque-modules/src/main/java/org/jtheque/modules/impl/RepositoryImpl.java
|
2249
|
package org.jtheque.modules.impl;
/*
* Copyright JTheque (Baptiste Wicht)
*
* 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.
*/
import org.jtheque.modules.ModuleDescription;
import org.jtheque.modules.Repository;
import org.jtheque.utils.annotations.Immutable;
import org.jtheque.utils.bean.InternationalString;
import org.jtheque.utils.collections.CollectionUtils;
import java.util.Collection;
/**
* A module repository.
*
* @author Baptiste Wicht
*/
@Immutable
final class RepositoryImpl implements Repository {
private final InternationalString title;
private final String application;
private final Collection<ModuleDescription> modules;
/**
* Create a new RepositoryImpl.
*
* @param title The title of the repository.
* @param application The application of the repository.
* @param modules The modules of the repository.
*/
RepositoryImpl(InternationalString title, String application, Collection<ModuleDescription> modules) {
super();
this.title = title;
this.application = application;
this.modules = CollectionUtils.protectedCopy(modules);
}
@Override
public String getApplication() {
return application;
}
@Override
public Collection<ModuleDescription> getModules() {
return modules;
}
@Override
public InternationalString getTitle() {
return title;
}
@Override
public String toString() {
return "Repository{" +
"title=" + title +
", application='" + application + '\'' +
", modules=" + modules +
'}';
}
}
|
apache-2.0
|
KevinLiLu/kafka
|
core/src/test/scala/unit/kafka/server/LogRecoveryTest.scala
|
9565
|
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 kafka.server
import java.util.Properties
import kafka.utils.TestUtils
import TestUtils._
import kafka.zk.ZooKeeperTestHarness
import java.io.File
import kafka.server.checkpoints.OffsetCheckpointFile
import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}
import org.apache.kafka.common.TopicPartition
import org.apache.kafka.common.serialization.{IntegerSerializer, StringSerializer}
import org.junit.{After, Before, Test}
import org.junit.Assert._
class LogRecoveryTest extends ZooKeeperTestHarness {
val replicaLagTimeMaxMs = 5000L
val replicaLagMaxMessages = 10L
val replicaFetchWaitMaxMs = 1000
val replicaFetchMinBytes = 20
val overridingProps = new Properties()
overridingProps.put(KafkaConfig.ReplicaLagTimeMaxMsProp, replicaLagTimeMaxMs.toString)
overridingProps.put(KafkaConfig.ReplicaFetchWaitMaxMsProp, replicaFetchWaitMaxMs.toString)
overridingProps.put(KafkaConfig.ReplicaFetchMinBytesProp, replicaFetchMinBytes.toString)
var configs: Seq[KafkaConfig] = null
val topic = "new-topic"
val partitionId = 0
val topicPartition = new TopicPartition(topic, partitionId)
var server1: KafkaServer = null
var server2: KafkaServer = null
def configProps1 = configs.head
def configProps2 = configs.last
val message = "hello"
var producer: KafkaProducer[Integer, String] = null
def hwFile1 = new OffsetCheckpointFile(new File(configProps1.logDirs.head, ReplicaManager.HighWatermarkFilename))
def hwFile2 = new OffsetCheckpointFile(new File(configProps2.logDirs.head, ReplicaManager.HighWatermarkFilename))
var servers = Seq.empty[KafkaServer]
// Some tests restart the brokers then produce more data. But since test brokers use random ports, we need
// to use a new producer that knows the new ports
def updateProducer() = {
if (producer != null)
producer.close()
producer = TestUtils.createProducer(
TestUtils.getBrokerListStrFromServers(servers),
keySerializer = new IntegerSerializer,
valueSerializer = new StringSerializer
)
}
@Before
override def setUp() {
super.setUp()
configs = TestUtils.createBrokerConfigs(2, zkConnect, enableControlledShutdown = false).map(KafkaConfig.fromProps(_, overridingProps))
// start both servers
server1 = TestUtils.createServer(configProps1)
server2 = TestUtils.createServer(configProps2)
servers = List(server1, server2)
// create topic with 1 partition, 2 replicas, one on each broker
createTopic(zkClient, topic, partitionReplicaAssignment = Map(0 -> Seq(0,1)), servers = servers)
// create the producer
updateProducer()
}
@After
override def tearDown() {
producer.close()
TestUtils.shutdownServers(servers)
super.tearDown()
}
@Test
def testHWCheckpointNoFailuresSingleLogSegment(): Unit = {
val numMessages = 2L
sendMessages(numMessages.toInt)
// give some time for the follower 1 to record leader HW
TestUtils.waitUntilTrue(() =>
server2.replicaManager.localLogOrException(topicPartition).highWatermark == numMessages,
"Failed to update high watermark for follower after timeout")
servers.foreach(_.replicaManager.checkpointHighWatermarks())
val leaderHW = hwFile1.read.getOrElse(topicPartition, 0L)
assertEquals(numMessages, leaderHW)
val followerHW = hwFile2.read.getOrElse(topicPartition, 0L)
assertEquals(numMessages, followerHW)
}
@Test
def testHWCheckpointWithFailuresSingleLogSegment(): Unit = {
var leader = waitUntilLeaderIsElectedOrChanged(zkClient, topic, partitionId)
assertEquals(0L, hwFile1.read.getOrElse(topicPartition, 0L))
sendMessages(1)
Thread.sleep(1000)
var hw = 1L
// kill the server hosting the preferred replica
server1.shutdown()
assertEquals(hw, hwFile1.read.getOrElse(topicPartition, 0L))
// check if leader moves to the other server
leader = waitUntilLeaderIsElectedOrChanged(zkClient, topic, partitionId, oldLeaderOpt = Some(leader))
assertEquals("Leader must move to broker 1", 1, leader)
// bring the preferred replica back
server1.startup()
// Update producer with new server settings
updateProducer()
leader = waitUntilLeaderIsElectedOrChanged(zkClient, topic, partitionId)
assertTrue("Leader must remain on broker 1, in case of ZooKeeper session expiration it can move to broker 0",
leader == 0 || leader == 1)
assertEquals(hw, hwFile1.read.getOrElse(topicPartition, 0L))
/** We plan to shutdown server2 and transfer the leadership to server1.
* With unclean leader election turned off, a prerequisite for the successful leadership transition
* is that server1 has caught up on the topicPartition, and has joined the ISR.
* In the line below, we wait until the condition is met before shutting down server2
*/
waitUntilTrue(() => server2.replicaManager.nonOfflinePartition(topicPartition).get.inSyncReplicas.size == 2,
"Server 1 is not able to join the ISR after restart")
// since server 2 was never shut down, the hw value of 30 is probably not checkpointed to disk yet
server2.shutdown()
assertEquals(hw, hwFile2.read.getOrElse(topicPartition, 0L))
server2.startup()
updateProducer()
leader = waitUntilLeaderIsElectedOrChanged(zkClient, topic, partitionId, oldLeaderOpt = Some(leader))
assertTrue("Leader must remain on broker 0, in case of ZooKeeper session expiration it can move to broker 1",
leader == 0 || leader == 1)
sendMessages(1)
hw += 1
// give some time for follower 1 to record leader HW of 60
TestUtils.waitUntilTrue(() =>
server2.replicaManager.localLogOrException(topicPartition).highWatermark == hw,
"Failed to update high watermark for follower after timeout")
// shutdown the servers to allow the hw to be checkpointed
servers.foreach(_.shutdown())
assertEquals(hw, hwFile1.read.getOrElse(topicPartition, 0L))
assertEquals(hw, hwFile2.read.getOrElse(topicPartition, 0L))
}
@Test
def testHWCheckpointNoFailuresMultipleLogSegments(): Unit = {
sendMessages(20)
val hw = 20L
// give some time for follower 1 to record leader HW of 600
TestUtils.waitUntilTrue(() =>
server2.replicaManager.localLogOrException(topicPartition).highWatermark == hw,
"Failed to update high watermark for follower after timeout")
// shutdown the servers to allow the hw to be checkpointed
servers.foreach(_.shutdown())
val leaderHW = hwFile1.read.getOrElse(topicPartition, 0L)
assertEquals(hw, leaderHW)
val followerHW = hwFile2.read.getOrElse(topicPartition, 0L)
assertEquals(hw, followerHW)
}
@Test
def testHWCheckpointWithFailuresMultipleLogSegments(): Unit = {
var leader = waitUntilLeaderIsElectedOrChanged(zkClient, topic, partitionId)
sendMessages(2)
var hw = 2L
// allow some time for the follower to get the leader HW
TestUtils.waitUntilTrue(() =>
server2.replicaManager.localLogOrException(topicPartition).highWatermark == hw,
"Failed to update high watermark for follower after timeout")
// kill the server hosting the preferred replica
server1.shutdown()
server2.shutdown()
assertEquals(hw, hwFile1.read.getOrElse(topicPartition, 0L))
assertEquals(hw, hwFile2.read.getOrElse(topicPartition, 0L))
server2.startup()
updateProducer()
// check if leader moves to the other server
leader = waitUntilLeaderIsElectedOrChanged(zkClient, topic, partitionId, oldLeaderOpt = Some(leader))
assertEquals("Leader must move to broker 1", 1, leader)
assertEquals(hw, hwFile1.read.getOrElse(topicPartition, 0L))
// bring the preferred replica back
server1.startup()
updateProducer()
assertEquals(hw, hwFile1.read.getOrElse(topicPartition, 0L))
assertEquals(hw, hwFile2.read.getOrElse(topicPartition, 0L))
sendMessages(2)
hw += 2
// allow some time for the follower to create replica
TestUtils.waitUntilTrue(() => server1.replicaManager.localLog(topicPartition).nonEmpty,
"Failed to create replica in follower after timeout")
// allow some time for the follower to get the leader HW
TestUtils.waitUntilTrue(() =>
server1.replicaManager.localLogOrException(topicPartition).highWatermark == hw,
"Failed to update high watermark for follower after timeout")
// shutdown the servers to allow the hw to be checkpointed
servers.foreach(_.shutdown())
assertEquals(hw, hwFile1.read.getOrElse(topicPartition, 0L))
assertEquals(hw, hwFile2.read.getOrElse(topicPartition, 0L))
}
private def sendMessages(n: Int) {
(0 until n).map(_ => producer.send(new ProducerRecord(topic, 0, message))).foreach(_.get)
}
}
|
apache-2.0
|
jentfoo/aws-sdk-java
|
aws-java-sdk-organizations/src/main/java/com/amazonaws/services/organizations/model/transform/DisablePolicyTypeRequestProtocolMarshaller.java
|
2748
|
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.organizations.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.organizations.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* DisablePolicyTypeRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DisablePolicyTypeRequestProtocolMarshaller implements Marshaller<Request<DisablePolicyTypeRequest>, DisablePolicyTypeRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/")
.httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true)
.operationIdentifier("AWSOrganizationsV20161128.DisablePolicyType").serviceName("AWSOrganizations").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public DisablePolicyTypeRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<DisablePolicyTypeRequest> marshall(DisablePolicyTypeRequest disablePolicyTypeRequest) {
if (disablePolicyTypeRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<DisablePolicyTypeRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING,
disablePolicyTypeRequest);
protocolMarshaller.startMarshalling();
DisablePolicyTypeRequestMarshaller.getInstance().marshall(disablePolicyTypeRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
apache-2.0
|
youwenliang/Project-6x6
|
dist/scripts/vendor/1aad92e4.modernizr.js
|
247
|
/* Modernizr (Custom Build) | MIT & BSD
* Build: http://modernizr.com/download/#-shiv-load-cssclasses-csstransforms3d-flexbox-opacity-touch-cors-svg
*/
;Modernizr.addTest("cors",!!(window.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest));
|
apache-2.0
|
lessthanoptimal/BoofCV
|
demonstrations/src/main/java/boofcv/demonstrations/imageprocessing/DemonstrationInterpolateScaleApp.java
|
4261
|
/*
* Copyright (c) 2011-2020, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* 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 boofcv.demonstrations.imageprocessing;
import boofcv.abst.distort.FDistort;
import boofcv.alg.interpolate.InterpolationType;
import boofcv.gui.DemonstrationBase;
import boofcv.gui.image.ImagePanel;
import boofcv.gui.image.ScaleOptions;
import boofcv.io.UtilIO;
import boofcv.io.image.ConvertBufferedImage;
import boofcv.struct.border.BorderType;
import boofcv.struct.image.GrayF32;
import boofcv.struct.image.ImageBase;
import boofcv.struct.image.ImageType;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Scales an image using the specified interpolation method.
*
* @author Peter Abeles
*/
public class DemonstrationInterpolateScaleApp<T extends ImageBase<T>>
extends DemonstrationBase implements ItemListener, ComponentListener
{
private final T latestImage;
private final T scaledImage;
private final ImagePanel panel = new ImagePanel();
private final JComboBox combo = new JComboBox();
private volatile InterpolationType interpType = InterpolationType.values()[0];
public DemonstrationInterpolateScaleApp(List<String> examples , ImageType<T> imageType ) {
super(examples, imageType);
panel.setScaling(ScaleOptions.NONE);
latestImage = imageType.createImage(1,1);
scaledImage = imageType.createImage(1,1);
for( InterpolationType type : InterpolationType.values() ) {
combo.addItem( type.toString() );
}
combo.addItemListener(this);
menuBar.add(combo);
panel.addComponentListener(this);
add(BorderLayout.CENTER, panel);
}
@Override
public void processImage(int sourceID, long frameID, BufferedImage buffered, ImageBase input) {
synchronized (latestImage) {
latestImage.setTo((T)input);
applyScaling();
}
}
private void applyScaling() {
scaledImage.reshape(panel.getWidth(), panel.getHeight());
if( scaledImage.width <= 0 || scaledImage.height <= 0 ) {
return;
}
if( latestImage.width != 0 && latestImage.height != 0 ) {
new FDistort(latestImage, scaledImage).interp(interpType).border(BorderType.EXTENDED).scale().apply();
BufferedImage out = ConvertBufferedImage.convertTo(scaledImage, null, true);
panel.setImageUI(out);
panel.repaint();
}
}
@Override
public void itemStateChanged(ItemEvent e) {
interpType = InterpolationType.values()[ combo.getSelectedIndex() ];
synchronized (latestImage) {
applyScaling();
}
}
@Override
public void componentResized(ComponentEvent e) {
synchronized (latestImage) {
if( inputMethod == InputMethod.IMAGE )
applyScaling();
}
}
@Override
public void componentMoved(ComponentEvent e) {}
@Override
public void componentShown(ComponentEvent e) {}
@Override
public void componentHidden(ComponentEvent e) {}
public static void main( String[] args ) {
ImageType type = ImageType.pl(3,GrayF32.class);
// ImageType type = ImageType.pl(3,GrayU8.class);
// ImageType type = ImageType.single(GrayU8.class);
// ImageType type = ImageType.il(3, InterleavedF32.class);
List<String> examples = new ArrayList<>();
examples.add( UtilIO.pathExample("eye01.jpg") );
examples.add( UtilIO.pathExample("small_sunflower.jpg"));
DemonstrationInterpolateScaleApp app = new DemonstrationInterpolateScaleApp(examples,type);
app.setPreferredSize(new Dimension(500,500));
app.openFile(new File(examples.get(0)));
app.display("Interpolation Enlarge");
}
}
|
apache-2.0
|
genericsystem/genericsystem2015
|
gs-reactor/src/main/java/org/genericsystem/reactor/contextproperties/StylesDefaults.java
|
1576
|
package org.genericsystem.reactor.contextproperties;
import org.genericsystem.reactor.Context;
import org.genericsystem.reactor.HtmlDomNode;
import org.genericsystem.reactor.Tag;
import javafx.collections.MapChangeListener;
import javafx.collections.ObservableMap;
public interface StylesDefaults extends MapStringDefaults {
public static final String STYLES = "styles";
<T> T getInheritedContextAttribute(String propertyName, Context[] model, Tag[] tag);
default ObservableMap<String, String> getDomNodeStyles(Context model) {
return getDomNodeMap(model, STYLES, HtmlDomNode::getStylesListener);
}
default void inheritStyle(Context context, String styleName) {
Context[] modelArray = new Context[] { context };
Tag[] tagArray = new Tag[] { (Tag) this };
ObservableMap<String, String> ancestorStyles = getInheritedContextAttribute(STYLES, modelArray, tagArray);
while (ancestorStyles != null)
if (ancestorStyles.containsKey(styleName)) {
ObservableMap<String, String> styles = getDomNodeStyles(context);
styles.put(styleName, ancestorStyles.get(styleName));
ancestorStyles.addListener((MapChangeListener<String, String>) c -> {
if (c.getKey().equals(styleName)) {
if (c.wasRemoved())
styles.remove(styleName);
if (c.wasAdded())
styles.put(styleName, c.getValueAdded());
}
});
break;
} else
ancestorStyles = getInheritedContextAttribute(STYLES, modelArray, tagArray);
}
default void inheritStyle(String styleName) {
addPrefixBinding(context -> inheritStyle(context, styleName));
}
}
|
apache-2.0
|
hmusavi/asn1_codec
|
ieee_1609dot2_api/per_opentype.c
|
9737
|
/*
* Copyright (c) 2007 Lev Walkin <[email protected]>. All rights reserved.
* Redistribution and modifications are permitted subject to BSD license.
*/
#include <asn_internal.h>
#include <per_support.h>
#include <constr_TYPE.h>
#include <per_opentype.h>
typedef struct uper_ugot_key {
asn_per_data_t oldpd; /* Old per data source */
size_t unclaimed;
size_t ot_moved; /* Number of bits moved by OT processing */
int repeat;
} uper_ugot_key;
static int uper_ugot_refill(asn_per_data_t *pd);
static int per_skip_bits(asn_per_data_t *pd, int skip_nbits);
static asn_dec_rval_t uper_sot_suck(asn_codec_ctx_t *,
asn_TYPE_descriptor_t *td,
const asn_per_constraints_t *constraints,
void **sptr, asn_per_data_t *pd);
/*
* Encode an "open type field".
* #10.1, #10.2
*/
int
uper_open_type_put(asn_TYPE_descriptor_t *td, asn_per_constraints_t *constraints, void *sptr, asn_per_outp_t *po) {
void *buf;
void *bptr;
ssize_t size;
size_t toGo;
ASN_DEBUG("Open type put %s ...", td->name);
size = uper_encode_to_new_buffer(td, constraints, sptr, &buf);
if(size <= 0) return -1;
for(bptr = buf, toGo = size; toGo;) {
ssize_t maySave = uper_put_length(po, toGo);
ASN_DEBUG("Prepending length %d to %s and allowing to save %d",
(int)size, td->name, (int)maySave);
if(maySave < 0) break;
if(per_put_many_bits(po, bptr, maySave * 8)) break;
bptr = (char *)bptr + maySave;
toGo -= maySave;
}
FREEMEM(buf);
if(toGo) return -1;
ASN_DEBUG("Open type put %s of length %ld + overhead (1byte?)",
td->name, (long)size);
return 0;
}
static asn_dec_rval_t
uper_open_type_get_simple(asn_codec_ctx_t *ctx, asn_TYPE_descriptor_t *td,
const asn_per_constraints_t *constraints, void **sptr, asn_per_data_t *pd) {
asn_dec_rval_t rv;
ssize_t chunk_bytes;
int repeat;
uint8_t *buf = 0;
size_t bufLen = 0;
size_t bufSize = 0;
asn_per_data_t spd;
size_t padding;
ASN__STACK_OVERFLOW_CHECK(ctx);
ASN_DEBUG("Getting open type %s...", td->name);
do {
chunk_bytes = uper_get_length(pd, -1, &repeat);
if(chunk_bytes < 0) {
FREEMEM(buf);
ASN__DECODE_STARVED;
}
if(bufLen + chunk_bytes > bufSize) {
void *ptr;
bufSize = chunk_bytes + (bufSize << 2);
ptr = REALLOC(buf, bufSize);
if(!ptr) {
FREEMEM(buf);
ASN__DECODE_FAILED;
}
buf = ptr;
}
if(per_get_many_bits(pd, buf + bufLen, 0, chunk_bytes << 3)) {
FREEMEM(buf);
ASN__DECODE_STARVED;
}
bufLen += chunk_bytes;
} while(repeat);
ASN_DEBUG("Getting open type %s encoded in %ld bytes", td->name,
(long)bufLen);
memset(&spd, 0, sizeof(spd));
spd.buffer = buf;
spd.nbits = bufLen << 3;
ASN_DEBUG_INDENT_ADD(+4);
rv = td->uper_decoder(ctx, td, constraints, sptr, &spd);
ASN_DEBUG_INDENT_ADD(-4);
if(rv.code == RC_OK) {
/* Check padding validity */
padding = spd.nbits - spd.nboff;
if ((padding < 8 ||
/* X.691#10.1.3 */
(spd.nboff == 0 && spd.nbits == 8 && spd.buffer == buf)) &&
per_get_few_bits(&spd, padding) == 0) {
/* Everything is cool */
FREEMEM(buf);
return rv;
}
FREEMEM(buf);
if(padding >= 8) {
ASN_DEBUG("Too large padding %d in open type", (int)padding);
ASN__DECODE_FAILED;
} else {
ASN_DEBUG("Non-zero padding");
ASN__DECODE_FAILED;
}
} else {
FREEMEM(buf);
/* rv.code could be RC_WMORE, nonsense in this context */
rv.code = RC_FAIL; /* Noone would give us more */
}
return rv;
}
static asn_dec_rval_t GCC_NOTUSED
uper_open_type_get_complex(asn_codec_ctx_t *ctx, asn_TYPE_descriptor_t *td,
asn_per_constraints_t *constraints, void **sptr, asn_per_data_t *pd) {
uper_ugot_key arg;
asn_dec_rval_t rv;
ssize_t padding;
ASN__STACK_OVERFLOW_CHECK(ctx);
ASN_DEBUG("Getting open type %s from %s", td->name,
per_data_string(pd));
arg.oldpd = *pd;
arg.unclaimed = 0;
arg.ot_moved = 0;
arg.repeat = 1;
pd->refill = uper_ugot_refill;
pd->refill_key = &arg;
pd->nbits = pd->nboff; /* 0 good bits at this point, will refill */
pd->moved = 0; /* This now counts the open type size in bits */
ASN_DEBUG_INDENT_ADD(+4);
rv = td->uper_decoder(ctx, td, constraints, sptr, pd);
ASN_DEBUG_INDENT_ADD(-4);
#define UPDRESTOREPD do { \
/* buffer and nboff are valid, preserve them. */ \
pd->nbits = arg.oldpd.nbits - (pd->moved - arg.ot_moved); \
pd->moved = arg.oldpd.moved + (pd->moved - arg.ot_moved); \
pd->refill = arg.oldpd.refill; \
pd->refill_key = arg.oldpd.refill_key; \
} while(0)
if(rv.code != RC_OK) {
UPDRESTOREPD;
return rv;
}
ASN_DEBUG("OpenType %s pd%s old%s unclaimed=%d, repeat=%d", td->name,
per_data_string(pd),
per_data_string(&arg.oldpd),
(int)arg.unclaimed, (int)arg.repeat);
padding = pd->moved % 8;
if(padding) {
int32_t pvalue;
if(padding > 7) {
ASN_DEBUG("Too large padding %d in open type",
(int)padding);
rv.code = RC_FAIL;
UPDRESTOREPD;
return rv;
}
padding = 8 - padding;
ASN_DEBUG("Getting padding of %d bits", (int)padding);
pvalue = per_get_few_bits(pd, padding);
switch(pvalue) {
case -1:
ASN_DEBUG("Padding skip failed");
UPDRESTOREPD;
ASN__DECODE_STARVED;
case 0: break;
default:
ASN_DEBUG("Non-blank padding (%d bits 0x%02x)",
(int)padding, (int)pvalue);
UPDRESTOREPD;
ASN__DECODE_FAILED;
}
}
if(pd->nboff != pd->nbits) {
ASN_DEBUG("Open type %s overhead pd%s old%s", td->name,
per_data_string(pd), per_data_string(&arg.oldpd));
if(1) {
UPDRESTOREPD;
ASN__DECODE_FAILED;
} else {
arg.unclaimed += pd->nbits - pd->nboff;
}
}
/* Adjust pd back so it points to original data */
UPDRESTOREPD;
/* Skip data not consumed by the decoder */
if(arg.unclaimed) {
ASN_DEBUG("Getting unclaimed %d", (int)arg.unclaimed);
switch(per_skip_bits(pd, arg.unclaimed)) {
case -1:
ASN_DEBUG("Claim of %d failed", (int)arg.unclaimed);
ASN__DECODE_STARVED;
case 0:
ASN_DEBUG("Got claim of %d", (int)arg.unclaimed);
break;
default:
/* Padding must be blank */
ASN_DEBUG("Non-blank unconsumed padding");
ASN__DECODE_FAILED;
}
arg.unclaimed = 0;
}
if(arg.repeat) {
ASN_DEBUG("Not consumed the whole thing");
rv.code = RC_FAIL;
return rv;
}
return rv;
}
asn_dec_rval_t
uper_open_type_get(asn_codec_ctx_t *ctx, asn_TYPE_descriptor_t *td,
const asn_per_constraints_t *constraints, void **sptr,
asn_per_data_t *pd) {
return uper_open_type_get_simple(ctx, td, constraints, sptr, pd);
}
int
uper_open_type_skip(asn_codec_ctx_t *ctx, asn_per_data_t *pd) {
asn_TYPE_descriptor_t s_td;
asn_dec_rval_t rv;
s_td.name = "<unknown extension>";
s_td.uper_decoder = uper_sot_suck;
rv = uper_open_type_get(ctx, &s_td, 0, 0, pd);
if(rv.code != RC_OK)
return -1;
else
return 0;
}
/*
* Internal functions.
*/
static asn_dec_rval_t
uper_sot_suck(asn_codec_ctx_t *ctx, asn_TYPE_descriptor_t *td,
const asn_per_constraints_t *constraints, void **sptr, asn_per_data_t *pd) {
asn_dec_rval_t rv;
(void)ctx;
(void)td;
(void)constraints;
(void)sptr;
while(per_get_few_bits(pd, 24) >= 0);
rv.code = RC_OK;
rv.consumed = pd->moved;
return rv;
}
static int
uper_ugot_refill(asn_per_data_t *pd) {
uper_ugot_key *arg = pd->refill_key;
ssize_t next_chunk_bytes, next_chunk_bits;
ssize_t avail;
asn_per_data_t *oldpd = &arg->oldpd;
ASN_DEBUG("REFILLING pd->moved=%ld, oldpd->moved=%ld",
(long)pd->moved, (long)oldpd->moved);
/* Advance our position to where pd is */
oldpd->buffer = pd->buffer;
oldpd->nboff = pd->nboff;
oldpd->nbits -= pd->moved - arg->ot_moved;
oldpd->moved += pd->moved - arg->ot_moved;
arg->ot_moved = pd->moved;
if(arg->unclaimed) {
/* Refill the container */
if(per_get_few_bits(oldpd, 1))
return -1;
if(oldpd->nboff == 0) {
assert(0);
return -1;
}
pd->buffer = oldpd->buffer;
pd->nboff = oldpd->nboff - 1;
pd->nbits = oldpd->nbits;
ASN_DEBUG("UNCLAIMED <- return from (pd->moved=%ld)",
(long)pd->moved);
return 0;
}
if(!arg->repeat) {
ASN_DEBUG("Want more but refill doesn't have it");
return -1;
}
next_chunk_bytes = uper_get_length(oldpd, -1, &arg->repeat);
ASN_DEBUG("Open type LENGTH %ld bytes at off %ld, repeat %ld",
(long)next_chunk_bytes, (long)oldpd->moved, (long)arg->repeat);
if(next_chunk_bytes < 0) return -1;
if(next_chunk_bytes == 0) {
pd->refill = 0; /* No more refills, naturally */
assert(!arg->repeat); /* Implementation guarantee */
}
next_chunk_bits = next_chunk_bytes << 3;
avail = oldpd->nbits - oldpd->nboff;
if(avail >= next_chunk_bits) {
pd->nbits = oldpd->nboff + next_chunk_bits;
arg->unclaimed = 0;
ASN_DEBUG("!+Parent frame %ld bits, alloting %ld [%ld..%ld] (%ld)",
(long)next_chunk_bits, (long)oldpd->moved,
(long)oldpd->nboff, (long)oldpd->nbits,
(long)(oldpd->nbits - oldpd->nboff));
} else {
pd->nbits = oldpd->nbits;
arg->unclaimed = next_chunk_bits - avail;
ASN_DEBUG("!-Parent frame %ld, require %ld, will claim %ld",
(long)avail, (long)next_chunk_bits,
(long)arg->unclaimed);
}
pd->buffer = oldpd->buffer;
pd->nboff = oldpd->nboff;
ASN_DEBUG("Refilled pd%s old%s",
per_data_string(pd), per_data_string(oldpd));
return 0;
}
static int
per_skip_bits(asn_per_data_t *pd, int skip_nbits) {
int hasNonZeroBits = 0;
while(skip_nbits > 0) {
int skip;
/* per_get_few_bits() is more efficient when nbits <= 24 */
if(skip_nbits < 24)
skip = skip_nbits;
else
skip = 24;
skip_nbits -= skip;
switch(per_get_few_bits(pd, skip)) {
case -1: return -1; /* Starving */
case 0: continue; /* Skipped empty space */
default: hasNonZeroBits = 1; continue;
}
}
return hasNonZeroBits;
}
|
apache-2.0
|
masneyb/pi-dinger
|
README.md
|
3661
|
# pi-dinger
This project allows ringing one or two bells with varying sequences from a
Raspberry Pi using a solenoid. A [Hubot](https://github.com/github/hubot)
plugin is provided so that you can ring the bell from inside a chat room.
The Hubot plugin uses [Amazon SQS](https://aws.amazon.com/sqs/) so that
your Raspberry Pi can live behind a NAT without any networking changes.

## Hardware requirements
- One or two bells with a 3 3/8-inch base.
- A solenoid for each bell. You can use different size bells or solenoids to
produce different tones. I used these two solenoids:
https://www.sparkfun.com/products/11015 and
https://www.sparkfun.com/products/10391.
- A transistor or relay for each bell so that the solenoid runs on a separate power
supply from the Raspberry Pi. Warning: Hooking the solenoid directly to your GPIO
pins can damaged your Pi.
- The solenoid will need to be mounted next to the bell. [3D mounts](mount) are
provided. Alternatively, you can use cardboard and zip ties if you do not have
access to a 3D printer.
## Software installation on the Raspberry Pi
This was tested on the latest
[Raspbian based on Debian Jessie](https://www.raspberrypi.org/downloads/raspbian/):
- Install AWS CLI: `sudo apt-get install awscli jq`.
- Add the user that this will run as to the gpio group:
`sudo usermod -a -G gpio USERNAME`.
- Edit the paths and credential environment variables in the systemd service file
_raspberry-pi/bell-dinger-sqs.service_. Specify -1 for the second GPIO pin number
if you only have one bell.
- Install systemd service:
- `sudo cp raspberry-pi/bell-dinger-sqs.service /etc/systemd/system/`
- `sudo systemctl daemon-reload`
- `sudo systemctl start bell-dinger-sqs.service`
- `sudo systemctl enable bell-dinger-sqs.service`
## Slack / Hubot integration
There is a [Hubot](https://github.com/github/hubot) script provided under [hubot/ding.coffe](./hubot/ding.coffee). You can use the [hubot-slack](https://github.com/slackhq/hubot-slack) adapter to integrate with your Slack account. If you need a host you can use [Heroku](https://gist.github.com/trey/9690729).
You will need to provide some envrionment variables to your hubot to access your AWS SQS:
```
export HUBOT_ACCESS_KEY_ID=YOUR_ACCESS_KEY_ID
export HUBOT_SECRET_ACCESS_KEY=YOUR_SECRET_ACCESS_KEY_ID
export HUBOT_AWS_REGION=YOUR_REGION
export HUBOT_AWS_SQS_URL=YOUR_SQS_URL
```
Once you have installed the [ding.coffee](./hubot/ding.coffee) script for hubot you will be able to ring the bell by messaging your hubot `ding`.
##### Example log
```
Alexander Paz [10:28 PM]
@hubot: ding
hubot [10:28 PM]
:bellhop_bell:
```
You can also specify a parameter that will be a sequence of dings.
```
@hubot ding
@hubot ding 102
```
The number determines the bell to strike. The example shown
will strike the first bell 0.05 seconds, wait 0.15 seconds,
and strike the second bell for 0.05 seconds. The code only allows
60 numbers inside a single message.
## SQS Message Structure
As mentioned above, The timing of striking the bell is coded into the queue
message body. To manually drive the queue you would need only to send a message
with correct body structure. For example, rather than driving the bell through
Slack, you could achieve the same result by placing a message on the queue being
monitored with the message body `1001`.
## Team Members
* [Brian Masney](https://github.com/masneyb)
* [Alex Paz](https://github.com/alexjpaz) - [Hubot / Slack integration](hubot/)
* [Bobby Martin](https://github.com/nyxcharon) - [3D printed mount design](mount/)
|
apache-2.0
|
shatian114/tpWeb
|
userInterface.md
|
5991
|
## 用户类
这个类的父路径为userManager,所有这个类下面的接口在ajax的路径前面都是`userManager`,如注册的接口是`regist.php`,则ajax的url参数为`/userManager/regist.php`。
### 注册(regist.php)
#### up
* name:用户名
* password: 密码(在前端将密码加密再传过来)
#### return
* 0、1如概述
* 2:用户名已注册
### 登陆(login.php)
#### up
* loginType:登陆方式,可以有一下几种
* name:用户名
* identity:身份证
* mobilePhone:手机号
* name:用户名
* password: 密码(在前端将密码加密再传过来)
#### return
* 0、1如概述
* 2:密码错误
* 3:用户名不存在
### 登出(logout.php)
#### up
* 无需上传参数
#### return
* 1:成功登出
### 修改密码(changePassword.php)
#### up
* password: 新密码
#### return
* 0、1如概述
### 根据查询类型查询用户信息(getUserData.php)
#### up
* searchType:查询的类型,可以为以下几种
* name:用户名
* remarkName:别名
* nickName:昵称
* realName:真实姓名
* uid:用户的id
* identity:身份证号
* mobilePhone:手机号
* alipay:支付宝
#### return
* 0:如概述
* 2:无此用户
* 返回json
* id:用户在数据表里的id,为递增模式
* gid:用户的用户组id,1为photon用户组,2为bloom用户组
* name:用户名
* remarkName:别名
* nickname:昵称
* realName:真实姓名
* fraction:积分
* headerImgUrl:用户头像的url
* sex:性别(n为未知,w为女,m为男)
* address:地址
* identityNum:身份证号
* identityNumVerify:身份证号是否经过了验证(0为未验证,1为已验证)
* mobilePhone:手机号
* mobilePhoneVerify:手机号是否经过了验证(0为未验证,1为已验证)
* bornDate:出生日期
* classNum:年级
* forbid:用户是否被禁制(0为开放,1为禁止)
* alipay:用户的支付宝帐号
* imgGetCount:用户所有图片的浏览总和
### 更新登陆用户的详细资料(upFullData.php)
#### up
* json格式
* remarkName:别名
* nickName:昵称
* headerImgUrl:用户头像的url
* sex:性别(n为未知,w为女,m为男)
* address:地址
* realName:真实姓名
* identityNum:身份证号
* mobilePhone:手机号
* bornDate:出生日期
* alipay:用户的支付宝帐号
#### return
* 0、1如概述
* 2:资料更新错误
### 关注用户(attention.php)
#### up
* name:被关注的用户名
#### return
* 0:如概述
* 1:双方已为好友
* 2:为被关注的粉丝
### 取消关注用户(noAttention.php)
#### up
* name:被关注的用户名
#### return
* 0:如概述
* 1:取消关注
* 2:取消关注(但是被关注的用户还关注了自己)
### 获取好友列表(friend.php)
#### up
* 无需上传
#### return
* 0:如概述
* json格式
* friendNum:好友的数量
* friend:好友数组
### 获取粉丝列表(fans.php)
#### up
* 无需上传
#### return
* 0:如概述
* json格式
* fansNum:粉丝的数量
* fans:粉丝数组
### 获取关注的人列表(fans.php)
#### up
* 无需上传
#### return
* 0:如概述
* json格式
* gzNum:关注的人的数量
* gz:关注的人的数组
### 签到(checkIn.php)
#### up
* 无需上传
#### return
* 0、1如概述
### 获取签到累计数(getCheckInSum.php)
#### up
* 无需上传
#### return
* 签到的累计数
### 获取连续签到数(getCheckContinousInSum.php)
#### up
* 无需上传
#### return
* 连续的签到数
### 增加积分(addFraction.php)
#### up
* fractionNum:需要增加的积分数
#### return
* 0、1如概述
* 2:添加失败
### 减少积分(cutFraction.php)
#### up
* fractionNum:需要减少的积分数
#### return
* 0、1如概述
* 减少失败(积分数不够)
### 禁止、删除用户(operateUser.php)
#### up
* operateType:操作类型,可以为以下两种
* delete:删除
* forbid:禁止
* id:需要禁止的用户的id
#### return
* 0、1如概述
### 查找用户的唯一资料是否存在(isExists.php)
#### up
* searchType:查找类型,可以为以下四种
* name:用户名
* mobilePhone:手机号
* identity:身份证号
* alipay:支付宝号
* seatchStr:查找的值
#### return
* 0:如概述
* 1:存在
* 2:不存在
### 给用户推送官方信息(sendMsg.php)
#### up
* uid:接收信息的用户的id
* msgContent:信息的内容
#### return
* 0、1:如概述
### 给用户推送访客信息(sendGuestMsg.php)
#### up
* uid:接收信息的用户的id
#### return
* 0、1:如概述
### 获取用户的消息息(getMsg.php)
#### up
* msgType:消息的类型,可以为以下3种
* 1:评论消息
* 2:被关注和被取消关注的消息
* 3:官方推送的消息
* 4:访客消息
#### return
* 0:如概述
* json格式的信息
* msgNum:信息的数量
* msgArr:信息的数组,每个元素为一个信息的json格式
* id:信息的id,可能是不连续的
* msgType:信息的类型(同上)
* msgContent:信息的内容(如果信息类型为关注,则1为被关注,2为被取消关注;如果信息类型为评论,则内容为评论的id;如果信息类型为推送信息,则为推送的内容)
* fromUid:发送信息的人的id(如果为访客信息,这个就是访客的id)
* msgDate:信息接收日期
* msgTime:信息接收时间
* msgRead:信息的读取状态,0为未读取
### 设置用户为推荐画师(setRecommend.php)
#### up
* uid:画师的uid
#### return
* 0、1:如概述
### 取消推荐画师(setNoRecommend.php)
#### up
* uid:画师的uid
#### return
* 0、1:如概述
### 获取推荐画师(getRecommend.php)
#### up
* 无需上传
#### return
* 0:如概述
* json格式
* recommendNum:推荐画师的个数
* recommendArr:推荐画师的信息的数组,元素为json格式的画师的详细信息(信息同查询用户信息返回的json格式)
|
apache-2.0
|
ifilipenko/Building-Blocks
|
src/BuildingBlocks.Store.RavenDB.Tests/RavenDbSessionTests.cs
|
1629
|
using FluentAssertions;
using NUnit.Framework;
using Raven.Client.Embedded;
namespace BuildingBlocks.Store.RavenDB.Tests
{
[TestFixture]
public class RavenDbSessionTests
{
private EmbeddableDocumentStore _documentStore;
private RavenDbSession _session;
[TestFixtureSetUp]
public void SetupRavenDb()
{
_documentStore = new EmbeddableDocumentStore
{
RunInMemory = true
};
_documentStore.Initialize();
}
[SetUp]
public void SetupSession()
{
_session = new RavenDbSession(_documentStore);
}
[TearDown]
public void DisposeSession()
{
_session.Dispose();
}
[Test]
public void RavenDbSessionShouldSaveEntityWithStringId()
{
var entityWithStringId = new EntityWithStringId();
_session.Save(entityWithStringId);
entityWithStringId.Id.Should().Be("EntityWithStringIds/1");
}
[Test]
public void RavenDbSessionShouldUpdateEntityWithStringId()
{
var entityWithLongId = new EntityWithLongId();
_session.Save(entityWithLongId);
entityWithLongId.Id.Should().Be(1L);
}
private class EntityWithLongId : IEntity<long>
{
public long Id { get; set; }
}
private class EntityWithStringId : IEntity<string>
{
public string Id { get; set; }
}
}
}
|
apache-2.0
|
ajor/bpftrace
|
src/bpftrace.cpp
|
17280
|
#include <assert.h>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <regex>
#include <sstream>
#include <sys/epoll.h>
#include "bcc_syms.h"
#include "perf_reader.h"
#include "bpforc.h"
#include "bpftrace.h"
#include "attached_probe.h"
#include "triggers.h"
namespace bpftrace {
int BPFtrace::add_probe(ast::Probe &p)
{
for (auto attach_point : *p.attach_points)
{
if (attach_point->provider == "BEGIN")
{
Probe probe;
probe.path = "/proc/self/exe";
probe.attach_point = "BEGIN_trigger";
probe.type = probetype(attach_point->provider);
probe.prog_name = p.name();
probe.name = p.name();
special_probes_.push_back(probe);
continue;
}
else if (attach_point->provider == "END")
{
Probe probe;
probe.path = "/proc/self/exe";
probe.attach_point = "END_trigger";
probe.type = probetype(attach_point->provider);
probe.prog_name = p.name();
probe.name = p.name();
special_probes_.push_back(probe);
continue;
}
std::vector<std::string> attach_funcs;
if (attach_point->func.find("*") != std::string::npos ||
attach_point->func.find("[") != std::string::npos &&
attach_point->func.find("]") != std::string::npos)
{
std::string file_name;
switch (probetype(attach_point->provider))
{
case ProbeType::kprobe:
case ProbeType::kretprobe:
file_name = "/sys/kernel/debug/tracing/available_filter_functions";
break;
case ProbeType::tracepoint:
file_name = "/sys/kernel/debug/tracing/available_events";
break;
default:
std::cerr << "Wildcard matches aren't available on probe type '"
<< attach_point->provider << "'" << std::endl;
return 1;
}
auto matches = find_wildcard_matches(attach_point->target,
attach_point->func,
file_name);
attach_funcs.insert(attach_funcs.end(), matches.begin(), matches.end());
}
else
{
attach_funcs.push_back(attach_point->func);
}
for (auto func : attach_funcs)
{
Probe probe;
probe.path = attach_point->target;
probe.attach_point = func;
probe.type = probetype(attach_point->provider);
probe.prog_name = p.name();
probe.name = attach_point->name(func);
probe.freq = attach_point->freq;
probes_.push_back(probe);
}
}
return 0;
}
std::set<std::string> BPFtrace::find_wildcard_matches(const std::string &prefix, const std::string &func, const std::string &file_name)
{
// Turn glob into a regex
auto regex_str = "(" + std::regex_replace(func, std::regex("\\*"), "[^\\s]*") + ")";
if (prefix != "")
regex_str = prefix + ":" + regex_str;
regex_str = "^" + regex_str;
std::regex func_regex(regex_str);
std::smatch match;
std::ifstream file(file_name);
if (file.fail())
{
std::cerr << strerror(errno) << ": " << file_name << std::endl;
return std::set<std::string>();
}
std::string line;
std::set<std::string> matches;
while (std::getline(file, line))
{
if (std::regex_search(line, match, func_regex))
{
assert(match.size() == 2);
matches.insert(match[1]);
}
}
return matches;
}
int BPFtrace::num_probes() const
{
return special_probes_.size() + probes_.size();
}
void perf_event_printer(void *cb_cookie, void *data, int size)
{
auto bpftrace = static_cast<BPFtrace*>(cb_cookie);
auto printf_id = *static_cast<uint64_t*>(data);
auto arg_data = static_cast<uint8_t*>(data) + sizeof(uint64_t);
auto fmt = std::get<0>(bpftrace->printf_args_[printf_id]).c_str();
auto args = std::get<1>(bpftrace->printf_args_[printf_id]);
std::vector<uint64_t> arg_values;
std::vector<std::unique_ptr<char>> resolved_symbols;
for (auto arg : args)
{
switch (arg.type)
{
case Type::integer:
arg_values.push_back(*(uint64_t*)arg_data);
break;
case Type::string:
arg_values.push_back((uint64_t)arg_data);
break;
case Type::sym:
resolved_symbols.emplace_back(strdup(
bpftrace->resolve_sym(*(uint64_t*)arg_data).c_str()));
arg_values.push_back((uint64_t)resolved_symbols.back().get());
break;
case Type::usym:
resolved_symbols.emplace_back(strdup(
bpftrace->resolve_usym(*(uint64_t*)arg_data).c_str()));
arg_values.push_back((uint64_t)resolved_symbols.back().get());
break;
default:
abort();
}
arg_data += arg.size;
}
switch (args.size())
{
case 0:
printf(fmt);
break;
case 1:
printf(fmt, arg_values.at(0));
break;
case 2:
printf(fmt, arg_values.at(0), arg_values.at(1));
break;
case 3:
printf(fmt, arg_values.at(0), arg_values.at(1), arg_values.at(2));
break;
case 4:
printf(fmt, arg_values.at(0), arg_values.at(1), arg_values.at(2),
arg_values.at(3));
break;
case 5:
printf(fmt, arg_values.at(0), arg_values.at(1), arg_values.at(2),
arg_values.at(3), arg_values.at(4));
break;
case 6:
printf(fmt, arg_values.at(0), arg_values.at(1), arg_values.at(2),
arg_values.at(3), arg_values.at(4), arg_values.at(5));
break;
default:
abort();
}
}
void perf_event_lost(void *cb_cookie, uint64_t lost)
{
printf("Lost %lu events\n", lost);
}
std::unique_ptr<AttachedProbe> BPFtrace::attach_probe(Probe &probe, const BpfOrc &bpforc)
{
auto func = bpforc.sections_.find("s_" + probe.prog_name);
if (func == bpforc.sections_.end())
{
std::cerr << "Code not generated for probe: " << probe.name << std::endl;
return nullptr;
}
try
{
return std::make_unique<AttachedProbe>(probe, func->second);
}
catch (std::runtime_error e)
{
std::cerr << e.what() << std::endl;
}
return nullptr;
}
int BPFtrace::run(std::unique_ptr<BpfOrc> bpforc)
{
for (Probe &probe : special_probes_)
{
auto attached_probe = attach_probe(probe, *bpforc.get());
if (attached_probe == nullptr)
return -1;
special_attached_probes_.push_back(std::move(attached_probe));
}
int epollfd = setup_perf_events();
if (epollfd < 0)
return epollfd;
BEGIN_trigger();
for (Probe &probe : probes_)
{
auto attached_probe = attach_probe(probe, *bpforc.get());
if (attached_probe == nullptr)
return -1;
attached_probes_.push_back(std::move(attached_probe));
}
poll_perf_events(epollfd);
attached_probes_.clear();
END_trigger();
poll_perf_events(epollfd, 100);
special_attached_probes_.clear();
return 0;
}
int BPFtrace::setup_perf_events()
{
int epollfd = epoll_create1(EPOLL_CLOEXEC);
if (epollfd == -1)
{
std::cerr << "Failed to create epollfd" << std::endl;
return -1;
}
std::vector<int> cpus = ebpf::get_online_cpus();
online_cpus_ = cpus.size();
for (int cpu : cpus)
{
int page_cnt = 8;
void *reader = bpf_open_perf_buffer(&perf_event_printer, &perf_event_lost, this, -1, cpu, page_cnt);
if (reader == nullptr)
{
std::cerr << "Failed to open perf buffer" << std::endl;
return -1;
}
struct epoll_event ev = {};
ev.events = EPOLLIN;
ev.data.ptr = reader;
int reader_fd = perf_reader_fd((perf_reader*)reader);
bpf_update_elem(perf_event_map_->mapfd_, &cpu, &reader_fd, 0);
if (epoll_ctl(epollfd, EPOLL_CTL_ADD, reader_fd, &ev) == -1)
{
std::cerr << "Failed to add perf reader to epoll" << std::endl;
return -1;
}
}
return epollfd;
}
void BPFtrace::poll_perf_events(int epollfd, int timeout)
{
auto events = std::vector<struct epoll_event>(online_cpus_);
while (true)
{
int ready = epoll_wait(epollfd, events.data(), online_cpus_, timeout);
if (ready <= 0)
{
return;
}
for (int i=0; i<ready; i++)
{
perf_reader_event_read((perf_reader*)events[i].data.ptr);
}
}
return;
}
int BPFtrace::print_maps()
{
for(auto &mapmap : maps_)
{
IMap &map = *mapmap.second.get();
int err;
if (map.type_.type == Type::quantize)
err = print_map_quantize(map);
else
err = print_map(map);
if (err)
return err;
}
return 0;
}
int BPFtrace::print_map(IMap &map)
{
std::vector<uint8_t> old_key;
try
{
old_key = find_empty_key(map, map.key_.size());
}
catch (std::runtime_error &e)
{
std::cerr << "Error getting key for map '" << map.name_ << "': "
<< e.what() << std::endl;
return -2;
}
auto key(old_key);
std::vector<std::pair<std::vector<uint8_t>, std::vector<uint8_t>>> values_by_key;
while (bpf_get_next_key(map.mapfd_, old_key.data(), key.data()) == 0)
{
int value_size = map.type_.size;
if (map.type_.type == Type::count)
value_size *= ncpus_;
auto value = std::vector<uint8_t>(value_size);
int err = bpf_lookup_elem(map.mapfd_, key.data(), value.data());
if (err)
{
std::cerr << "Error looking up elem: " << err << std::endl;
return -1;
}
values_by_key.push_back({key, value});
old_key = key;
}
if (map.type_.type == Type::count)
{
std::sort(values_by_key.begin(), values_by_key.end(), [&](auto &a, auto &b)
{
return reduce_value(a.second, ncpus_) < reduce_value(b.second, ncpus_);
});
}
else
{
sort_by_key(map.key_.args_, values_by_key);
};
for (auto &pair : values_by_key)
{
auto key = pair.first;
auto value = pair.second;
std::cout << map.name_ << map.key_.argument_value_list(*this, key) << ": ";
if (map.type_.type == Type::stack)
std::cout << get_stack(*(uint32_t*)value.data(), false, 8);
else if (map.type_.type == Type::ustack)
std::cout << get_stack(*(uint32_t*)value.data(), true, 8);
else if (map.type_.type == Type::sym)
std::cout << resolve_sym(*(uintptr_t*)value.data());
else if (map.type_.type == Type::usym)
std::cout << resolve_usym(*(uintptr_t*)value.data());
else if (map.type_.type == Type::string)
std::cout << value.data() << std::endl;
else if (map.type_.type == Type::count)
std::cout << reduce_value(value, ncpus_) << std::endl;
else
std::cout << *(int64_t*)value.data() << std::endl;
}
std::cout << std::endl;
return 0;
}
int BPFtrace::print_map_quantize(IMap &map)
{
// A quantize-map adds an extra 8 bytes onto the end of its key for storing
// the bucket number.
// e.g. A map defined as: @x[1, 2] = @quantize(3);
// would actually be stored with the key: [1, 2, 3]
std::vector<uint8_t> old_key;
try
{
old_key = find_empty_key(map, map.key_.size() + 8);
}
catch (std::runtime_error &e)
{
std::cerr << "Error getting key for map '" << map.name_ << "': "
<< e.what() << std::endl;
return -2;
}
auto key(old_key);
std::map<std::vector<uint8_t>, std::vector<uint64_t>> values_by_key;
while (bpf_get_next_key(map.mapfd_, old_key.data(), key.data()) == 0)
{
auto key_prefix = std::vector<uint8_t>(map.key_.size());
int bucket = key.at(map.key_.size());
for (size_t i=0; i<map.key_.size(); i++)
key_prefix.at(i) = key.at(i);
int value_size = map.type_.size * ncpus_;
auto value = std::vector<uint8_t>(value_size);
int err = bpf_lookup_elem(map.mapfd_, key.data(), value.data());
if (err)
{
std::cerr << "Error looking up elem: " << err << std::endl;
return -1;
}
if (values_by_key.find(key_prefix) == values_by_key.end())
{
// New key - create a list of buckets for it
values_by_key[key_prefix] = std::vector<uint64_t>(65);
}
values_by_key[key_prefix].at(bucket) = reduce_value(value, ncpus_);
old_key = key;
}
// Sort based on sum of counts in all buckets
std::vector<std::pair<std::vector<uint8_t>, uint64_t>> total_counts_by_key;
for (auto &map_elem : values_by_key)
{
int sum = 0;
for (size_t i=0; i<map_elem.second.size(); i++)
{
sum += map_elem.second.at(i);
}
total_counts_by_key.push_back({map_elem.first, sum});
}
std::sort(total_counts_by_key.begin(), total_counts_by_key.end(), [&](auto &a, auto &b)
{
return a.second < b.second;
});
for (auto &key_count : total_counts_by_key)
{
auto &key = key_count.first;
auto &value = values_by_key[key];
std::cout << map.name_ << map.key_.argument_value_list(*this, key) << ": " << std::endl;
print_quantize(value);
std::cout << std::endl;
}
return 0;
}
int BPFtrace::print_quantize(const std::vector<uint64_t> &values) const
{
int max_index = -1;
int max_value = 0;
for (size_t i = 0; i < values.size(); i++)
{
int v = values.at(i);
if (v != 0)
max_index = i;
if (v > max_value)
max_value = v;
}
if (max_index == -1)
return 0;
for (int i = 0; i <= max_index; i++)
{
std::ostringstream header;
if (i == 0)
{
header << "[0, 1]";
}
else
{
header << "[" << quantize_index_label(i);
header << ", " << quantize_index_label(i+1) << ")";
}
int max_width = 52;
int bar_width = values.at(i)/(float)max_value*max_width;
std::string bar(bar_width, '@');
std::cout << std::setw(16) << std::left << header.str()
<< std::setw(8) << std::right << values.at(i)
<< " |" << std::setw(max_width) << std::left << bar << "|"
<< std::endl;
}
return 0;
}
std::string BPFtrace::quantize_index_label(int power)
{
char suffix = '\0';
if (power >= 40)
{
suffix = 'T';
power -= 40;
}
else if (power >= 30)
{
suffix = 'G';
power -= 30;
}
else if (power >= 20)
{
suffix = 'M';
power -= 20;
}
else if (power >= 10)
{
suffix = 'k';
power -= 10;
}
std::ostringstream label;
label << (1<<power);
if (suffix)
label << suffix;
return label.str();
}
uint64_t BPFtrace::reduce_value(const std::vector<uint8_t> &value, int ncpus)
{
uint64_t sum = 0;
for (int i=0; i<ncpus; i++)
{
sum += *(uint64_t*)(value.data() + i*sizeof(uint64_t*));
}
return sum;
}
std::vector<uint8_t> BPFtrace::find_empty_key(IMap &map, size_t size) const
{
if (size == 0) size = 8;
auto key = std::vector<uint8_t>(size);
int value_size = map.type_.size;
if (map.type_.type == Type::count || map.type_.type == Type::quantize)
value_size *= ncpus_;
auto value = std::vector<uint8_t>(value_size);
if (bpf_lookup_elem(map.mapfd_, key.data(), value.data()))
return key;
for (auto &elem : key) elem = 0xff;
if (bpf_lookup_elem(map.mapfd_, key.data(), value.data()))
return key;
for (auto &elem : key) elem = 0x55;
if (bpf_lookup_elem(map.mapfd_, key.data(), value.data()))
return key;
throw std::runtime_error("Could not find empty key");
}
std::string BPFtrace::get_stack(uint32_t stackid, bool ustack, int indent)
{
auto stack_trace = std::vector<uint64_t>(MAX_STACK_SIZE);
int err = bpf_lookup_elem(stackid_map_->mapfd_, &stackid, stack_trace.data());
if (err)
{
std::cerr << "Error looking up stack id " << stackid << ": " << err << std::endl;
return "";
}
std::ostringstream stack;
std::string padding(indent, ' ');
stack << "\n";
for (auto &addr : stack_trace)
{
if (addr == 0)
break;
if (!ustack)
stack << padding << resolve_sym(addr, true) << std::endl;
else
stack << padding << resolve_usym(addr) << std::endl;
}
return stack.str();
}
std::string BPFtrace::resolve_sym(uintptr_t addr, bool show_offset)
{
struct bcc_symbol sym;
std::ostringstream symbol;
if (ksyms_.resolve_addr(addr, &sym))
{
symbol << sym.name;
if (show_offset)
symbol << "+" << sym.offset;
}
else
{
symbol << (void*)addr;
}
return symbol.str();
}
std::string BPFtrace::resolve_usym(uintptr_t addr) const
{
// TODO
std::ostringstream symbol;
symbol << (void*)addr;
return symbol.str();
}
void BPFtrace::sort_by_key(std::vector<SizedType> key_args,
std::vector<std::pair<std::vector<uint8_t>, std::vector<uint8_t>>> &values_by_key)
{
int arg_offset = 0;
for (auto arg : key_args)
{
arg_offset += arg.size;
}
// Sort the key arguments in reverse order so the results are sorted by
// the first argument first, then the second, etc.
for (size_t i=key_args.size(); i-- > 0; )
{
auto arg = key_args.at(i);
arg_offset -= arg.size;
if (arg.type == Type::integer)
{
if (arg.size == 8)
{
std::stable_sort(values_by_key.begin(), values_by_key.end(), [&](auto &a, auto &b)
{
return *(uint64_t*)(a.first.data() + arg_offset) < *(uint64_t*)(b.first.data() + arg_offset);
});
}
else
abort();
}
else if (arg.type == Type::string)
{
std::stable_sort(values_by_key.begin(), values_by_key.end(), [&](auto &a, auto &b)
{
return strncmp((char*)(a.first.data() + arg_offset),
(char*)(b.first.data() + arg_offset),
STRING_SIZE) < 0;
});
}
// Other types don't get sorted
}
}
} // namespace bpftrace
|
apache-2.0
|
DeLaSalleUniversity-Manila/ForkHub-macexcel
|
app/src/main/java/com/github/zion/ui/gist/StarredGistsFragment.java
|
1214
|
/*
* Copyright 2012 GitHub Inc.
*
* 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.github.zion.ui.gist;
import com.github.zion.core.ResourcePager;
import com.github.zion.core.gist.GistPager;
import org.eclipse.egit.github.core.Gist;
import org.eclipse.egit.github.core.client.PageIterator;
/**
* Fragment to display a list of Gists
*/
public class StarredGistsFragment extends GistsFragment {
@Override
protected ResourcePager<Gist> createPager() {
return new GistPager(store) {
@Override
public PageIterator<Gist> createIterator(int page, int size) {
return service.pageStarredGists(page, size);
}
};
}
}
|
apache-2.0
|
USC-NSL/SIF
|
lib/PScout/bin/parseandroidmanifest.pl
|
11115
|
#!/usr/bin/perl
use XML::Simple;
use Data::Dumper;
open MANLIST, "<manifestlist" or die $!;
while (<MANLIST>) {
chomp($_);
$file = $_;
next if (-B "$file");
print "Processing $file -----\n";
$xml = new XML::Simple;
eval{
$data = $xml->XMLin($file);
};
if ($@) {
print "ERROR! Failed to parse $file...\n";
}
$package = $data->{"package"};
if (exists $data->{"application"}->{"android:permission"}) {
print "Application ".$package." ".$data->{"application"}->{"android:permission"}."\n";
}
@perms;
if (UNIVERSAL::isa($data->{"permission"}, 'ARRAY')) {
@perms = @{$data->{"permission"}};
} elsif (exists $data->{"permission"}) {
push (@perms, $data->{"permission"});
}
foreach (@perms) {
print "Permission ".$package." ".$_->{"android:name"}." ".$_->{"android:protectionLevel"}."\n";
}
@activities;
if (UNIVERSAL::isa($data->{"application"}->{"activity"}, 'ARRAY')) {
@activities = @{$data->{"application"}->{"activity"}};
} elsif (exists $data->{"application"}->{"activity"}) {
push (@activities, $data->{"application"}->{"activity"});
}
foreach (@activities) {
if (exists $_->{"android:permission"}) {
$activityname = $_->{"android:name"};
$permname = $_->{"android:permission"};
if ($activityname =~ m/^\./) {
print "Activity ".$package.$_->{"android:name"}." ".$_->{"android:permission"}."\n";
} elsif (index($activityname, ".") == -1) {
print "Activity ".$package.".".$_->{"android:name"}." ".$_->{"android:permission"}."\n";
} else {
print "Activity ".$_->{"android:name"}." ".$_->{"android:permission"}."\n";
}
%intents = ();
if (UNIVERSAL::isa($_->{"intent-filter"}, 'ARRAY')) {
foreach $if (@{$_->{"intent-filter"}}) {
if (UNIVERSAL::isa($if->{"action"}, 'ARRAY')) {
foreach $a (@{$if->{"action"}}) {$intents{$a->{"android:name"}} = 1;}
} else {
$intents{$if->{"action"}->{"android:name"}} = 1;
}
}
} elsif (exists $_->{"intent-filter"}) {
if (UNIVERSAL::isa($_->{"intent-filter"}->{"action"}, 'ARRAY')) {
foreach $a (@{$_->{"intent-filter"}->{"action"}}) {$intents{$a->{"android:name"}} = 1;}
} else {
$intents{$_->{"intent-filter"}->{"action"}->{"android:name"}} = 1;
}
}
print "Intent:$_ $permname S\n" foreach (keys %intents);
}
#print $_->{"android:name"}."\n";
}
@activitiesalias;
if (UNIVERSAL::isa($data->{"application"}->{"activity-alias"}, 'ARRAY')) {
@activitiesalias = @{$data->{"application"}->{"activity-alias"}};
} elsif (exists $data->{"application"}->{"activity-alias"}) {
push (@activitiesalias, $data->{"application"}->{"activity-alias"});
}
foreach (@activitiesalias) {
if (exists $_->{"android:permission"}) {
$activityname = $_->{"android:name"};
$permname = $_->{"android:permission"};
if ($activityname =~ m/^\./) {
print "Activity ".$package.$_->{"android:name"}." ".$_->{"android:permission"}."\n";
} elsif (index($activityname, ".") == -1) {
print "Activity ".$package.".".$_->{"android:name"}." ".$_->{"android:permission"}."\n";
} else {
print "Activity ".$_->{"android:name"}." ".$_->{"android:permission"}."\n";
}
%intents = ();
if (UNIVERSAL::isa($_->{"intent-filter"}, 'ARRAY')) {
foreach $if (@{$_->{"intent-filter"}}) {
if (UNIVERSAL::isa($if->{"action"}, 'ARRAY')) {
foreach $a (@{$if->{"action"}}) {$intents{$a->{"android:name"}} = 1;}
} else {
$intents{$if->{"action"}->{"android:name"}} = 1;
}
}
} elsif (exists $_->{"intent-filter"}) {
if (UNIVERSAL::isa($_->{"intent-filter"}->{"action"}, 'ARRAY')) {
foreach $a (@{$_->{"intent-filter"}->{"action"}}) {$intents{$a->{"android:name"}} = 1;}
} else {
$intents{$_->{"intent-filter"}->{"action"}->{"android:name"}} = 1;
}
}
print "Intent:$_ $permname S\n" foreach (keys %intents);
}
#print $_->{"android:name"}."\n";
}
@services;
if (UNIVERSAL::isa($data->{"application"}->{"service"}, 'ARRAY')) {
@services = @{$data->{"application"}->{"service"}};
} elsif (exists $data->{"application"}->{"service"}) {
push (@services, $data->{"application"}->{"service"});
}
foreach (@services) {
if (exists $_->{"android:permission"}) {
$servicename = $_->{"android:name"};
$permname = $_->{"android:permission"};
if ($servicename =~ m/^\./) {
print "Service ".$package.$_->{"android:name"}." ".$_->{"android:permission"}."\n";
} elsif (index($servicename, ".") == -1) {
print "Service ".$package.".".$_->{"android:name"}." ".$_->{"android:permission"}."\n";
} else {
print "Service ".$_->{"android:name"}." ".$_->{"android:permission"}."\n";
}
%intents = ();
if (UNIVERSAL::isa($_->{"intent-filter"}, 'ARRAY')) {
foreach $if (@{$_->{"intent-filter"}}) {
if (UNIVERSAL::isa($if->{"action"}, 'ARRAY')) {
foreach $a (@{$if->{"action"}}) {$intents{$a->{"android:name"}} = 1;}
} else {
$intents{$if->{"action"}->{"android:name"}} = 1;
}
}
} elsif (exists $_->{"intent-filter"}) {
if (UNIVERSAL::isa($_->{"intent-filter"}->{"action"}, 'ARRAY')) {
foreach $a (@{$_->{"intent-filter"}->{"action"}}) {$intents{$a->{"android:name"}} = 1;}
} else {
$intents{$_->{"intent-filter"}->{"action"}->{"android:name"}} = 1;
}
}
print "Intent:$_ $permname S\n" foreach (keys %intents);
}
#print $_->{"android:name"}."\n";
}
@receivers;
if (UNIVERSAL::isa($data->{"application"}->{"receiver"}, 'ARRAY')) {
@receivers = @{$data->{"application"}->{"receiver"}};
} elsif (exists $data->{"application"}->{"receiver"}) {
push (@receivers, $data->{"application"}->{"receiver"});
}
foreach (@receivers) {
if (exists $_->{"android:permission"}) {
$receiverename = $_->{"android:name"};
$permname = $_->{"android:permission"};
if ($receiverename =~ m/^\./) {
print "Receiver ".$package.$_->{"android:name"}." ".$_->{"android:permission"}."\n";
} elsif (index($receiverename, ".") == -1) {
print "Receiver ".$package.".".$_->{"android:name"}." ".$_->{"android:permission"}."\n";
} else {
print "Receiver ".$_->{"android:name"}." ".$_->{"android:permission"}."\n";
}
%intents = ();
if (UNIVERSAL::isa($_->{"intent-filter"}, 'ARRAY')) {
foreach $if (@{$_->{"intent-filter"}}) {
if (UNIVERSAL::isa($if->{"action"}, 'ARRAY')) {
foreach $a (@{$if->{"action"}}) {$intents{$a->{"android:name"}} = 1;}
} else {
$intents{$if->{"action"}->{"android:name"}} = 1;
}
}
} elsif (exists $_->{"intent-filter"}) {
if (UNIVERSAL::isa($_->{"intent-filter"}->{"action"}, 'ARRAY')) {
foreach $a (@{$_->{"intent-filter"}->{"action"}}) {$intents{$a->{"android:name"}} = 1;}
} else {
$intents{$_->{"intent-filter"}->{"action"}->{"android:name"}} = 1;
}
}
print "Intent:$_ $permname S\n" foreach (keys %intents);
}
#print $_->{"android:name"}."\n";
}
@providers;
if (UNIVERSAL::isa($data->{"application"}->{"provider"}, 'ARRAY')) {
@providers = @{$data->{"application"}->{"provider"}};
} elsif (exists $data->{"application"}->{"provider"}) {
push (@providers, $data->{"application"}->{"provider"});
}
foreach (@providers) {
$providername = $_->{"android:name"};
@authorities = split(/;/, $_->{"android:authorities"});
if ($providername =~ m/^\./) {
$providername = "$package$providername";
} elsif (index($providername, ".") == -1) {
$providername = "$package.$providername";
}
foreach (@authorities) {
print "PROVIDER:$providername;AUTH:$_\n";
}
if (exists $_->{"android:readPermission"}) {
$readperm = $_->{"android:readPermission"};
foreach (@authorities) {
print "contents://".$_." R ".$readperm."\n";
}
}
if (exists $_->{"android:writePermission"}) {
$writeperm = $_->{"android:writePermission"};
foreach (@authorities) {
print "contents://".$_." W ".$writeperm."\n";
}
}
if (exists $_->{"android:permission"} && (! exists $_->{"android:readPermission"}) && (! exists $_->{"android:writePermission"})) {
$perm = $_->{"android:permission"};
foreach (@authorities) {
print "contents://".$_." R ".$perm."\n";
print "contents://".$_." W ".$perm."\n";
}
}
#deals with <path-permission>
@pathperms = ();
if (UNIVERSAL::isa($_->{"path-permission"}, 'ARRAY')) {
@pathperms = @{$_->{"path-permission"}};
} elsif (exists $_->{"path-permission"}) {
push (@pathperms, $_->{"path-permission"});
}
foreach (@pathperms) {
%pathtype = ();
if (exists $_->{"android:path"}) {
$key = $_->{"android:path"};
$pathtype{$key} = "path";
}
if (exists $_->{"android:pathPrefix"}) {
$key = $_->{"android:pathPrefix"};
$pathtype{$key} = "pathPrefix";
}
if (exists $_->{"android:pathPattern"}) {
$key = $_->{"android:pathPattern"};
$pathtype{$key} = "pathPattern";
}
if (exists $_->{"android:readPermission"}) {
$readperm = $_->{"android:readPermission"};
foreach (keys %pathtype) {
$path = $_;
foreach (@authorities) {
print "contents://".$_.$path." R ".$readperm." ".$pathtype{$path}."\n";
}
}
}
if (exists $_->{"android:writePermission"}) {
$writeperm = $_->{"android:writePermission"};
foreach (keys %pathtype) {
$path = $_;
foreach (@authorities) {
print "contents://".$_.$path." R ".$writeperm." ".$pathtype{$path}."\n";
}
}
}
if (exists $_->{"android:permission"} && (! exists $_->{"android:readPermission"}) && (! exists $_->{"android:writePermission"})) {
$perm = $_->{"android:permission"};
foreach (keys %pathtype) {
$path = $_;
foreach (@authorities) {
print "contents://".$_.$path." R ".$perm." ".$pathtype{$path}."\n";
print "contents://".$_.$path." W ".$perm." ".$pathtype{$path}."\n";
}
}
}
}
# deals with <grant-uri-permission>
if (exists $_->{"android:grantUriPermissions"}) {
$grant = $_->{"android:grantUriPermissions"};
foreach (@authorities) {
print "contents://".$_." grantUriPermissions ".$grant."\n";
}
} else {
foreach (@authorities) {
print "contents://".$_." grantUriPermissions false\n";
}
}
@grant = ();
if (UNIVERSAL::isa($_->{"grant-uri-permission"}, 'ARRAY')) {
@grant = @{$_->{"grant-uri-permission"}};
} elsif (exists $_->{"grant-uri-permission"}) {
push (@grant, $_->{"grant-uri-permission"});
}
foreach (@grant) {
if (exists $_->{"android:path"}) {
$name = $_->{"android:path"};
foreach (@authorities) {
print "contents://".$_.$name." grant-uri-permission path\n";
}
}
if (exists $_->{"android:pathPrefix"}) {
$name = $_->{"android:pathPrefix"};
foreach (@authorities) {
print "contents://".$_.$name." grant-uri-permission pathPrefix\n";
}
}
if (exists $_->{"android:pathPattern"}) {
$name = $_->{"android:pathPattern"};
foreach (@authorities) {
print "contents://".$_.$name." grant-uri-permission pathPattern\n";
}
}
}
}
}
#print Dumper($data);
#$method = "<android.os.PowerManager\$WakeLock: void acquire()>";
#if ($method =~ m/<(.*)\.([^\.]*): (.*) (.*)\(.*>/) {
# $package = $1;
# $class = $2;
# $method = $4;
# $class =~ s/\$/\./g;
# print $package."\n".$class."\n".$method."\n";
#}
#if (defined $data->{"package"}->{$package}->{"class"}->{$class}->{"method"}->{$4}) {
# print "yes\n";
#} else {
# print "no\n";
#}
|
apache-2.0
|
dave-tucker/intellij-yang
|
gen/com/intellij/lang/psi/impl/YangPrefixStmtImpl.java
|
1626
|
/*
* Copyright 2014 Red Hat, Inc.
*
* 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.
*/
// This is a generated file. Not intended for manual editing.
package com.intellij.lang.psi.impl;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import static com.intellij.lang.yang.psi.YangTypes.*;
import com.intellij.extapi.psi.ASTWrapperPsiElement;
import com.intellij.lang.psi.*;
public class YangPrefixStmtImpl extends ASTWrapperPsiElement implements YangPrefixStmt {
public YangPrefixStmtImpl(ASTNode node) {
super(node);
}
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof YangVisitor) ((YangVisitor)visitor).visitPrefixStmt(this);
else super.accept(visitor);
}
@Override
@NotNull
public YangStmtend getStmtend() {
return findNotNullChildByClass(YangStmtend.class);
}
@Override
@NotNull
public YangString getString() {
return findNotNullChildByClass(YangString.class);
}
}
|
apache-2.0
|
DaanHoogland/cloudstack
|
server/src/main/java/com/cloud/storage/upload/params/UploadParamsBase.java
|
6233
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.cloud.storage.upload.params;
import com.cloud.hypervisor.Hypervisor;
import java.util.Map;
public abstract class UploadParamsBase implements UploadParams {
private boolean isIso;
private long userId;
private String name;
private String displayText;
private Integer bits;
private boolean passwordEnabled;
private boolean requiresHVM;
private boolean isPublic;
private boolean featured;
private boolean isExtractable;
private String format;
private Long guestOSId;
private Long zoneId;
private Hypervisor.HypervisorType hypervisorType;
private String checksum;
private boolean bootable;
private String templateTag;
private long templateOwnerId;
private Map details;
private boolean sshkeyEnabled;
private boolean isDynamicallyScalable;
private boolean isRoutingType;
UploadParamsBase(long userId, String name, String displayText,
Integer bits, boolean passwordEnabled, boolean requiresHVM,
boolean isPublic, boolean featured,
boolean isExtractable, String format, Long guestOSId,
Long zoneId, Hypervisor.HypervisorType hypervisorType, String checksum,
String templateTag, long templateOwnerId,
Map details, boolean sshkeyEnabled,
boolean isDynamicallyScalable, boolean isRoutingType) {
this.userId = userId;
this.name = name;
this.displayText = displayText;
this.bits = bits;
this.passwordEnabled = passwordEnabled;
this.requiresHVM = requiresHVM;
this.isPublic = isPublic;
this.featured = featured;
this.isExtractable = isExtractable;
this.format = format;
this.guestOSId = guestOSId;
this.zoneId = zoneId;
this.hypervisorType = hypervisorType;
this.checksum = checksum;
this.templateTag = templateTag;
this.templateOwnerId = templateOwnerId;
this.details = details;
this.sshkeyEnabled = sshkeyEnabled;
this.isDynamicallyScalable = isDynamicallyScalable;
this.isRoutingType = isRoutingType;
}
UploadParamsBase(long userId, String name, String displayText, boolean isPublic, boolean isFeatured,
boolean isExtractable, Long osTypeId, Long zoneId, boolean bootable, long ownerId) {
this.userId = userId;
this.name = name;
this.displayText = displayText;
this.isPublic = isPublic;
this.featured = isFeatured;
this.isExtractable = isExtractable;
this.guestOSId = osTypeId;
this.zoneId = zoneId;
this.bootable = bootable;
this.templateOwnerId = ownerId;
}
@Override
public boolean isIso() {
return isIso;
}
@Override
public long getUserId() {
return userId;
}
@Override
public String getName() {
return name;
}
@Override
public String getDisplayText() {
return displayText;
}
@Override
public Integer getBits() {
return bits;
}
@Override
public boolean isPasswordEnabled() {
return passwordEnabled;
}
@Override
public boolean requiresHVM() {
return requiresHVM;
}
@Override
public String getUrl() {
return null;
}
@Override
public boolean isPublic() {
return isPublic;
}
@Override
public boolean isFeatured() {
return featured;
}
@Override
public boolean isExtractable() {
return isExtractable;
}
@Override
public String getFormat() {
return format;
}
@Override
public Long getGuestOSId() {
return guestOSId;
}
@Override
public Long getZoneId() {
return zoneId;
}
@Override
public Hypervisor.HypervisorType getHypervisorType() {
return hypervisorType;
}
@Override
public String getChecksum() {
return checksum;
}
@Override
public boolean isBootable() {
return bootable;
}
@Override
public String getTemplateTag() {
return templateTag;
}
@Override
public long getTemplateOwnerId() {
return templateOwnerId;
}
@Override
public Map getDetails() {
return details;
}
@Override
public boolean isSshKeyEnabled() {
return sshkeyEnabled;
}
@Override
public String getImageStoreUuid() {
return null;
}
@Override
public boolean isDynamicallyScalable() {
return isDynamicallyScalable;
}
@Override
public boolean isRoutingType() {
return isRoutingType;
}
@Override
public boolean isDirectDownload() {
return false;
}
void setIso(boolean iso) {
isIso = iso;
}
void setBootable(boolean bootable) {
this.bootable = bootable;
}
void setBits(Integer bits) {
this.bits = bits;
}
void setFormat(String format) {
this.format = format;
}
void setRequiresHVM(boolean requiresHVM) {
this.requiresHVM = requiresHVM;
}
void setHypervisorType(Hypervisor.HypervisorType hypervisorType) {
this.hypervisorType = hypervisorType;
}
}
|
apache-2.0
|
clamburger/pictshare
|
README.md
|
17053
|
# PictShare
**[Live Demo](https://www.pictshare.net)**
PictShare is a multi lingual, open source image hosting service with a simple resizing and upload API that you can host yourself.
---
[](https://rocket.haschek.at/channel/pictshare)
[](https://github.com/chrisiaut/pictshare/blob/master/LICENSE)

Table of contents
=================
* [Installation](#installation)
* [Docker](#docker)
* [On nginx](#on-nginx)
* [Why would I want to host my own images?](#why-would-i-want-to-host-my-own-images)
* [Features](#features)
* [Smart query system](#smart-query-system)
* [Available options](#available-options)
* [How does the external-upload-API work?](#how-does-the-external-upload-api-work)
* [Upload from external URL](#upload-from-external-url)
* [Example:](#example)
* [Upload via POST](#upload-via-post)
* [Upload from base64 string](#upload-from-base64-string)
* [Restriction settings](#restriction-settings)
* [UPLOAD_CODE](#upload_code)
* [IMAGE_CHANGE_CODE](#image_change_code)
* [Security and privacy](#security-and-privacy)
* [Requirements](#requirements)
* [Upgrading](#upgrading)
* [Addons](#addons)
* [Traffic analysis](#traffic-analysis)
* [Coming soon](#coming-soon)
## Installation
### Docker
The fastest way to deploy PictShare is via the [official Docker repo](https://hub.docker.com/r/hascheksolutions/pictshare/)
- [Source code & more examples](https://github.com/HaschekSolutions/PictShare-Docker)
```bash
docker run -d -p 80:80 -e "TITLE=My own PictShare" hascheksolutions/pictshare
```
[](https://www.pictshare.net/8a1dec0973.mp4)
### Without Docker
- Make sure you have PHP5 GD libraries installed: ```apt-get install php5-gd```
- Unpack the [PictShare zip](https://github.com/chrisiaut/pictshare/archive/master.zip)
- Rename /inc/example.config.inc.php to /inc/config.inc.php
- ```chmod +x bin/ffmpeg``` if you want to be able to use mp4 uploads
- The provided ffmpeg binary (bin/ffmpeg) is from [here](http://johnvansickle.com/ffmpeg/) and it's a 64bit linux executable. If you need a different one, load yours and overwrite the one provided
- (optional) You can and should put a [nginx](https://www.nginx.com/) proxy before the Apache server. That thing is just insanely fast with static content like images.
- (optional) To secure your traffic I'd highly recommend getting an [SSL Cert](https://letsencrypt.org/) for your server if you don't already have one.
UPDATES
========
- Nov. 23: Added support for MP4 uploads and conversion from gif to MP4
- Nov. 12: Created new git project: [Pictshare stats](https://github.com/chrisiaut/pictshare_stats)
- Nov. 07: Added 9 new (instagram-like) filters
- Nov. 06: Master delete code. One code to delete them all
- Nov. 01: [Restricted uploads and option-use](#restriction-settings)
- Oct. 30: [Rotations and filters](#smart-query-system)
- Oct. 10: [Album functionality](#smart-query-system) finally ready
## Why would I want to host my own images?
If you own a server (even an home server) you can host your own PictShare instance so you have full control over your content and can delete images hasslefree.
If you're an **app developer** or **sysadmin** you can use it for a centralized image hosting. With the simple upload API you can upload images to your PictShare instance and get a nice short URL
If you're a blogger like myself, you can use it as storage for your images so the images will still work even if you change blog providers or servers
## Features
- Uploads without logins or validation (that's a good thing, right?)
- Simple API to upload any image from remote servers to your instance [via URL](#upload-from-url) and [via Base64](#upload-from-base64-string)
- 100% file based - no database needed
- Simple album functions with embedding support
- Converts gif to (much smaller) MP4
- MP4 resizing
- PictShare removes all exif data so you can upload photos from your phone and all GPS tags and camera model info get wiped
- Smart [resize, filter and rotation](#smart-query-system) features
- Duplicates don't take up space. If the exact same images is uploaded twice, the second upload will link to the first
- You can control who can upload images or use filters/resizes by defining an [upload-code](#restriction-settings)
- You can set a code in your ```/inc/config.inc.php``` (MASTER_DELETE_CODE) that, if appended to any URL of an Image, will delete the image and all cached versions of it from the server
- Detailed traffic and view statistics of your images via [Pictshare stats](https://github.com/chrisiaut/pictshare_stats)
## Smart query system
PictShare images can be changed after upload just by modifying the URL. It works like this:
<span style="color:blue">https://base.domain</span>/<span style="color:red"><options></span>/<span style="color:green"><image></span>
For example: https://pictshare.net/100x100/negative/b260e36b60.jpg will show you the uploaded Image ```b260e36b60.jpg``` but resize it to 100x100 pixels and apply the "negative" filter. The original image will stay untouched.
### Available options
Original URL: ```https://www.pictshare.net/b260e36b60.jpg```
Note: If an option needs a value it works like this: ```optionname_value```. Eg: ```pixelate_10```
If there is some option that's not recognized by PictShare it's simply ignored, so this will work: https://www.pictshare.net/pictshare-is-awesome/b260e36b60.jpg and also even this will work: https://www.pictshare.net/b260e36b60.jpg/how-can-this-still/work/
Option | Paramter | Example URL | Result
-------------- | ------------------ | ---------------------- | ---------------
**Resizing** | | |
<width>**x**<height> | -none- | https://pictshare.net/20x20/b260e36b60.jpg | 
forcesize | -none- | https://pictshare.net/100x400/forcesize/b260e36b60.jpg | 
**Albums** | | |
just add multiple image hashes | -none- | https://www.pictshare.net/b260e36b60.jpg/32c9cf77c5.jpg/163484b6b1.jpg | Takes the **images** you put in the URL and makes an album out of them. All filters are supported!
embed | -none- | https://www.pictshare.net/b260e36b60.jpg/32c9cf77c5.jpg/163484b6b1.jpg/embed | Renders the album without CSS and with transparent background so you can embed them easily
responsive | -none- | https://www.pictshare.net/b260e36b60.jpg/32c9cf77c5.jpg/163484b6b1.jpg/responsive | Renders all images responsive (max-width 100%) according to screen size
<width>**x**<height> | -none- | https://www.pictshare.net/b260e36b60.jpg/32c9cf77c5.jpg/163484b6b1.jpg/150x150 | Sets the size for the thumbnails in the album
forcesize | -none- | https://www.pictshare.net/b260e36b60.jpg/32c9cf77c5.jpg/163484b6b1.jpg/100x300/forcesize | Forces thumbnail sizes to the values you provided
**GIF to mp4** | | |
mp4 | -none- | https://www.pictshare.net/mp4/102687fe65.gif | Converts gif to mp4 and displays as that. Note that you can't include that mp4 in an img tag
raw | -none- | https://www.pictshare.net/mp4/raw/102687fe65.gif | Renders the converted mp4 directly. Use with /mp4/
preview | -none- | https://www.pictshare.net/mp4/preview/102687fe65.gif | Renders the first frame of generated MP4 as JPEG. Use with /mp4/
**MP4 options** | | |
-none- | -none- | https://www.pictshare.net/65714d22f0.mp4 | Renders the mp4 embedded in a simple HTML template. This link can't be embedded into video tags, use /raw/ instead if you want to embed
raw | -none- | https://www.pictshare.net/raw/65714d22f0.mp4 | Renders the mp4 video directly so you can link it
preview | -none- | https://www.pictshare.net/preview/65714d22f0.mp4 | Renders the first frame of the MP4 as an JPEG image
**Rotating** | | |
left | -none- | https://pictshare.net/left/b260e36b60.jpg | 
right | -none- | https://pictshare.net/right/b260e36b60.jpg | 
upside | -none- | https://pictshare.net/upside/b260e36b60.jpg | 
**Filters** | | |
negative | -none- | https://pictshare.net/negative/b260e36b60.jpg | 
grayscale | -none- | https://pictshare.net/grayscale/b260e36b60.jpg | 
brightness | -255 to 255 | https://pictshare.net/brightness_100/b260e36b60.jpg | 
edgedetect | -none- | https://pictshare.net/edgedetect/b260e36b60.jpg | 
smooth | -10 to 2048 | https://pictshare.net/smooth_3/b260e36b60.jpg | 
contrast | -100 to 100 | https://pictshare.net/contrast_40/b260e36b60.jpg | 
pixelate | 0 to 100 | https://pictshare.net/pixelate_10/b260e36b60.jpg | 
blur | -none- or 0 to 5 | https://pictshare.net/blur/b260e36b60.jpg | 
sepia | -none- | https://pictshare.net/sepia/b260e36b60.jpg | 
sharpen | -none- | https://pictshare.net/sharpen/b260e36b60.jpg | 
emboss | -none- | https://pictshare.net/emboss/b260e36b60.jpg | 
cool | -none- | https://pictshare.net/cool/b260e36b60.jpg | 
light | -none- | https://pictshare.net/light/b260e36b60.jpg | 
aqua | -none- | https://pictshare.net/aqua/b260e36b60.jpg | 
fuzzy | -none- | https://pictshare.net/fuzzy/b260e36b60.jpg | 
boost | -none- | https://pictshare.net/boost/b260e36b60.jpg | 
gray | -none- | https://pictshare.net/gray/b260e36b60.jpg | 
You can also combine as many options as you want. Even multiple times! Want your image to be negative, resized, grayscale , with increased brightness and negate it again? No problem: https://pictshare.net/500x500/grayscale/negative/brightness_100/negative/b260e36b60.jpg
## How does the external-upload-API work?
### Upload from external URL
PictShare has a simple REST API to upload remote pictures. The API can be accessed via the backend.php file like this:
```https://pictshare.net/backend.php?getimage=<URL of the image you want to upload>```.
#### Example:
Request: ```https://pictshare.net/backend.php?getimage=https://www.0xf.at/css/imgs/logo.png```
The server will answer with the file name and the server path in JSON:
```json
{"status":"OK","type":"png","hash":"10ba188162.png","url":"https:\/\/pictshare.net\/10ba188162.png"}
```
### Upload via POST
Send a POST request to ```https://pictshare.net/backend.php``` and send the image in the variable ```postimage```.
Server will return JSON of uploaded data like this:
```json
{"status":"OK","type":"png","hash":"2f18a052c4.png","url":"https:\/\/pictshare.net\/2f18a052c4.png","domain":"https:\/\/pictshare.net\/"}
```
### Upload from base64 string
Just send a POST request to ```https://pictshare.net/backend.php``` and send your image in base64 as the variable name ```base64```
Server will automatically try to guess the file type (which should work in 90% of the cases) and if it can't figure it out it'll just upload it as png.
## Restriction settings
In your ```config.inc.php``` there are two values to be set: ```UPLOAD_CODE``` and ```IMAGE_CHANGE_CODE```
Both can be set to strings or multiple strings semi;colon;separated. If there is a semicolon in the string, any of the elements will work
### UPLOAD_CODE
If set, will show users a code field in the upload form. If it doesn't match your setting, files won't be uploaded.
If enabled, the Upload API will need the variable ```upload_code``` via GET (eg: ```https://pictshare.net/backend.php?getimage=https://www.0xf.at/css/imgs/logo.png&upload_code=YourUploadCodeHere```)
### IMAGE_CHANGE_CODE
If set,the [options](#available-options) will only work if the URL got the code in it. You can provide the code as option ```changecode_YourChangeCode```
For example: If enabled the image ```https://www.pictshare.net/negative/b260e36b60.jpg``` won't show the negative version but the original.
If you access the image with the code like this: ```https://www.pictshare.net/changecode_YourChangeCode/b260e36b60.jpg``` it gets cached on the server so the next time someone requests the link without providing the change-code, they'll see the inverted image (because you just created it before by accessing the image with the code)
## Security and privacy
- By hosting your own images you can delete them any time you want
- You can enable or disable upload logging. Don't want to know who uploaded stuff? Just change the setting in inc/config.inc.php
- No exif data is stored on the server, all jpegs get cleaned on upload
- You have full control over your data. PictShare doesn't need remote libaries or tracking crap
## Requirements
- Apache or Nginx Webserver with PHP
- PHP 5 GD library
- A domain or sub-domain since PictShare can't be run from a subfolder of some other domain
## nginx config
This is a simple config file that should make PictShare work on nginx
- Install php fpm: ```apt-get install php5-fpm```
- Install php Graphics libraries: ```apt-get install php5-gd```
```
server {
listen 80 default_server;
server_name your.awesome.domain.name;
root /var/www/pictshare; # or where ever you put it
index index.php;
location / {
try_files $uri $uri/ /index.php?url=$request_uri; # instead of htaccess mod_rewrite
}
location ~ \.php {
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_script_name;
}
location ~ /(upload|tmp|bin) {
deny all;
return 404;
}
}
```
## Upgrading
- Just re-download the [PictShare zip](https://github.com/chrisiaut/pictshare/archive/master.zip) file and extract and overwrite existing pictshare files. Uploads and config won't be affected.
- Check if your ```/inc/config.inc.php``` file has all settings required by the ```/inc/example.config.inc.php``` since new options might get added in new versions
Or use these commands:
```bash
# to be run from the directory where your pictshare directory sits in
git clone https://github.com/chrisiaut/pictshare.git temp
cp -r temp/* pictshare/.
rm -rf temp
```
## Addons
- Chrome Browser extension: https://chrome.google.com/webstore/detail/pictshare-1-click-imagesc/mgomffcdpnohakmlhhjmiemlolonpafc
- Source: https://github.com/chrisiaut/PictShare-Chrome-extension
- Plugin to upload images with ShareX: https://github.com/ShareX/CustomUploaders/blob/master/pictshare.net.json
## Traffic analysis
See [Pictshare stats](https://github.com/chrisiaut/pictshare_stats)
## Coming soon
- Delete codes for every uploaded image so users can delete images if no longer needed
- Albums
---
Design (c) by [Bernhard Moser](mailto://[email protected])
This is a [HASCHEK SOLUTIONS](https://haschek.solutions) project
[](https://haschek.solutions)
|
apache-2.0
|
jsmale/MassTransit
|
src/MassTransit.RabbitMqTransport/SequentialHostnameSelector.cs
|
2154
|
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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.
namespace MassTransit.RabbitMqTransport
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Logging;
/// <summary>
/// Creates an IHostnameSelector which sequentially chooses the next host name from the provided list based on index
/// </summary>
public class SequentialHostnameSelector :
IRabbitMqHostNameSelector
{
static readonly ILog _log = Logger.Get<SequentialHostnameSelector>();
string _lastHost;
int _nextHostIndex;
public SequentialHostnameSelector()
{
_nextHostIndex = 0;
_lastHost = "";
}
public string NextFrom(IList<string> options)
{
if (options == null)
throw new ArgumentNullException(nameof(options));
if (options.All(string.IsNullOrWhiteSpace))
throw new ArgumentException("There must be at least one host to use a hostname selector.", nameof(options));
do
{
_lastHost = options[_nextHostIndex % options.Count];
}
while (string.IsNullOrWhiteSpace(_lastHost));
if (_log.IsDebugEnabled)
_log.Debug($"Returning next host: {_lastHost}");
Interlocked.Increment(ref _nextHostIndex);
return _lastHost;
}
public string LastHost => _lastHost;
}
}
|
apache-2.0
|
som-snytt/dotty
|
library/src/scala/annotation/internal/ContextResultCount.scala
|
329
|
package scala.annotation
package internal
/** An annotation that's aitomatically added for methods
* that have one or more nested context closures as their right hand side.
* The parameter `n` is an Int Literal that tells how many nested closures
* there are.
*/
class ContextResultCount(n: Int) extends StaticAnnotation
|
apache-2.0
|
inputx/code-ref-doc
|
rebbit/_variables/display_names.html
|
5233
|
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title>PHPXRef 0.7.1 : Unnamed Project : Variable Reference: $display_names</title>
<link rel="stylesheet" href="../sample.css" type="text/css">
<link rel="stylesheet" href="../sample-print.css" type="text/css" media="print">
<style id="hilight" type="text/css"></style>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
</head>
<body bgcolor="#ffffff" text="#000000" link="#801800" vlink="#300540" alink="#ffffff">
<table class="pagetitle" width="100%">
<tr>
<td valign="top" class="pagetitle">
[ <a href="../index.html">Index</a> ]
</td>
<td align="right" class="pagetitle">
<h2 style="margin-bottom: 0px">PHP Cross Reference of Unnamed Project</h2>
</td>
</tr>
</table>
<!-- Generated by PHPXref 0.7.1 at Thu Oct 23 19:15:14 2014 -->
<!-- PHPXref (c) 2000-2010 Gareth Watts - [email protected] -->
<!-- http://phpxref.sourceforge.net/ -->
<script src="../phpxref.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
<!--
ext='.html';
relbase='../';
subdir='_variables';
filename='index.html';
cookiekey='phpxref';
handleNavFrame(relbase, subdir, filename);
logVariable('display_names');
// -->
</script>
<script language="JavaScript" type="text/javascript">
if (gwGetCookie('xrefnav')=='off')
document.write('<p class="navlinks">[ <a href="javascript:navOn()">Show Explorer<\/a> ]<\/p>');
else
document.write('<p class="navlinks">[ <a href="javascript:navOff()">Hide Explorer<\/a> ]<\/p>');
</script>
<noscript>
<p class="navlinks">
[ <a href="../nav.html" target="_top">Show Explorer</a> ]
[ <a href="index.html" target="_top">Hide Navbar</a> ]
</p>
</noscript>
[<a href="../index.html">Top level directory</a>]<br>
<script language="JavaScript" type="text/javascript">
<!--
document.writeln('<table align="right" class="searchbox-link"><tr><td><a class="searchbox-link" href="javascript:void(0)" onMouseOver="showSearchBox()">Search</a><br>');
document.writeln('<table border="0" cellspacing="0" cellpadding="0" class="searchbox" id="searchbox">');
document.writeln('<tr><td class="searchbox-title">');
document.writeln('<a class="searchbox-title" href="javascript:showSearchPopup()">Search History +</a>');
document.writeln('<\/td><\/tr>');
document.writeln('<tr><td class="searchbox-body" id="searchbox-body">');
document.writeln('<form name="search" style="margin:0px; padding:0px" onSubmit=\'return jump()\'>');
document.writeln('<a class="searchbox-body" href="../_classes/index.html">Class<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="classname"><br>');
document.writeln('<a id="funcsearchlink" class="searchbox-body" href="../_functions/index.html">Function<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="funcname"><br>');
document.writeln('<a class="searchbox-body" href="../_variables/index.html">Variable<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="varname"><br>');
document.writeln('<a class="searchbox-body" href="../_constants/index.html">Constant<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="constname"><br>');
document.writeln('<a class="searchbox-body" href="../_tables/index.html">Table<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="tablename"><br>');
document.writeln('<input type="submit" class="searchbox-button" value="Search">');
document.writeln('<\/form>');
document.writeln('<\/td><\/tr><\/table>');
document.writeln('<\/td><\/tr><\/table>');
// -->
</script>
<div id="search-popup" class="searchpopup"><p id="searchpopup-title" class="searchpopup-title">title</p><div id="searchpopup-body" class="searchpopup-body">Body</div><p class="searchpopup-close"><a href="javascript:gwCloseActive()">[close]</a></p></div>
<h3>Variable Cross Reference</h3>
<h2><a href="index.html#display_names">$display_names</a></h2>
<b>Defined at:</b><ul>
<li><a href="../bonfire/modules/ui/libraries/contexts.php.html">/bonfire/modules/ui/libraries/contexts.php</A> -> <a href="../bonfire/modules/ui/libraries/contexts.php.source.html#l740"> line 740</A></li>
</ul>
<br><b>Referenced 3 times:</b><ul>
<li><a href="../bonfire/modules/ui/libraries/contexts.php.html">/bonfire/modules/ui/libraries/contexts.php</a> -> <a href="../bonfire/modules/ui/libraries/contexts.php.source.html#l740"> line 740</a></li>
<li><a href="../bonfire/modules/ui/libraries/contexts.php.html">/bonfire/modules/ui/libraries/contexts.php</a> -> <a href="../bonfire/modules/ui/libraries/contexts.php.source.html#l745"> line 745</a></li>
<li><a href="../bonfire/modules/ui/libraries/contexts.php.html">/bonfire/modules/ui/libraries/contexts.php</a> -> <a href="../bonfire/modules/ui/libraries/contexts.php.source.html#l748"> line 748</a></li>
</ul>
<!-- A link to the phpxref site in your customized footer file is appreciated ;-) -->
<br><hr>
<table width="100%">
<tr><td>Generated: Thu Oct 23 19:15:14 2014</td>
<td align="right"><i>Cross-referenced by <a href="http://phpxref.sourceforge.net/">PHPXref 0.7.1</a></i></td>
</tr>
</table>
</body></html>
|
apache-2.0
|
ultradns/ultra-java-api
|
src/main/java/com/neustar/ultraservice/schema/v01/HeaderRule.java
|
3436
|
package com.neustar.ultraservice.schema.v01;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for HeaderRule complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="HeaderRule">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* </sequence>
* <attribute name="headerField" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="matchCriteria" use="required" type="{http://schema.ultraservice.neustar.com/v01/}MatchCriteria" />
* <attribute name="headerValue" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* <attribute name="caseInsensitive" use="required" type="{http://www.w3.org/2001/XMLSchema}boolean" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "HeaderRule")
public class HeaderRule {
@XmlAttribute(name = "headerField", required = true)
protected String headerField;
@XmlAttribute(name = "matchCriteria", required = true)
protected MatchCriteria matchCriteria;
@XmlAttribute(name = "headerValue", required = true)
protected String headerValue;
@XmlAttribute(name = "caseInsensitive", required = true)
protected boolean caseInsensitive;
/**
* Gets the value of the headerField property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getHeaderField() {
return headerField;
}
/**
* Sets the value of the headerField property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHeaderField(String value) {
this.headerField = value;
}
/**
* Gets the value of the matchCriteria property.
*
* @return
* possible object is
* {@link MatchCriteria }
*
*/
public MatchCriteria getMatchCriteria() {
return matchCriteria;
}
/**
* Sets the value of the matchCriteria property.
*
* @param value
* allowed object is
* {@link MatchCriteria }
*
*/
public void setMatchCriteria(MatchCriteria value) {
this.matchCriteria = value;
}
/**
* Gets the value of the headerValue property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getHeaderValue() {
return headerValue;
}
/**
* Sets the value of the headerValue property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHeaderValue(String value) {
this.headerValue = value;
}
/**
* Gets the value of the caseInsensitive property.
*
*/
public boolean isCaseInsensitive() {
return caseInsensitive;
}
/**
* Sets the value of the caseInsensitive property.
*
*/
public void setCaseInsensitive(boolean value) {
this.caseInsensitive = value;
}
}
|
apache-2.0
|
dropwizard/metrics
|
metrics-jetty11/src/test/java/io/dropwizard/metrics/jetty11/InstrumentedHandlerTest.java
|
9140
|
package io.dropwizard.metrics.jetty11;
import com.codahale.metrics.MetricRegistry;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import jakarta.servlet.AsyncContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.WriteListener;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
import static org.assertj.core.api.Assertions.assertThat;
public class InstrumentedHandlerTest {
private final HttpClient client = new HttpClient();
private final MetricRegistry registry = new MetricRegistry();
private final Server server = new Server();
private final ServerConnector connector = new ServerConnector(server);
private final InstrumentedHandler handler = new InstrumentedHandler(registry);
@Before
public void setUp() throws Exception {
handler.setName("handler");
handler.setHandler(new TestHandler());
server.addConnector(connector);
server.setHandler(handler);
server.start();
client.start();
}
@After
public void tearDown() throws Exception {
server.stop();
client.stop();
}
@Test
public void hasAName() throws Exception {
assertThat(handler.getName())
.isEqualTo("handler");
}
@Test
public void createsAndRemovesMetricsForTheHandler() throws Exception {
final ContentResponse response = client.GET(uri("/hello"));
assertThat(response.getStatus())
.isEqualTo(404);
assertThat(registry.getNames())
.containsOnly(
MetricRegistry.name(TestHandler.class, "handler.1xx-responses"),
MetricRegistry.name(TestHandler.class, "handler.2xx-responses"),
MetricRegistry.name(TestHandler.class, "handler.3xx-responses"),
MetricRegistry.name(TestHandler.class, "handler.4xx-responses"),
MetricRegistry.name(TestHandler.class, "handler.5xx-responses"),
MetricRegistry.name(TestHandler.class, "handler.percent-4xx-1m"),
MetricRegistry.name(TestHandler.class, "handler.percent-4xx-5m"),
MetricRegistry.name(TestHandler.class, "handler.percent-4xx-15m"),
MetricRegistry.name(TestHandler.class, "handler.percent-5xx-1m"),
MetricRegistry.name(TestHandler.class, "handler.percent-5xx-5m"),
MetricRegistry.name(TestHandler.class, "handler.percent-5xx-15m"),
MetricRegistry.name(TestHandler.class, "handler.requests"),
MetricRegistry.name(TestHandler.class, "handler.active-suspended"),
MetricRegistry.name(TestHandler.class, "handler.async-dispatches"),
MetricRegistry.name(TestHandler.class, "handler.async-timeouts"),
MetricRegistry.name(TestHandler.class, "handler.get-requests"),
MetricRegistry.name(TestHandler.class, "handler.put-requests"),
MetricRegistry.name(TestHandler.class, "handler.active-dispatches"),
MetricRegistry.name(TestHandler.class, "handler.trace-requests"),
MetricRegistry.name(TestHandler.class, "handler.other-requests"),
MetricRegistry.name(TestHandler.class, "handler.connect-requests"),
MetricRegistry.name(TestHandler.class, "handler.dispatches"),
MetricRegistry.name(TestHandler.class, "handler.head-requests"),
MetricRegistry.name(TestHandler.class, "handler.post-requests"),
MetricRegistry.name(TestHandler.class, "handler.options-requests"),
MetricRegistry.name(TestHandler.class, "handler.active-requests"),
MetricRegistry.name(TestHandler.class, "handler.delete-requests"),
MetricRegistry.name(TestHandler.class, "handler.move-requests")
);
server.stop();
assertThat(registry.getNames())
.isEmpty();
}
@Test
public void responseTimesAreRecordedForBlockingResponses() throws Exception {
final ContentResponse response = client.GET(uri("/blocking"));
assertThat(response.getStatus())
.isEqualTo(200);
assertResponseTimesValid();
}
@Test
@Ignore("flaky on virtual machines")
public void responseTimesAreRecordedForAsyncResponses() throws Exception {
final ContentResponse response = client.GET(uri("/async"));
assertThat(response.getStatus())
.isEqualTo(200);
assertResponseTimesValid();
}
private void assertResponseTimesValid() {
assertThat(registry.getMeters().get(metricName() + ".2xx-responses")
.getCount()).isGreaterThan(0L);
assertThat(registry.getTimers().get(metricName() + ".get-requests")
.getSnapshot().getMedian()).isGreaterThan(0.0).isLessThan(TimeUnit.SECONDS.toNanos(1));
assertThat(registry.getTimers().get(metricName() + ".requests")
.getSnapshot().getMedian()).isGreaterThan(0.0).isLessThan(TimeUnit.SECONDS.toNanos(1));
}
private String uri(String path) {
return "http://localhost:" + connector.getLocalPort() + path;
}
private String metricName() {
return MetricRegistry.name(TestHandler.class.getName(), "handler");
}
/**
* test handler.
* <p>
* Supports
* <p>
* /blocking - uses the standard servlet api
* /async - uses the 3.1 async api to complete the request
* <p>
* all other requests will return 404
*/
private static class TestHandler extends AbstractHandler {
@Override
public void handle(
String path,
Request request,
final HttpServletRequest httpServletRequest,
final HttpServletResponse httpServletResponse
) throws IOException, ServletException {
switch (path) {
case "/blocking":
request.setHandled(true);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
httpServletResponse.setStatus(200);
httpServletResponse.setContentType("text/plain");
httpServletResponse.getWriter().write("some content from the blocking request\n");
break;
case "/async":
request.setHandled(true);
final AsyncContext context = request.startAsync();
Thread t = new Thread(() -> {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
httpServletResponse.setStatus(200);
httpServletResponse.setContentType("text/plain");
final ServletOutputStream servletOutputStream;
try {
servletOutputStream = httpServletResponse.getOutputStream();
servletOutputStream.setWriteListener(
new WriteListener() {
@Override
public void onWritePossible() throws IOException {
servletOutputStream.write("some content from the async\n"
.getBytes(StandardCharsets.UTF_8));
context.complete();
}
@Override
public void onError(Throwable throwable) {
context.complete();
}
}
);
} catch (IOException e) {
context.complete();
}
});
t.start();
break;
default:
break;
}
}
}
}
|
apache-2.0
|
UniversalDependencies/docs
|
treebanks/bg_btb/bg-feat-NumType.md
|
4252
|
---
layout: base
title: 'Statistics of NumType in UD_Bulgarian'
udver: '2'
---
## Treebank Statistics: UD_Bulgarian: Features: `NumType`
This feature is universal.
It occurs with 2 different values: `Card`, `Ord`.
3629 tokens (2%) have a non-empty value of `NumType`.
726 types (3%) occur at least once with a non-empty value of `NumType`.
557 lemmas (4%) occur at least once with a non-empty value of `NumType`.
The feature is used with 3 part-of-speech tags: <tt><a href="bg-pos-NUM.html">NUM</a></tt> (2104; 1% instances), <tt><a href="bg-pos-ADJ.html">ADJ</a></tt> (906; 1% instances), <tt><a href="bg-pos-ADV.html">ADV</a></tt> (619; 0% instances).
### `NUM`
2104 <tt><a href="bg-pos-NUM.html">NUM</a></tt> tokens (100% of all `NUM` tokens) have a non-empty value of `NumType`.
The most frequent other feature values with which `NUM` and `NumType` co-occurred: <tt><a href="bg-feat-Definite.html">Definite</a></tt><tt>=Ind</tt> (1956; 93%), <tt><a href="bg-feat-Number.html">Number</a></tt><tt>=Plur</tt> (1862; 88%), <tt><a href="bg-feat-Gender.html">Gender</a></tt><tt>=EMPTY</tt> (1589; 76%).
`NUM` tokens may have the following values of `NumType`:
* `Card` (2101; 100% of non-empty `NumType`): <em>две, един, два, 2, една, 1, 3, три, 10, двамата</em>
* `Ord` (3; 0% of non-empty `NumType`): <em>02, 08, 2000</em>
* `EMPTY` (2): <em>-, 3</em>
<table>
<tr><th>Paradigm <i>2000</i></th><th><tt>Card</tt></th><th><tt>Ord</tt></th></tr>
<tr><td><tt>_</tt></td><td></td><td><em>2000</em></td></tr>
<tr><td><tt><tt><a href="bg-feat-Definite.html">Definite</a></tt><tt>=Ind</tt>|<tt><a href="bg-feat-Number.html">Number</a></tt><tt>=Plur</tt></tt></td><td><em>2000</em></td><td></td></tr>
</table>
`NumType` seems to be **lexical feature** of `NUM`. 100% lemmas (413) occur only with one value of `NumType`.
### `ADJ`
906 <tt><a href="bg-pos-ADJ.html">ADJ</a></tt> tokens (7% of all `ADJ` tokens) have a non-empty value of `NumType`.
The most frequent other feature values with which `ADJ` and `NumType` co-occurred: <tt><a href="bg-feat-Aspect.html">Aspect</a></tt><tt>=EMPTY</tt> (906; 100%), <tt><a href="bg-feat-Degree.html">Degree</a></tt><tt>=Pos</tt> (906; 100%), <tt><a href="bg-feat-VerbForm.html">VerbForm</a></tt><tt>=EMPTY</tt> (906; 100%), <tt><a href="bg-feat-Voice.html">Voice</a></tt><tt>=EMPTY</tt> (906; 100%), <tt><a href="bg-feat-Number.html">Number</a></tt><tt>=Sing</tt> (847; 93%), <tt><a href="bg-feat-Definite.html">Definite</a></tt><tt>=Ind</tt> (667; 74%).
`ADJ` tokens may have the following values of `NumType`:
* `Ord` (906; 100% of non-empty `NumType`): <em>2001, 2000, първата, първите, 1, втори, първи, 1998, II, втора</em>
* `EMPTY` (12685): <em>други, народното, българската, нова, другите, нови, европейската, последните, друг, цялата</em>
`NumType` seems to be **lexical feature** of `ADJ`. 100% lemmas (163) occur only with one value of `NumType`.
### `ADV`
619 <tt><a href="bg-pos-ADV.html">ADV</a></tt> tokens (9% of all `ADV` tokens) have a non-empty value of `NumType`.
The most frequent other feature values with which `ADV` and `NumType` co-occurred: <tt><a href="bg-feat-PronType.html">PronType</a></tt><tt>=EMPTY</tt> (499; 81%), <tt><a href="bg-feat-Degree.html">Degree</a></tt><tt>=Pos</tt> (463; 75%).
`ADV` tokens may have the following values of `NumType`:
* `Card` (619; 100% of non-empty `NumType`): <em>много, повече, толкова, малко, повечето, колко, колкото, по-малко, най-много, доколкото</em>
* `EMPTY` (5939): <em>още, вчера, само, вече, когато, защото, обаче, сега, как, така</em>
## Relations with Agreement in `NumType`
The 10 most frequent relations where parent and child node agree in `NumType`:
<tt>NUM --[<tt><a href="bg-dep-flat.html">flat</a></tt>]--> NUM</tt> (52; 100%),
<tt>NUM --[<tt><a href="bg-dep-conj.html">conj</a></tt>]--> NUM</tt> (39; 100%),
<tt>NUM --[<tt><a href="bg-dep-nmod.html">nmod</a></tt>]--> NUM</tt> (34; 100%),
<tt>ADJ --[<tt><a href="bg-dep-conj.html">conj</a></tt>]--> ADJ</tt> (13; 87%).
|
apache-2.0
|
jumpstarter-io/nova
|
nova/api/openstack/compute/contrib/floating_ips.py
|
12423
|
# Copyright 2011 OpenStack Foundation
# Copyright (c) 2011 X.commerce, a business unit of eBay Inc.
# Copyright 2011 Grid Dynamics
# Copyright 2011 Eldar Nugaev, Kirill Shileev, Ilya Alekseyev
#
# 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.
import webob
from nova.api.openstack import common
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.api.openstack import xmlutil
from nova import compute
from nova.compute import utils as compute_utils
from nova import exception
from nova.i18n import _
from nova.i18n import _LW
from nova import network
from nova.openstack.common import log as logging
from nova.openstack.common import uuidutils
LOG = logging.getLogger(__name__)
authorize = extensions.extension_authorizer('compute', 'floating_ips')
def make_float_ip(elem):
elem.set('id')
elem.set('ip')
elem.set('pool')
elem.set('fixed_ip')
elem.set('instance_id')
class FloatingIPTemplate(xmlutil.TemplateBuilder):
def construct(self):
root = xmlutil.TemplateElement('floating_ip',
selector='floating_ip')
make_float_ip(root)
return xmlutil.MasterTemplate(root, 1)
class FloatingIPsTemplate(xmlutil.TemplateBuilder):
def construct(self):
root = xmlutil.TemplateElement('floating_ips')
elem = xmlutil.SubTemplateElement(root, 'floating_ip',
selector='floating_ips')
make_float_ip(elem)
return xmlutil.MasterTemplate(root, 1)
def _translate_floating_ip_view(floating_ip):
result = {
'id': floating_ip['id'],
'ip': floating_ip['address'],
'pool': floating_ip['pool'],
}
try:
result['fixed_ip'] = floating_ip['fixed_ip']['address']
except (TypeError, KeyError, AttributeError):
result['fixed_ip'] = None
try:
result['instance_id'] = floating_ip['fixed_ip']['instance_uuid']
except (TypeError, KeyError, AttributeError):
result['instance_id'] = None
return {'floating_ip': result}
def _translate_floating_ips_view(floating_ips):
return {'floating_ips': [_translate_floating_ip_view(ip)['floating_ip']
for ip in floating_ips]}
def get_instance_by_floating_ip_addr(self, context, address):
snagiibfa = self.network_api.get_instance_id_by_floating_address
instance_id = snagiibfa(context, address)
if instance_id:
return self.compute_api.get(context, instance_id)
def disassociate_floating_ip(self, context, instance, address):
try:
self.network_api.disassociate_floating_ip(context, instance, address)
except exception.Forbidden:
raise webob.exc.HTTPForbidden()
except exception.CannotDisassociateAutoAssignedFloatingIP:
msg = _('Cannot disassociate auto assigned floating ip')
raise webob.exc.HTTPForbidden(explanation=msg)
class FloatingIPController(object):
"""The Floating IPs API controller for the OpenStack API."""
def __init__(self):
self.compute_api = compute.API()
self.network_api = network.API()
super(FloatingIPController, self).__init__()
@wsgi.serializers(xml=FloatingIPTemplate)
def show(self, req, id):
"""Return data about the given floating ip."""
context = req.environ['nova.context']
authorize(context)
try:
floating_ip = self.network_api.get_floating_ip(context, id)
except (exception.NotFound, exception.InvalidID):
msg = _("Floating ip not found for id %s") % id
raise webob.exc.HTTPNotFound(explanation=msg)
return _translate_floating_ip_view(floating_ip)
@wsgi.serializers(xml=FloatingIPsTemplate)
def index(self, req):
"""Return a list of floating ips allocated to a project."""
context = req.environ['nova.context']
authorize(context)
floating_ips = self.network_api.get_floating_ips_by_project(context)
return _translate_floating_ips_view(floating_ips)
@wsgi.serializers(xml=FloatingIPTemplate)
def create(self, req, body=None):
context = req.environ['nova.context']
authorize(context)
pool = None
if body and 'pool' in body:
pool = body['pool']
try:
address = self.network_api.allocate_floating_ip(context, pool)
ip = self.network_api.get_floating_ip_by_address(context, address)
except exception.NoMoreFloatingIps:
if pool:
msg = _("No more floating ips in pool %s.") % pool
else:
msg = _("No more floating ips available.")
raise webob.exc.HTTPNotFound(explanation=msg)
except exception.FloatingIpLimitExceeded:
if pool:
msg = _("IP allocation over quota in pool %s.") % pool
else:
msg = _("IP allocation over quota.")
raise webob.exc.HTTPForbidden(explanation=msg)
except exception.FloatingIpPoolNotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.format_message())
return _translate_floating_ip_view(ip)
def delete(self, req, id):
context = req.environ['nova.context']
authorize(context)
# get the floating ip object
try:
floating_ip = self.network_api.get_floating_ip(context, id)
except (exception.NotFound, exception.InvalidID):
msg = _("Floating ip not found for id %s") % id
raise webob.exc.HTTPNotFound(explanation=msg)
address = floating_ip['address']
# get the associated instance object (if any)
instance = get_instance_by_floating_ip_addr(self, context, address)
try:
self.network_api.disassociate_and_release_floating_ip(
context, instance, floating_ip)
except exception.Forbidden:
raise webob.exc.HTTPForbidden()
except exception.CannotDisassociateAutoAssignedFloatingIP:
msg = _('Cannot disassociate auto assigned floating ip')
raise webob.exc.HTTPForbidden(explanation=msg)
return webob.Response(status_int=202)
class FloatingIPActionController(wsgi.Controller):
def __init__(self, ext_mgr=None, *args, **kwargs):
super(FloatingIPActionController, self).__init__(*args, **kwargs)
self.compute_api = compute.API()
self.network_api = network.API()
self.ext_mgr = ext_mgr
@wsgi.action('addFloatingIp')
def _add_floating_ip(self, req, id, body):
"""Associate floating_ip to an instance."""
context = req.environ['nova.context']
authorize(context)
try:
address = body['addFloatingIp']['address']
except TypeError:
msg = _("Missing parameter dict")
raise webob.exc.HTTPBadRequest(explanation=msg)
except KeyError:
msg = _("Address not specified")
raise webob.exc.HTTPBadRequest(explanation=msg)
instance = common.get_instance(self.compute_api, context, id)
cached_nwinfo = compute_utils.get_nw_info_for_instance(instance)
if not cached_nwinfo:
msg = _('No nw_info cache associated with instance')
raise webob.exc.HTTPBadRequest(explanation=msg)
fixed_ips = cached_nwinfo.fixed_ips()
if not fixed_ips:
msg = _('No fixed ips associated to instance')
raise webob.exc.HTTPBadRequest(explanation=msg)
fixed_address = None
if self.ext_mgr.is_loaded('os-extended-floating-ips'):
if 'fixed_address' in body['addFloatingIp']:
fixed_address = body['addFloatingIp']['fixed_address']
for fixed in fixed_ips:
if fixed['address'] == fixed_address:
break
else:
msg = _('Specified fixed address not assigned to instance')
raise webob.exc.HTTPBadRequest(explanation=msg)
if not fixed_address:
fixed_address = fixed_ips[0]['address']
if len(fixed_ips) > 1:
LOG.warn(_LW('multiple fixed_ips exist, using the first: '
'%s'), fixed_address)
try:
self.network_api.associate_floating_ip(context, instance,
floating_address=address,
fixed_address=fixed_address)
except exception.FloatingIpAssociated:
msg = _('floating ip is already associated')
raise webob.exc.HTTPBadRequest(explanation=msg)
except exception.NoFloatingIpInterface:
msg = _('l3driver call to add floating ip failed')
raise webob.exc.HTTPBadRequest(explanation=msg)
except exception.FloatingIpNotFoundForAddress:
msg = _('floating ip not found')
raise webob.exc.HTTPNotFound(explanation=msg)
except exception.Forbidden as e:
raise webob.exc.HTTPForbidden(explanation=e.format_message())
except Exception:
msg = _('Error. Unable to associate floating ip')
LOG.exception(msg)
raise webob.exc.HTTPBadRequest(explanation=msg)
return webob.Response(status_int=202)
@wsgi.action('removeFloatingIp')
def _remove_floating_ip(self, req, id, body):
"""Dissociate floating_ip from an instance."""
context = req.environ['nova.context']
authorize(context)
try:
address = body['removeFloatingIp']['address']
except TypeError:
msg = _("Missing parameter dict")
raise webob.exc.HTTPBadRequest(explanation=msg)
except KeyError:
msg = _("Address not specified")
raise webob.exc.HTTPBadRequest(explanation=msg)
# get the floating ip object
try:
floating_ip = self.network_api.get_floating_ip_by_address(context,
address)
except exception.FloatingIpNotFoundForAddress:
msg = _("floating ip not found")
raise webob.exc.HTTPNotFound(explanation=msg)
# get the associated instance object (if any)
instance = get_instance_by_floating_ip_addr(self, context, address)
# disassociate if associated
if (instance and
floating_ip.get('fixed_ip_id') and
(uuidutils.is_uuid_like(id) and
[instance['uuid'] == id] or
[instance['id'] == id])[0]):
try:
disassociate_floating_ip(self, context, instance, address)
except exception.FloatingIpNotAssociated:
msg = _('Floating ip is not associated')
raise webob.exc.HTTPBadRequest(explanation=msg)
return webob.Response(status_int=202)
else:
msg = _("Floating ip %(address)s is not associated with instance "
"%(id)s.") % {'address': address, 'id': id}
raise webob.exc.HTTPUnprocessableEntity(explanation=msg)
class Floating_ips(extensions.ExtensionDescriptor):
"""Floating IPs support."""
name = "FloatingIps"
alias = "os-floating-ips"
namespace = "http://docs.openstack.org/compute/ext/floating_ips/api/v1.1"
updated = "2011-06-16T00:00:00Z"
def get_resources(self):
resources = []
res = extensions.ResourceExtension('os-floating-ips',
FloatingIPController(),
member_actions={})
resources.append(res)
return resources
def get_controller_extensions(self):
controller = FloatingIPActionController(self.ext_mgr)
extension = extensions.ControllerExtension(self, 'servers', controller)
return [extension]
|
apache-2.0
|
bbrangeo/OpenSourceBIMaaS
|
dev/foundation/src/main/java/com/bimaas/exception/JSONErrorBuilder.java
|
1064
|
/**
*
*/
package com.bimaas.exception;
import org.json.JSONObject;
/**
* Builds the errors and return a {@link JSONObject} with the error.
* <p>
* <code>
* {"response":
* {"error|warning": "error details"}
* }
* </code>
* </p>
*
* @author isuru
*
*/
public class JSONErrorBuilder {
/**
* Build the error as a json object.
*
* @param e
* to be included.
* @return {@link JSONObject} to be return.
*/
public static JSONObject getErrorResponse(String e) {
JSONObject errorResponse = new JSONObject();
JSONObject error = new JSONObject();
error.put("error", e);
errorResponse.put("response", error);
return errorResponse;
}
/**
* Build the warning as a json object.
*
* @param e
* to be included.
* @return {@link JSONObject} to be return.
*/
public static JSONObject getWarningResponse(String e) {
JSONObject errorResponse = new JSONObject();
JSONObject error = new JSONObject();
error.put("warning", e);
errorResponse.put("response", error);
return errorResponse;
}
}
|
apache-2.0
|
gallandarakhneorg/sarl
|
eclipse-products/contribs/io.sarl.examples/io.sarl.examples.tests/src/io/sarl/examples/tests/FakeTest.java
|
772
|
/*
* Copyright (C) 2014-2016 the original authors or authors.
*
* 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 io.sarl.examples.tests;
import org.junit.Test;
@SuppressWarnings("all")
public class FakeTest {
@Test
public void fake() {
//
}
}
|
apache-2.0
|
Funi1234/InternetSpaceships
|
python/main/eve_universe.py
|
1437
|
#/usr/bin/python
"""
Author: David Benson ([email protected])
Date: 02/09/2013
Description: This python module is responsible for storing information about all
systems within the eve universe.
"""
import system
import datetime
import evelink.api
class EveUniverse:
""" This class acts as a storage class for the all the space systems in Eve Online.
A very simple version control system is implemented using timestamps.
"""
def __init__(self):
# Constructor intialises empty array, the last updated timestamp and the connection to Eve APIs.
self.systems = {}
self.api = evelink.api.API()
self.current_timestamp = datetime.datetime.now()
def retrieve_systems(self):
# Method returns a list of all systems from eve api.
response = self.api.get('map/Sovereignty')
for item in response.iter('row'):
temp = system.System(item.attrib['solarSystemName'],
item.attrib['allianceID'], item.attrib['factionID'], item.attrib['corporationID'])
self.systems[item.attrib['solarSystemID']] = temp
self.current_timestamp = datetime.datetime.now()
def __repr__(self):
# Presents a string representation of the object.
result = "Last Updated: %s \n" % self.current_timestamp
result += self.systems.__str__()
return result
sys = EveUniverse()
sys.retrieve_systems()
print(sys.__repr__())
|
apache-2.0
|
moyq5/weixin-popular
|
src/main/java/weixin/popular/bean/message/mass/sendall/Filter.java
|
1712
|
package weixin.popular.bean.message.mass.sendall;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* 用于设定图文消息的接收者
* @author Moyq5
* @date 2016年9月17日
*/
public class Filter {
/**
* 用于设定是否向全部用户发送,值为true或false,选择true该消息群发给所有用户,选择false可根据tag_id发送给指定群组的用户
*/
@JsonProperty("is_to_all")
private Boolean isToAll;
/**
* 群发到的标签的tag_id,参加用户管理中用户分组接口,若is_to_all值为true,可不填写tag_id
*/
@JsonProperty("tag_id")
private String tagId;
/**
* 用于设定是否向全部用户发送,值为true或false,选择true该消息群发给所有用户,选择false可根据tag_id发送给指定群组的用户
* @return 是否向全部用户发送
*/
public Boolean getIsToAll() {
return isToAll;
}
/**
* 用于设定是否向全部用户发送,值为true或false,选择true该消息群发给所有用户,选择false可根据tag_id发送给指定群组的用户
* @param isToAll 是否向全部用户发送
*/
public void setIsToAll(Boolean isToAll) {
this.isToAll = isToAll;
}
/**
* 群发到的标签的tag_id,参加用户管理中用户分组接口,若is_to_all值为true,可不填写tag_id
* @return 群发到的标签的tag_id
*/
public String getTagId() {
return tagId;
}
/**
* 群发到的标签的tag_id,参加用户管理中用户分组接口,若is_to_all值为true,可不填写tag_id
* @param tagId 群发到的标签的tag_id
*/
public void setTagId(String tagId) {
this.tagId = tagId;
}
}
|
apache-2.0
|
BjoernKW/Freshcard
|
src/main/resources/db/migration/V6__Add_oAuth_fields.sql
|
436
|
ALTER TABLE users
ADD COLUMN use_oauth boolean NOT NULL DEFAULT false;
ALTER TABLE users
ADD COLUMN most_recently_used_oauth_service character varying;
ALTER TABLE users
ADD COLUMN github_access_token character varying;
ALTER TABLE users
ADD COLUMN linkedin_access_token character varying;
ALTER TABLE users
ADD COLUMN twitter_access_token character varying;
ALTER TABLE users
ADD COLUMN xing_access_token character varying;
|
apache-2.0
|
jbosstm/narayana.io
|
docs/api/com/arjuna/orbportability/orb/core/class-use/ORB.html
|
9193
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_312) on Wed Jan 19 23:44:09 GMT 2022 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class com.arjuna.orbportability.orb.core.ORB (Narayana: narayana-full 5.12.5.Final API)</title>
<meta name="date" content="2022-01-19">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class com.arjuna.orbportability.orb.core.ORB (Narayana: narayana-full 5.12.5.Final API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../com/arjuna/orbportability/orb/core/ORB.html" title="class in com.arjuna.orbportability.orb.core">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><b>Narayana: narayana-full 5.12.5.Final</b></div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/arjuna/orbportability/orb/core/class-use/ORB.html" target="_top">Frames</a></li>
<li><a href="ORB.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class com.arjuna.orbportability.orb.core.ORB" class="title">Uses of Class<br>com.arjuna.orbportability.orb.core.ORB</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../com/arjuna/orbportability/orb/core/ORB.html" title="class in com.arjuna.orbportability.orb.core">ORB</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#com.arjuna.orbportability.oa.core">com.arjuna.orbportability.oa.core</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="com.arjuna.orbportability.oa.core">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../com/arjuna/orbportability/orb/core/ORB.html" title="class in com.arjuna.orbportability.orb.core">ORB</a> in <a href="../../../../../../com/arjuna/orbportability/oa/core/package-summary.html">com.arjuna.orbportability.oa.core</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../com/arjuna/orbportability/oa/core/package-summary.html">com.arjuna.orbportability.oa.core</a> with parameters of type <a href="../../../../../../com/arjuna/orbportability/orb/core/ORB.html" title="class in com.arjuna.orbportability.orb.core">ORB</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="typeNameLabel">POAImple.</span><code><span class="memberNameLink"><a href="../../../../../../com/arjuna/orbportability/oa/core/POAImple.html#init-com.arjuna.orbportability.orb.core.ORB-">init</a></span>(<a href="../../../../../../com/arjuna/orbportability/orb/core/ORB.html" title="class in com.arjuna.orbportability.orb.core">ORB</a> o)</code>
<div class="block">Initialise the root POA.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="typeNameLabel">POAImple.</span><code><span class="memberNameLink"><a href="../../../../../../com/arjuna/orbportability/oa/core/POAImple.html#run-com.arjuna.orbportability.orb.core.ORB-">run</a></span>(<a href="../../../../../../com/arjuna/orbportability/orb/core/ORB.html" title="class in com.arjuna.orbportability.orb.core">ORB</a> o)</code>
<div class="block">run is a way of starting a server listening for invocations.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="typeNameLabel">POAImple.</span><code><span class="memberNameLink"><a href="../../../../../../com/arjuna/orbportability/oa/core/POAImple.html#run-com.arjuna.orbportability.orb.core.ORB-java.lang.String-">run</a></span>(<a href="../../../../../../com/arjuna/orbportability/orb/core/ORB.html" title="class in com.arjuna.orbportability.orb.core">ORB</a> o,
java.lang.String name)</code>
<div class="block">run is a way of starting a server listening for invocations.</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing constructors, and an explanation">
<caption><span>Constructors in <a href="../../../../../../com/arjuna/orbportability/oa/core/package-summary.html">com.arjuna.orbportability.oa.core</a> with parameters of type <a href="../../../../../../com/arjuna/orbportability/orb/core/ORB.html" title="class in com.arjuna.orbportability.orb.core">ORB</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/arjuna/orbportability/oa/core/OA.html#OA-com.arjuna.orbportability.orb.core.ORB-">OA</a></span>(<a href="../../../../../../com/arjuna/orbportability/orb/core/ORB.html" title="class in com.arjuna.orbportability.orb.core">ORB</a> theORB)</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../com/arjuna/orbportability/orb/core/ORB.html" title="class in com.arjuna.orbportability.orb.core">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><b>Narayana: narayana-full 5.12.5.Final</b></div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/arjuna/orbportability/orb/core/class-use/ORB.html" target="_top">Frames</a></li>
<li><a href="ORB.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2022 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
|
apache-2.0
|
consulo/consulo
|
modules/base/core-api/src/main/java/com/intellij/psi/search/EverythingGlobalScope.java
|
1792
|
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* 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.
*/
/*
* @author max
*/
package com.intellij.psi.search;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import javax.annotation.Nonnull;
public class EverythingGlobalScope extends GlobalSearchScope {
public EverythingGlobalScope(Project project) {
super(project);
}
public EverythingGlobalScope() {
}
@Nonnull
@Override
public String getDisplayName() {
return "All Places";
}
@Override
public int compare(@Nonnull final VirtualFile file1, @Nonnull final VirtualFile file2) {
return 0;
}
@Override
public boolean contains(@Nonnull final VirtualFile file) {
return true;
}
@Override
public boolean isSearchInLibraries() {
return true;
}
@Override
public boolean isSearchInModuleContent(@Nonnull final Module aModule) {
return true;
}
@Override
public boolean isSearchOutsideRootModel() {
return true;
}
@Nonnull
@Override
public GlobalSearchScope union(@Nonnull SearchScope scope) {
return this;
}
@Nonnull
@Override
public SearchScope intersectWith(@Nonnull SearchScope scope2) {
return scope2;
}
}
|
apache-2.0
|
manager-alert/manager-alert
|
src/app/landing-page/landing-page.component.spec.ts
|
765
|
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { LayoutModule } from '../layout/layout.module';
import { LandingPageComponent } from './landing-page.component';
describe('LandingPageComponent', () => {
let component: LandingPageComponent;
let fixture: ComponentFixture<LandingPageComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [LandingPageComponent],
imports: [LayoutModule.forRoot()]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(LandingPageComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should be created', () => {
expect(component).toBeTruthy();
});
});
|
apache-2.0
|
real-logic/Agrona
|
agrona-agent/src/main/java/org/agrona/agent/BufferAlignmentInterceptor.java
|
4703
|
/*
* Copyright 2014-2021 Real Logic Limited.
*
* 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
*
* https://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 org.agrona.agent;
import net.bytebuddy.asm.Advice;
import org.agrona.BitUtil;
import org.agrona.DirectBuffer;
/**
* Interceptor to be applied when verifying buffer alignment accesses.
*/
@SuppressWarnings("unused")
public class BufferAlignmentInterceptor
{
abstract static class Verifier
{
/**
* Interceptor for type alignment verifier.
*
* @param index into the buffer.
* @param buffer the buffer.
* @param alignment to be verified.
*/
public static void verifyAlignment(final int index, final @Advice.This DirectBuffer buffer, final int alignment)
{
final int alignmentOffset = (int)(buffer.addressOffset() + index) % alignment;
if (0 != alignmentOffset)
{
throw new BufferAlignmentException(
"Unaligned " + alignment + "-byte access (index=" + index + ", offset=" + alignmentOffset + ")");
}
}
}
/**
* Verifier for {@code long} types.
*/
public static final class LongVerifier extends Verifier
{
/**
* Verify alignment of the {@code long} types.
*
* @param index into the buffer.
* @param buffer the buffer.
*/
@Advice.OnMethodEnter
public static void verifyAlignment(final int index, final @Advice.This DirectBuffer buffer)
{
verifyAlignment(index, buffer, BitUtil.SIZE_OF_LONG);
}
}
/**
* Verifier for {@code double} types.
*/
public static final class DoubleVerifier extends Verifier
{
/**
* Verify alignment of the {@code double} types.
*
* @param index into the buffer.
* @param buffer the buffer.
*/
@Advice.OnMethodEnter
public static void verifyAlignment(final int index, final @Advice.This DirectBuffer buffer)
{
verifyAlignment(index, buffer, BitUtil.SIZE_OF_DOUBLE);
}
}
/**
* Verifier for {@code int} types.
*/
public static final class IntVerifier extends Verifier
{
/**
* Verify alignment of the {@code int} types.
*
* @param index into the buffer.
* @param buffer the buffer.
*/
@Advice.OnMethodEnter
public static void verifyAlignment(final int index, final @Advice.This DirectBuffer buffer)
{
verifyAlignment(index, buffer, BitUtil.SIZE_OF_INT);
}
}
/**
* Verifier for {@code float} types.
*/
public static final class FloatVerifier extends Verifier
{
/**
* Verify alignment of the {@code float} types.
*
* @param index into the buffer.
* @param buffer the buffer.
*/
@Advice.OnMethodEnter
public static void verifyAlignment(final int index, final @Advice.This DirectBuffer buffer)
{
verifyAlignment(index, buffer, BitUtil.SIZE_OF_FLOAT);
}
}
/**
* Verifier for {@code short} types.
*/
public static final class ShortVerifier extends Verifier
{
/**
* Verify alignment of the {@code short} types.
*
* @param index into the buffer.
* @param buffer the buffer.
*/
@Advice.OnMethodEnter
public static void verifyAlignment(final int index, final @Advice.This DirectBuffer buffer)
{
verifyAlignment(index, buffer, BitUtil.SIZE_OF_SHORT);
}
}
/**
* Verifier for {@code char} types.
*/
public static final class CharVerifier extends Verifier
{
/**
* Verify alignment of the {@code char} types.
*
* @param index into the buffer.
* @param buffer the buffer.
*/
@Advice.OnMethodEnter
public static void verifyAlignment(final int index, final @Advice.This DirectBuffer buffer)
{
verifyAlignment(index, buffer, BitUtil.SIZE_OF_CHAR);
}
}
}
|
apache-2.0
|
manueldeveloper/springcloudconfigserver
|
SimpleRestAPI/src/main/java/com/example/demo/SimpleRestApiApplication.java
|
2343
|
package com.example.demo;
import java.util.Collection;
import java.util.stream.Stream;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.data.rest.core.annotation.RestResource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@EnableDiscoveryClient
@SpringBootApplication
public class SimpleRestApiApplication {
@Bean
CommandLineRunner commandLineRunner(ReservationRepository reservationRepository) {
return strings -> {
Stream.of("Josh", "Peter", "Susi")
.forEach(n -> reservationRepository.save(new Reservation(n)));
};
}
public static void main(String[] args) {
SpringApplication.run(SimpleRestApiApplication.class, args);
}
}
@RepositoryRestResource
interface ReservationRepository extends JpaRepository<Reservation, Long>{
@RestResource(path="by-name")
Collection<Reservation> findByReservationName(@Param("rn") String rn);
}
@Entity
class Reservation{
@Id
@GeneratedValue
private Long id;
private String reservationName;
public Reservation() {
}
public Reservation(String n) {
this.reservationName= n;
}
public Long getId() {
return id;
}
public String getReservationName() {
return reservationName;
}
@Override
public String toString() {
return "Reservation{" +
"id= " + id +
", reservationName= '" + reservationName + "'";
}
}
@RefreshScope
@RestController
class MessageRestController {
@Value("${msg:Hello world - Config Server is not working..pelase check}")
private String msg;
@RequestMapping("/msg")
String getMsg() {
return this.msg;
}
}
|
apache-2.0
|
stdlib-js/stdlib
|
lib/node_modules/@stdlib/_tools/eslint/rules/jsdoc-markdown-remark/test/fixtures/valid.js
|
6669
|
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var config = require( './config.js' );
// VARIABLES //
var valid;
var test;
// MAIN //
// Create our test cases:
valid = [];
test = {
'code': [
'/**',
'* Squares a number.',
'* ',
'* @param {number} x - input number',
'* @returns {number} x squared',
'*',
'* @example',
'* var y = square( 2.0 );',
'* // returns 4.0',
'*/',
'function square( x ) {',
' return x*x;',
'}'
].join( '\n' ),
'options': [
{
'config': config
}
]
};
valid.push( test );
test = {
'code': [
'/**',
'* Returns a pseudo-random number on [0,1].',
'* ',
'* @returns {number} uniform random number',
'*',
'* @example',
'* var y = rand();',
'* // e.g., returns 0.5363925252089496',
'*/',
'function rand() {',
' return Math.random();',
'}'
].join( '\n' ),
'options': [
{
'config': config
}
]
};
valid.push( test );
test = {
'code': [
'/**',
'* Returns the number of minutes in a month.',
'*',
'* @param {(string|Date|integer)} [month] - month',
'* @param {integer} [year] - year',
'* @throws {TypeError} first argument must be either a string, integer, or `Date` object',
'* @throws {Error} must provide a recognized month',
'* @throws {RangeError} an integer month argument must be on the interval `[1,12]`',
'* @throws {TypeError} second argument must be an integer',
'* @returns {integer} minutes in a month',
'*',
'* @example',
'* var num = minutesInMonth();',
'* // returns <number>',
'*',
'* @example',
'* var num = minutesInMonth( 2 );',
'* // returns <number>',
'*',
'* @example',
'* var num = minutesInMonth( 2, 2016 );',
'* // returns 41760',
'*',
'* @example',
'* var num = minutesInMonth( 2, 2017 );',
'* // returns 40320',
'*/',
'function minutesInMonth( month, year ) {',
' var mins;',
' var mon;',
' var yr;',
' var d;',
' if ( arguments.length === 0 ) {',
' // Note: cannot cache as application may cross over into a new year:',
' d = new Date();',
' mon = d.getMonth() + 1; // zero-based',
' yr = d.getFullYear();',
' } else if ( arguments.length === 1 ) {',
' if ( isDateObject( month ) ) {',
' d = month;',
' mon = d.getMonth() + 1; // zero-based',
' yr = d.getFullYear();',
' } else if ( isString( month ) || isInteger( month ) ) {',
' // Note: cannot cache as application may cross over into a new year:',
' yr = ( new Date() ).getFullYear();',
' mon = month;',
' } else {',
' throw new TypeError( \'invalid argument. First argument must be either a string, integer, or `Date` object. Value: `\'+month+\'`.\' );',
' }',
' } else {',
' if ( !isString( month ) && !isInteger( month ) ) {',
' throw new TypeError( \'invalid argument. First argument must be either a string or integer. Value: `\'+month+\'`.\' );',
' }',
' if ( !isInteger( year ) ) {',
' throw new TypeError( \'invalid argument. Second argument must be an integer. Value: `\'+year+\'`.\' );',
' }',
' mon = month;',
' yr = year;',
' }',
' if ( isInteger( mon ) && (mon < 1 || mon > 12) ) {',
' throw new RangeError( \'invalid argument. An integer month value must be on the interval `[1,12]`. Value: `\'+mon+\'`.\' );',
' }',
' mon = lowercase( mon.toString() );',
' mins = MINUTES_IN_MONTH[ mon ];',
' if ( mins === void 0 ) {',
' throw new Error( \'invalid argument. Must provide a recognized month. Value: `\'+mon+\'`.\' );',
' }',
' // Check if February during a leap year...',
' if ( mins === 40320 && isLeapYear( yr ) ) {',
' mins += MINUTES_IN_DAY;',
' }',
' return mins;',
'}'
].join( '\n' ),
'options': [
{
'config': config
}
]
};
valid.push( test );
test = {
'code': [
'/**',
'* Removes a UTF-8 byte order mark (BOM) from the beginning of a string.',
'*',
'* ## Notes',
'*',
'* - A UTF-8 byte order mark ([BOM][1]) is the byte sequence `0xEF,0xBB,0xBF`.',
'* - To convert a UTF-8 encoded `Buffer` to a `string`, the `Buffer` must be converted to \'[UTF-16][2]. The BOM thus gets converted to the single 16-bit code point `\'\ufeff\'` \'(UTF-16 BOM).',
'*',
'* [1]: https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8',
'* [2]: http://es5.github.io/#x4.3.16',
'*',
'*',
'* @param {string} str - input string',
'* @throws {TypeError} must provide a string primitive',
'* @returns {string} string with BOM removed',
'*',
'* @example',
'* var str = removeUTF8BOM( \'\ufeffbeep\' );',
'* // returns \'beep\'',
'*/',
'function removeUTF8BOM( str ) {',
' if ( !isString( str ) ) {',
' throw new TypeError( \'invalid argument. Must provide a string primitive. Value: `\' + str + \'`.\' );',
' }',
' if ( str.charCodeAt( 0 ) === BOM ) {',
' return str.slice( 1 );',
' }',
' return str;',
'}'
].join( '\n' ),
'options': [
{
'config': config
}
]
};
valid.push( test );
test = {
'code': [
'/**',
'* @name arcsine',
'* @memberof random',
'* @readonly',
'* @type {Function}',
'* @see {@link module:@stdlib/random/base/arcsine}',
'*/',
'setReadOnly( random, \'arcsine\', require( \'@stdlib/random/base/arcsine\' ) );'
].join( '\n' ),
'options': [
{
'config': config
}
]
};
valid.push( test );
test = {
'code': [
'/**',
'* Beep boop.',
'*',
'* Some code...',
'*',
'* ```javascript',
'* var f = foo();',
'* ```',
'*',
'* Some LaTeX...',
'*',
'* ```tex',
'* \\frac{1}{2}',
'* ```',
'*',
'* ## Notes',
'*',
'* - First.',
'* - Second.',
'* - Third.',
'*',
'* ## References',
'*',
'* - Jane Doe. Science. 2017.',
'*',
'* | x | y |',
'* | 1 | 2 |',
'* | 2 | 1 |',
'*',
'*',
'* @param {string} str - input value',
'* @returns {string} output value',
'*',
'* @example',
'* var out = beep( "boop" );',
'* // returns "beepboop"',
'*/',
'function beep( str ) {',
'\treturn "beep" + str;',
'}'
].join( '\n' ),
'options': [
{
'config': config
}
]
};
valid.push( test );
// EXPORTS //
module.exports = valid;
|
apache-2.0
|
YoukaiCat/imgbrd-grabber
|
gui/src/batch/adduniquewindow.cpp
|
3454
|
#include <QSettings>
#include <QFileDialog>
#include "adduniquewindow.h"
#include "ui_adduniquewindow.h"
#include "functions.h"
#include "helpers.h"
#include "vendor/json.h"
#include "models/page.h"
#include "models/filename.h"
/**
* Constructor of the AddUniqueWindow class, generating its window.
* @param favorites List of favorites tags, needed for coloration
* @param parent The parent window
*/
AddUniqueWindow::AddUniqueWindow(QString selected, QMap<QString,Site*> sites, Profile *profile, QWidget *parent)
: QDialog(parent), ui(new Ui::AddUniqueWindow), m_sites(sites), m_profile(profile)
{
ui->setupUi(this);
ui->comboSites->addItems(m_sites.keys());
ui->comboSites->setCurrentIndex(m_sites.keys().indexOf(selected));
QSettings *settings = profile->getSettings();
ui->lineFolder->setText(settings->value("Save/path").toString());
ui->lineFilename->setText(settings->value("Save/filename").toString());
}
/**
* Ui events
*/
void AddUniqueWindow::on_buttonFolder_clicked()
{
QString folder = QFileDialog::getExistingDirectory(this, tr("Choose a save folder"), ui->lineFolder->text());
if (!folder.isEmpty())
{ ui->lineFolder->setText(folder); }
}
void AddUniqueWindow::on_lineFilename_textChanged(QString text)
{
QString message;
Filename fn(text);
fn.isValid(&message);
ui->labelFilename->setText(message);
}
/**
* Search for image in available websites.
*/
void AddUniqueWindow::add()
{ ok(false); }
void AddUniqueWindow::ok(bool close)
{
Site *site = m_sites[ui->comboSites->currentText()];
m_close = close;
bool useDirectLink = true;
if (
(site->value("Urls/Html/Post").contains("{id}") && ui->lineId->text().isEmpty()) ||
(site->value("Urls/Html/Post").contains("{md5}") && ui->lineMd5->text().isEmpty()) ||
!site->contains("Regex/ImageUrl")
)
{ useDirectLink = false; }
if (useDirectLink)
{
QString url = site->value("Urls/Html/Post");
url.replace("{id}", ui->lineId->text());
url.replace("{md5}", ui->lineMd5->text());
QMap<QString,QString> details = QMap<QString,QString>();
details.insert("page_url", url);
details.insert("id", ui->lineId->text());
details.insert("md5", ui->lineMd5->text());
details.insert("website", ui->comboSites->currentText());
details.insert("site", QString::number((qintptr)m_sites[ui->comboSites->currentText()]));
m_image = QSharedPointer<Image>(new Image(site, details, m_profile));
connect(m_image.data(), &Image::finishedLoadingTags, this, &AddUniqueWindow::addLoadedImage);
m_image->loadDetails();
}
else
{
m_page = new Page(m_profile, m_sites[ui->comboSites->currentText()], m_sites.values(), QStringList() << (ui->lineId->text().isEmpty() ? "md5:"+ui->lineMd5->text() : "id:"+ui->lineId->text()) << "status:any", 1, 1);
connect(m_page, SIGNAL(finishedLoading(Page*)), this, SLOT(replyFinished(Page*)));
m_page->load();
}
}
/**
* Signal triggered when the search is finished.
* @param r The QNetworkReply associated with the search
*/
void AddUniqueWindow::replyFinished(Page *p)
{
if (p->images().isEmpty())
{
p->deleteLater();
error(this, tr("No image found."));
return;
}
addImage(p->images().first());
p->deleteLater();
}
void AddUniqueWindow::addLoadedImage()
{
addImage(m_image);
}
void AddUniqueWindow::addImage(QSharedPointer<Image> img)
{
emit sendData(DownloadQueryImage(img, m_sites[ui->comboSites->currentText()], ui->lineFilename->text(), ui->lineFolder->text()));
if (m_close)
close();
}
|
apache-2.0
|
tensorflow/tfjs
|
tfjs-core/src/ops/sign_test.ts
|
3063
|
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* 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.
* =============================================================================
*/
import * as tf from '../index';
import {ALL_ENVS, describeWithFlags} from '../jasmine_util';
import {expectArraysClose} from '../test_util';
describeWithFlags('sign', ALL_ENVS, () => {
it('basic', async () => {
const a = tf.tensor1d([1.5, 0, NaN, -1.4]);
const r = tf.sign(a);
expectArraysClose(await r.data(), [1, 0, 0, -1]);
});
it('does not propagate NaNs', async () => {
const a = tf.tensor1d([1.5, NaN, -1.4]);
const r = tf.sign(a);
expectArraysClose(await r.data(), [1, 0, -1]);
});
it('gradients: Scalar', async () => {
const a = tf.scalar(5.2);
const dy = tf.scalar(3);
const gradients = tf.grad(a => tf.sign(a))(a, dy);
expect(gradients.shape).toEqual(a.shape);
expect(gradients.dtype).toEqual('float32');
expectArraysClose(await gradients.data(), [0]);
});
it('gradient with clones', async () => {
const a = tf.scalar(5.2);
const dy = tf.scalar(3);
const gradients = tf.grad(a => tf.sign(a.clone()).clone())(a, dy);
expect(gradients.shape).toEqual(a.shape);
expect(gradients.dtype).toEqual('float32');
expectArraysClose(await gradients.data(), [0]);
});
it('gradients: Tensor1D', async () => {
const a = tf.tensor1d([-1.1, 2.6, 3, -5.9]);
const dy = tf.tensor1d([-1, 1, 1, -1]);
const gradients = tf.grad(a => tf.sign(a))(a, dy);
expect(gradients.shape).toEqual(a.shape);
expect(gradients.dtype).toEqual('float32');
expectArraysClose(await gradients.data(), [0, 0, 0, 0]);
});
it('gradients: Tensor2D', async () => {
const a = tf.tensor2d([-3, 1, 2.2, 3], [2, 2]);
const dy = tf.tensor2d([1, 2, 3, 4], [2, 2]);
const gradients = tf.grad(a => tf.sign(a))(a, dy);
expect(gradients.shape).toEqual(a.shape);
expect(gradients.dtype).toEqual('float32');
expectArraysClose(await gradients.data(), [0, 0, 0, 0]);
});
it('throws when passed a non-tensor', () => {
expect(() => tf.sign({} as tf.Tensor))
.toThrowError(/Argument 'x' passed to 'sign' must be a Tensor/);
});
it('accepts a tensor-like object', async () => {
const r = tf.sign([1.5, 0, NaN, -1.4]);
expectArraysClose(await r.data(), [1, 0, 0, -1]);
});
it('throws for string tensor', () => {
expect(() => tf.sign('q'))
.toThrowError(/Argument 'x' passed to 'sign' must be numeric/);
});
});
|
apache-2.0
|
javild/opencga
|
opencga-storage/src/main/java/org/opencb/opencga/storage/alignment/hbase/AlignmentHBaseQueryBuilder.java
|
10790
|
/*
* Copyright 2015-2016 OpenCB
*
* 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 org.opencb.opencga.storage.alignment.hbase;
import com.google.protobuf.InvalidProtocolBufferException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.util.Bytes;
import org.opencb.biodata.models.alignment.Alignment;
import org.opencb.biodata.models.alignment.stats.RegionCoverage;
import org.opencb.biodata.models.feature.Region;
import org.opencb.commons.containers.QueryResult;
import org.opencb.commons.containers.map.QueryOptions;
import org.opencb.opencga.core.auth.MonbaseCredentials;
import org.opencb.opencga.storage.alignment.AlignmentQueryBuilder;
import org.opencb.opencga.storage.alignment.AlignmentSummary;
import org.opencb.opencga.storage.alignment.proto.AlignmentProto;
import org.opencb.opencga.storage.alignment.proto.AlignmentProtoHelper;
import org.xerial.snappy.Snappy;
/**
* Created with IntelliJ IDEA.
* User: jcoll
* Date: 3/7/14
* Time: 10:12 AM
* To change this template use File | Settings | File Templates.
*/
public class AlignmentHBaseQueryBuilder implements AlignmentQueryBuilder {
HBaseManager manager;
String tableName, columnFamilyName = null;
public void connect(){
manager.connect();
}
// public AlignmentHBaseQueryBuilder(MonbaseCredentials credentials, String tableName) {
// manager = new HBaseManager(credentials);
// this.tableName = tableName;
// }
public AlignmentHBaseQueryBuilder(String tableName) {
}
public AlignmentHBaseQueryBuilder(Configuration config, String tableName) {
manager = new HBaseManager(config);
this.tableName = tableName;
}
@Override
public QueryResult getAllAlignmentsByRegion(Region region, QueryOptions options) {
boolean wasOpened = true;
if(!manager.isOpened()){
manager.connect();
wasOpened = false;
}
HTable table = manager.getTable(tableName);//manager.createTable(tableName, columnFamilyName);
if(table == null){
return null;
}
QueryResult<Alignment> queryResult = new QueryResult<>();
String sample = options.getString("sample", "HG00096");
String family = options.getString("family", "c");
int bucketSize = 256; //FIXME: HARDCODE!
//String startRow = region.getChromosome() + "_" + String.format("%07d", region.getStart() / bucketSize);
//String endRow = region.getChromosome() + "_" + String.format("%07d", region.getEnd() / bucketSize);
String startRow = AlignmentHBase.getBucketRowkey(region.getChromosome(), region.getStart(), bucketSize);
String endRow = AlignmentHBase.getBucketRowkey(region.getChromosome(), region.getEnd()+bucketSize, bucketSize);
System.out.println("Scaning from " + startRow + " to " + endRow);
Scan scan = new Scan();
scan.setStartRow(Bytes.toBytes(startRow));
scan.setStopRow(Bytes.toBytes(endRow));
scan.addColumn(Bytes.toBytes(family), Bytes.toBytes(sample));
scan.setMaxVersions(1);
// scan.setMaxResultSize()
ResultScanner resultScanner;
try {
resultScanner = table.getScanner(scan);
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
System.err.println("[ERROR] -- Bad query");
return null;
}
Map<Integer, AlignmentSummary> summaryMap = new HashMap<>();
for(Result result : resultScanner){
for(Cell cell : result.listCells()){
//System.out.println("Qualifier : " + keyValue.getKeyString() + " : Value : "/* + Bytes.toString(keyValue.getValue())*/);
AlignmentProto.AlignmentBucket alignmentBucket = null;
try {
alignmentBucket = AlignmentProto.AlignmentBucket.parseFrom(Snappy.uncompress(CellUtil.cloneValue(cell)));
} catch (InvalidProtocolBufferException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
continue;
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
continue;
}
//System.out.println("Tenemos un bucket!");
AlignmentSummary summary;
if(!summaryMap.containsKey(alignmentBucket.getSummaryIndex())) {
summaryMap.put(alignmentBucket.getSummaryIndex(), getRegionSummary(region.getChromosome(), alignmentBucket.getSummaryIndex(), table));
}
summary = summaryMap.get(alignmentBucket.getSummaryIndex());
long pos = AlignmentHBase.getPositionFromRowkey(org.apache.hadoop.hbase.util.Bytes.toString(cell.getRowArray()), bucketSize);
List<Alignment> alignmentList = AlignmentProtoHelper.toAlignmentList(alignmentBucket, summary, region.getChromosome(), pos);
//System.out.println("Los tenemos!!");
for(Alignment alignment : alignmentList){
queryResult.addResult(alignment);
}
}
}
if(!wasOpened){
manager.disconnect();
}
return queryResult;
//return null;
}
private AlignmentSummary getRegionSummary(String chromosome, int index,HTable table){
// manager.connect();
// HTable table = manager.createTable(tableName, columnFamilyName);
Scan scan = new Scan(
Bytes.toBytes(AlignmentHBase.getSummaryRowkey(chromosome, index)) ,
Bytes.toBytes(AlignmentHBase.getSummaryRowkey(chromosome, index+1)));
ResultScanner resultScanner;
try {
resultScanner = table.getScanner(scan);
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
System.err.println("[ERROR] -- Bad query");
return null;
}
AlignmentSummary summary = null;
for(Result result : resultScanner){
for(KeyValue keyValue : result.list()){
//System.out.println("Qualifier : " + keyValue.getKeyString() );
try {
summary = new AlignmentSummary( AlignmentProto.Summary.parseFrom(Snappy.uncompress(keyValue.getValue())), index);
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
return summary;
}
@Override
public QueryResult getAllAlignmentsByGene(String gene, QueryOptions options) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public QueryResult getCoverageByRegion(Region region, QueryOptions options) {
QueryResult<RegionCoverage> queryResult = new QueryResult<>();
if (!manager.isOpened()) {
manager.connect();
}
String sample = options.getString("sample", "HG00096");
String family = options.getString("family", "c");
int bucketSize = 256; //FIXME: HARDCODE!
//String startRow = region.getChromosome() + "_" + String.format("%07d", region.getStart() / bucketSize);
//String endRow = region.getChromosome() + "_" + String.format("%07d", region.getEnd() / bucketSize);
String startRow = AlignmentHBase.getBucketRowkey(region.getChromosome(), region.getStart(), bucketSize);
String endRow = AlignmentHBase.getBucketRowkey(region.getChromosome(), region.getEnd() + bucketSize, bucketSize);
HTable table = manager.getTable(tableName);
Scan scan = new Scan();
scan.setStartRow(Bytes.toBytes(startRow));
scan.setStopRow(Bytes.toBytes(endRow));
scan.addColumn(Bytes.toBytes(family), Bytes.toBytes(sample));
scan.setMaxVersions(1);
ResultScanner scanner;
try {
scanner = table.getScanner(scan);
} catch (IOException ex) {
Logger.getLogger(AlignmentHBaseQueryBuilder.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
for (Result result : scanner) {
for (Cell cell : result.listCells()) {
AlignmentProto.Coverage parseFrom;
try {
parseFrom = AlignmentProto.Coverage.parseFrom(CellUtil.cloneValue(cell));
} catch (InvalidProtocolBufferException ex) {
Logger.getLogger(AlignmentHBaseQueryBuilder.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return queryResult;
}
@Override
public QueryResult getAlignmentsHistogramByRegion(Region region, boolean histogramLogarithm, int histogramMax) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public QueryResult getAlignmentRegionInfo(Region region, QueryOptions options) {
throw new UnsupportedOperationException("Not supported yet.");
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public String getColumnFamilyName() {
return columnFamilyName;
}
public void setColumnFamilyName(String columnFamilyName) {
this.columnFamilyName = columnFamilyName;
}
}
|
apache-2.0
|
nitro-devs/nitro-game-engine
|
docs/sdl2_sys/keycode/constant.SDLK_KP9.html
|
4284
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="rustdoc">
<meta name="description" content="API documentation for the Rust `SDLK_KP9` constant in crate `sdl2_sys`.">
<meta name="keywords" content="rust, rustlang, rust-lang, SDLK_KP9">
<title>sdl2_sys::keycode::SDLK_KP9 - Rust</title>
<link rel="stylesheet" type="text/css" href="../../normalize.css">
<link rel="stylesheet" type="text/css" href="../../rustdoc.css">
<link rel="stylesheet" type="text/css" href="../../main.css">
</head>
<body class="rustdoc constant">
<!--[if lte IE 8]>
<div class="warning">
This old browser is unsupported and will most likely display funky
things.
</div>
<![endif]-->
<nav class="sidebar">
<p class='location'><a href='../index.html'>sdl2_sys</a>::<wbr><a href='index.html'>keycode</a></p><script>window.sidebarCurrent = {name: 'SDLK_KP9', ty: 'constant', relpath: ''};</script><script defer src="sidebar-items.js"></script>
</nav>
<nav class="sub">
<form class="search-form js-only">
<div class="search-container">
<input class="search-input" name="search"
autocomplete="off"
placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
type="search">
</div>
</form>
</nav>
<section id='main' class="content">
<h1 class='fqn'><span class='in-band'>Constant <a href='../index.html'>sdl2_sys</a>::<wbr><a href='index.html'>keycode</a>::<wbr><a class="constant" href=''>SDLK_KP9</a></span><span class='out-of-band'><span id='render-detail'>
<a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs">
[<span class='inner'>−</span>]
</a>
</span><a class='srclink' href='../../src/sdl2_sys/keycode.rs.html#117' title='goto source code'>[src]</a></span></h1>
<pre class='rust const'>pub const SDLK_KP9: <a class="type" href="../../sdl2_sys/keycode/type.SDL_Keycode.html" title="type sdl2_sys::keycode::SDL_Keycode">SDL_Keycode</a><code> = </code><code>1073741921</code></pre></section>
<section id='search' class="content hidden"></section>
<section class="footer"></section>
<aside id="help" class="hidden">
<div>
<h1 class="hidden">Help</h1>
<div class="shortcuts">
<h2>Keyboard Shortcuts</h2>
<dl>
<dt>?</dt>
<dd>Show this help dialog</dd>
<dt>S</dt>
<dd>Focus the search field</dd>
<dt>⇤</dt>
<dd>Move up in search results</dd>
<dt>⇥</dt>
<dd>Move down in search results</dd>
<dt>⏎</dt>
<dd>Go to active search result</dd>
<dt>+</dt>
<dd>Collapse/expand all sections</dd>
</dl>
</div>
<div class="infos">
<h2>Search Tricks</h2>
<p>
Prefix searches with a type followed by a colon (e.g.
<code>fn:</code>) to restrict the search to a given type.
</p>
<p>
Accepted types are: <code>fn</code>, <code>mod</code>,
<code>struct</code>, <code>enum</code>,
<code>trait</code>, <code>type</code>, <code>macro</code>,
and <code>const</code>.
</p>
<p>
Search functions by type signature (e.g.
<code>vec -> usize</code> or <code>* -> vec</code>)
</p>
</div>
</div>
</aside>
<script>
window.rootPath = "../../";
window.currentCrate = "sdl2_sys";
</script>
<script src="../../jquery.js"></script>
<script src="../../main.js"></script>
<script defer src="../../search-index.js"></script>
</body>
</html>
|
apache-2.0
|
googleinterns/step133-2020
|
src/test/java/com/google/step/finscholar/CollegeTest.java
|
3967
|
// Copyright 2019 Google LLC
//
// 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
//
// https://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.google.step.finscholar;
import com.google.step.finscholar.data.College;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** This class tests the College object's methods and behavior. */
@RunWith(JUnit4.class)
public final class CollegeTest {
private static College college;
private static List<UUID> users = new ArrayList<UUID>();
@BeforeClass
public static void setUp() {
users.add(UUID.randomUUID());
users.add(UUID.randomUUID());
college = new College.CollegeBuilder("Duke University")
.setInstitutionType("Private")
.setAcceptanceRate(0.07)
.setAverageACTScore(33)
.setUsersUUIDList(users)
.setTotalCostAttendance(75000)
.setNetCostForFirstQuintile(2000)
.setNetCostForSecondQuintile(5000)
.setNetCostForThirdQuintile(10000)
.setNetCostForFourthQuintile(20000)
.setNetCostForFifthQuintile(30000)
.setCumulativeMedianDebt(10000)
.build();
}
@Test
public void schoolNameCorrectlySet() {
String expected = "Duke University";
String actual = college.getSchoolName();
Assert.assertEquals(expected, actual);
}
@Test
public void isUUIDGenerated() {
UUID actual = college.getCollegeUuid();
Assert.assertNotNull(actual);
}
@Test
public void institutionTypeCorrectlySet() {
String expected = "Private";
String actual = college.getInstitutionType();
Assert.assertEquals(expected, actual);
}
@Test
public void acceptanceRateCorrectlySet() {
double expected = 0.07;
double actual = college.getAcceptanceRate();
Assert.assertEquals(expected, actual, 0);
}
@Test
public void ACTScoreCorrectlySet() {
double expected = 33;
double actual = college.getAverageACTScore();
Assert.assertEquals(expected, actual, 0);
}
@Test
public void usersListCorrectlySet() {
List<UUID> actual = college.getUsersUUIDList();
Assert.assertEquals(users, actual);
}
@Test
public void totalCostCorrectlySet() {
int expected = 75000;
int actual = college.getTotalCostAttendance();
Assert.assertEquals(expected, actual);
}
@Test
public void firstNetCostCorrectlySet() {
int expected = 2000;
int actual = college.getNetCostForFirstQuintile();
Assert.assertEquals(expected, actual);
}
@Test
public void secondNetCostCorrectlySet() {
int expected = 5000;
int actual = college.getNetCostForSecondQuintile();
Assert.assertEquals(expected, actual);
}
@Test
public void thirdNetCostCorrectlySet() {
int expected = 10000;
int actual = college.getNetCostForThirdQuintile();
Assert.assertEquals(expected, actual);
}
@Test
public void fourthNetCostCorrectlySet() {
int expected = 20000;
int actual = college.getNetCostForFourthQuintile();
Assert.assertEquals(expected, actual);
}
@Test
public void fifthNetCostCorrectlySet() {
int expected = 30000;
int actual = college.getNetCostForFifthQuintile();
Assert.assertEquals(expected, actual);
}
@Test
public void medianDebtCorrectlySet() {
int expected = 10000;
int actual = college.getCumulativeMedianDebt();
Assert.assertEquals(expected, actual);
}
}
|
apache-2.0
|
wbrefvem/openshift-ansible
|
roles/openshift_health_checker/openshift_checks/package_version.py
|
3386
|
"""Check that available RPM packages match the required versions."""
from openshift_checks import OpenShiftCheck
from openshift_checks.mixins import NotContainerizedMixin
class PackageVersion(NotContainerizedMixin, OpenShiftCheck):
"""Check that available RPM packages match the required versions."""
name = "package_version"
tags = ["preflight"]
# NOTE: versions outside those specified are mapped to least/greatest
openshift_to_ovs_version = {
(3, 4): "2.4",
(3, 5): ["2.6", "2.7"],
(3, 6): ["2.6", "2.7", "2.8", "2.9"],
(3, 7): ["2.6", "2.7", "2.8", "2.9"],
(3, 8): ["2.6", "2.7", "2.8", "2.9"],
(3, 9): ["2.6", "2.7", "2.8", "2.9"],
(3, 10): ["2.6", "2.7", "2.8", "2.9"],
}
openshift_to_docker_version = {
(3, 1): "1.8",
(3, 2): "1.10",
(3, 3): "1.10",
(3, 4): "1.12",
(3, 5): "1.12",
(3, 6): "1.12",
(3, 7): "1.12",
(3, 8): "1.12",
(3, 9): ["1.12", "1.13"],
}
def is_active(self):
"""Skip hosts that do not have package requirements."""
group_names = self.get_var("group_names", default=[])
master_or_node = 'oo_masters_to_config' in group_names or 'oo_nodes_to_config' in group_names
return super(PackageVersion, self).is_active() and master_or_node
def run(self):
rpm_prefix = self.get_var("openshift_service_type")
if self._templar is not None:
rpm_prefix = self._templar.template(rpm_prefix)
openshift_release = self.get_var("openshift_release", default='')
deployment_type = self.get_var("openshift_deployment_type")
check_multi_minor_release = deployment_type in ['openshift-enterprise']
args = {
"package_mgr": self.get_var("ansible_pkg_mgr"),
"package_list": [
{
"name": "openvswitch",
"version": self.get_required_ovs_version(),
"check_multi": False,
},
{
"name": "docker",
"version": self.get_required_docker_version(),
"check_multi": False,
},
{
"name": "{}".format(rpm_prefix),
"version": openshift_release,
"check_multi": check_multi_minor_release,
},
{
"name": "{}-master".format(rpm_prefix),
"version": openshift_release,
"check_multi": check_multi_minor_release,
},
{
"name": "{}-node".format(rpm_prefix),
"version": openshift_release,
"check_multi": check_multi_minor_release,
},
],
}
return self.execute_module_with_retries("aos_version", args)
def get_required_ovs_version(self):
"""Return the correct Open vSwitch version(s) for the current OpenShift version."""
return self.get_required_version("Open vSwitch", self.openshift_to_ovs_version)
def get_required_docker_version(self):
"""Return the correct Docker version(s) for the current OpenShift version."""
return self.get_required_version("Docker", self.openshift_to_docker_version)
|
apache-2.0
|
bykoianko/omim
|
geocoder/geocoder_tests/geocoder_tests.cpp
|
6292
|
#include "testing/testing.hpp"
#include "geocoder/geocoder.hpp"
#include "indexer/search_string_utils.hpp"
#include "platform/platform_tests_support/scoped_file.hpp"
#include "base/geo_object_id.hpp"
#include "base/math.hpp"
#include "base/stl_helpers.hpp"
#include <algorithm>
#include <string>
#include <vector>
using namespace platform::tests_support;
using namespace std;
namespace
{
double const kCertaintyEps = 1e-6;
string const kRegionsData = R"#(
-4611686018427080071 {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-80.1142033187951, 21.55511095]}, "properties": {"name": "Cuba", "rank": 2, "address": {"country": "Cuba"}}}
-4611686018425533273 {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-78.7260117405499, 21.74300205]}, "properties": {"name": "Ciego de Ávila", "rank": 4, "address": {"region": "Ciego de Ávila", "country": "Cuba"}}}
-4611686018421500235 {"type": "Feature", "geometry": {"type": "Point", "coordinates": [-78.9263054493181, 22.08185765]}, "properties": {"name": "Florencia", "rank": 6, "address": {"subregion": "Florencia", "region": "Ciego de Ávila", "country": "Cuba"}}}
)#";
geocoder::Tokens Split(string const & s)
{
geocoder::Tokens result;
search::NormalizeAndTokenizeAsUtf8(s, result);
return result;
}
} // namespace
namespace geocoder
{
void TestGeocoder(Geocoder & geocoder, string const & query, vector<Result> && expected)
{
vector<Result> actual;
geocoder.ProcessQuery(query, actual);
TEST_EQUAL(actual.size(), expected.size(), (query, actual, expected));
sort(actual.begin(), actual.end(), base::LessBy(&Result::m_osmId));
sort(expected.begin(), expected.end(), base::LessBy(&Result::m_osmId));
for (size_t i = 0; i < actual.size(); ++i)
{
TEST(actual[i].m_certainty >= 0.0 && actual[i].m_certainty <= 1.0,
(query, actual[i].m_certainty));
TEST_EQUAL(actual[i].m_osmId, expected[i].m_osmId, (query));
TEST(base::AlmostEqualAbs(actual[i].m_certainty, expected[i].m_certainty, kCertaintyEps),
(query, actual[i].m_certainty, expected[i].m_certainty));
}
}
UNIT_TEST(Geocoder_Smoke)
{
ScopedFile const regionsJsonFile("regions.jsonl", kRegionsData);
Geocoder geocoder(regionsJsonFile.GetFullPath());
base::GeoObjectId const florenciaId(0xc00000000059d6b5);
base::GeoObjectId const cubaId(0xc00000000004b279);
TestGeocoder(geocoder, "florencia", {{florenciaId, 1.0}});
TestGeocoder(geocoder, "cuba florencia", {{florenciaId, 1.0}, {cubaId, 0.714286}});
TestGeocoder(geocoder, "florencia somewhere in cuba", {{cubaId, 0.714286}, {florenciaId, 1.0}});
}
UNIT_TEST(Geocoder_Hierarchy)
{
ScopedFile const regionsJsonFile("regions.jsonl", kRegionsData);
Geocoder geocoder(regionsJsonFile.GetFullPath());
auto entries = geocoder.GetHierarchy().GetEntries({("florencia")});
TEST(entries, ());
TEST_EQUAL(entries->size(), 1, ());
TEST_EQUAL((*entries)[0]->m_address[static_cast<size_t>(Type::Country)], Split("cuba"), ());
TEST_EQUAL((*entries)[0]->m_address[static_cast<size_t>(Type::Region)], Split("ciego de avila"),
());
TEST_EQUAL((*entries)[0]->m_address[static_cast<size_t>(Type::Subregion)], Split("florencia"),
());
}
UNIT_TEST(Geocoder_OnlyBuildings)
{
string const kData = R"#(
10 {"properties": {"address": {"locality": "Some Locality"}}}
21 {"properties": {"address": {"street": "Good", "locality": "Some Locality"}}}
22 {"properties": {"address": {"building": "5", "street": "Good", "locality": "Some Locality"}}}
31 {"properties": {"address": {"street": "Bad", "locality": "Some Locality"}}}
32 {"properties": {"address": {"building": "10", "street": "Bad", "locality": "Some Locality"}}}
40 {"properties": {"address": {"street": "MaybeNumbered", "locality": "Some Locality"}}}
41 {"properties": {"address": {"street": "MaybeNumbered-3", "locality": "Some Locality"}}}
42 {"properties": {"address": {"building": "3", "street": "MaybeNumbered", "locality": "Some Locality"}}}
)#";
ScopedFile const regionsJsonFile("regions.jsonl", kData);
Geocoder geocoder(regionsJsonFile.GetFullPath());
base::GeoObjectId const localityId(10);
base::GeoObjectId const goodStreetId(21);
base::GeoObjectId const badStreetId(31);
base::GeoObjectId const building5(22);
base::GeoObjectId const building10(32);
TestGeocoder(geocoder, "some locality", {{localityId, 1.0}});
TestGeocoder(geocoder, "some locality good", {{goodStreetId, 1.0}, {localityId, 0.857143}});
TestGeocoder(geocoder, "some locality bad", {{badStreetId, 1.0}, {localityId, 0.857143}});
TestGeocoder(geocoder, "some locality good 5", {{building5, 1.0}});
TestGeocoder(geocoder, "some locality bad 10", {{building10, 1.0}});
// There is a building "10" on Bad Street but we should not return it.
// Another possible resolution would be to return just "Good Street" (relaxed matching)
// but at the time of writing the goal is to either have an exact match or no match at all.
TestGeocoder(geocoder, "some locality good 10", {});
// Sometimes we may still emit a non-building.
// In this case it happens because all query tokens are used.
base::GeoObjectId const numberedStreet(41);
base::GeoObjectId const houseOnANonNumberedStreet(42);
TestGeocoder(geocoder, "some locality maybenumbered 3",
{{numberedStreet, 1.0}, {houseOnANonNumberedStreet, 0.8875}});
}
UNIT_TEST(Geocoder_MismatchedLocality)
{
string const kData = R"#(
10 {"properties": {"address": {"locality": "Moscow"}}}
11 {"properties": {"address": {"locality": "Paris"}}}
21 {"properties": {"address": {"street": "Street", "locality": "Moscow"}}}
22 {"properties": {"address": {"building": "2", "street": "Street", "locality": "Moscow"}}}
31 {"properties": {"address": {"street": "Street", "locality": "Paris"}}}
32 {"properties": {"address": {"building": "3", "street": "Street", "locality": "Paris"}}}
)#";
ScopedFile const regionsJsonFile("regions.jsonl", kData);
Geocoder geocoder(regionsJsonFile.GetFullPath());
base::GeoObjectId const building2(22);
TestGeocoder(geocoder, "Moscow Street 2", {{building2, 1.0}});
// "Street 3" looks almost like a match to "Paris-Street-3" but we should not emit it.
TestGeocoder(geocoder, "Moscow Street 3", {});
}
} // namespace geocoder
|
apache-2.0
|
ilearninging/xxhis
|
all/2591.html
|
12585
|
</div><form action="search.asp" name="form1" id="form1">
<table border="1" id="table1" style="border-collapse: collapse">
<tr>
<td height="25" align="center"><span style="font-size: 16px">清</span></td>
<td height="25" align="center"><span style="font-size: 16px">公元1664年</span></td>
<td height="25" align="center"><span style="font-size: 16px">甲辰</span></td>
<td height="25px" align="center"><span style="font-size: 16px">康熙三年</span></td>
</tr>
<tr>
<td colspan="4">
<table border="0" width="100%">
<tr>
<td valign="top">
<b>历史纪事</b> </td>
<td>
<div>水西等地苗民抗清
康熙三年(1664),水西、陇纳、上下木咱等地的苗民愤起抗清。他们在首领安坤、安如鼎的率领下同清军展开了多次激战,云南总兵刘称被斩。平西王吴三桂调集云南、贵州及广西三省兵会剿。自二月以来,擒杀陇纳等地苗民一千余名、安坤、安如鼎仅以身免。
划分湖广、偏沅巡抚辖地
康熙三年(1664)二月,清政府以武昌、汉阳、黄州、安陆、德安、荆州、襄阳、郧阳八府归湖广巡抚管辖。以长沙、衡州、永州、宝庆、辰州、常德、岳州七府,郴、靖二州归偏沅巡抚管辖。是月,添设湖广按察使司按察使、驻扎长沙府。三月十九日,命湖广右布政,移驻长沙,管辖长沙、宝庆、衡州、永州、辰州、常德、岳州等七府及郴、靖二州。四月,由于明确了管辖范围,偏沅巡抚周召南疏报,岳州、长沙、宝庆、永州等十二府州共开垦土地一千二百一十二顷三十六亩。湖广巡抚刘兆麟疏报,安陆、荆州等十府州陆续垦田一千八百零七顷四十五亩。清初垦田的迅速发展,与划分辖地直接相关。
郑经退归台湾
康熙三年(1664)三月,郑经在接连战败后,众心离散,镇营多叛,诸军乏粮,铜山再难坚守,于是,他与陈永华、冯锡范等率余众,退归台湾。郑经命周全斌断后。周全斌与兵官洪旭不睦,想借此时机偷袭,兼并其部。洪旭则预有防范。周全斌虑入台后,恐为其加害,乃率部自漳浦投清,封承恩伯。郑经的另一战将黄廷也于云霄降清,封慕义伯。工官冯澄世另乘一船随向台湾,途中为其家丁所迫,投海而死。郑经余众士气沮丧。郑经抵达台湾后,鼓励诸镇将士开垦荒田,栽种五谷,储备粮草,发展糖业,支持贸易。此后,农业丰收,兵民相安。同时,他还推广大陆的先进技术,伐木斩竹,烧瓦盖房;严禁赌博,与民休息,修筑丘埕,引海水晒盐,民得其益。并接受陈永华的建议,择地建造圣庙,设立学校,广收人才。是时,台湾在农业、教育等方面取得了进展。
松江人民反清起义
康熙三年(1664)四月,松月(上海市吴淞江以南地区)人民亡明后裔朱光辅(即朱二官)、朱拱橺(即朱日生)起义,称周王,有封职、宝印、札付、号旗等。园顿教、涅盘教、拜空教、大乘教等江南教徒纷纷参加起义。松江知府张羽明发觉后,逮捕总兵金仲美等八十余人,全部凌迟处死。复兴大狱,株连者不计其数。独朱光辅、朱拱橺严缉而未获。张羽明企图通过残酷镇压这次起义而得以高升,然而,时过未久,他也被革职。
明确奉天府辖区
康熙三年(1664)五月,清政府设承德、开原、铁岭三县,添设奉天府丞等官,改辽阳为辽州,会同海盐、盖平,均属奉天府。改广宁为府,添设通判、推官等职,设广宁县、宁远州,属广宁府,俱令奉天府府尹管辖。次年元月,又改奉天所属锦县为锦州府,广宁府改为广宁县,属锦州府。
郑氏官兵弃明投清
自康熙元年(1662)至康熙三年(1664),据管理福建安辑投诚的官员贲岱疏报:郑氏部众共投诚文武官三千九百八十五名,食粮兵四万零九百六十二名,归农官弁兵民六万四千三百三十名,眷属人役六万三千余名,大小船只九百余艘。其中,有郑经亲属郑缵绪、忠明伯周全斌、威远将军翁求多、永安候黄廷、副统领何义等文武要员。</div></td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="4">
<table border="0" width="100%">
<tr>
<td valign="top">
<b>文化纪事</b> </td>
<td>
<div>文学家钱谦益逝世
钱谦益(1582-1664)。谦益字受之,号牧斋、蒙叟,常熟人。著有《初学集》、《有学集》等,编有《列朝诗集》。有藏书楼名绛云楼,顺治七年失火烧毁。谦益妾柳如是(1618—1664),号河东君、靡芜君,能诗画。</div></td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="4">
<table border="0" width="100%">
<tr>
<td valign="top">
<b>杂谭逸事</b> </td>
<td>
<div>李率泰驰令沿海岛屿设“界沟”“界墙”
福建总督李率泰于康熙三年(1664)三月闻郑经退归台湾,即于当月移师铜山,下令沿海与各岛屿的居民,全部迁入内地。逢山之处,开凿宽、深各二丈之余的大沟,名曰“界沟”。修筑高一丈、厚四尺有余的高墙,名曰“界墙”。又于登高处建造炮台,二、三十里设大营盘,分兵把守。福建、浙江等沿海设省皆如此。当时,如有人想从这些地方处出入,必先行贿于守界牟兵,否则,稍有怨言则拖出杀死。此令实施后,沿海居民离乡背井,家破人亡,无以为生。康熙四年六月,李率泰又签署告示,禁止居住在福建的荷兰人与中国人之间的一切贸易。康熙五年(1666)二月,李率泰病故。他在遗疏中提出:荷兰夹板船虽已回国,但仍往来频繁,他日恐生事端;迁海之民尽失旧业,应将界限略做放宽,使他们有耕渔之获,从而改变其流离失所的惨状。
鳌拜绞杀飞扬古
康熙帝亲政前,由四辅政大臣辅政,鳌拜是其中的重要一员。内大臣飞扬古与鳌拜等辅臣素有旧怨。康熙三年(1664),鳌拜势焰日炽。飞扬古之子、侍卫倭赫及侍卫西住、折克图、塞尔弼四人,同值御前,不敬辅臣,招致鳌拜忌恨。四月初七日,鳌拜等辅臣借口这些人擅骑皇帝坐马、私用皇帝弓箭射鹿为理由,将他们论罪斩首。复以飞扬古守陵有埋怨情词为借口,将他与其子尼侃及出征之子萨哈连一并绞死。惟色黑以不知情,免死,后发配宁古塔。飞扬古等房屋家产拨归鳌拜之弟穆里玛。折克图之父鄂莫克图、西住之兄图尔喀、塞尔弼之兄塔达等都以其明知子弟犯罪重大,不立即请旨治罪,分别革职、鞭责。
礼部审讯汤若望等西方传教士
汤若望,字道未,德国人,耶稣会传教士,原名约翰·亚当·沙尔·封·自尔(Johann Adam Shall Von Bell)。他通晓天文历法,译撰了大量的西欧古典天文学论著。顺治、康熙年间,掌管钦天监达二十年。顺治帝病逝前夕,江南徽州府新安卫官生杨光先即以耶稣会非中国圣人之教,以及汤若望所修的《时宪历书》封面不应当题写“依西洋新法”五字,具呈礼部。此外,他还认为汤若望布教的目的是“暗窃正朔之权以予西洋”,礼部不予受理。此后,杨光先发表《辟邪论》,攻击汤若望及其在华的基督教。康熙三年(1664),西方传教士利类思、安文思写出《天学传概》,据理驳斥。继而双方展开笔战,杨光先有《不得已》,利类思则刊出《不得已辨》。这年七月二十六日,杨光先在鳌拜等辅政大臣的支持下,再向礼部呈《请诛邪教疏》,指控汤若望等传教士,以修历法为名,窥伺朝廷秘密,内外勾结,图谋不轨,已触犯《大清律》中的谋叛、妖书诸条款。八月初七日,礼部开始传讯汤若望、南怀仁、利类思、安文思等西方传教士及钦天监监副李祖白、翰林许之渐、汤若望义子潘尽孝等有关人员。又下令各省传教士由地方官拘禁待审。审讯达四个月,至康熙四年元月,判处汤若望等革职去衔,潘尽孝因系武职交兵部惩处,余者则由刑部议罪。此后,汤若望等人又经过多次审讯、议决,险遭凌迟。康熙四年五月初五日,康熙帝命将李祖白等五名钦天监官员处斩,利类思、安文思、南怀仁赦出,汤若望及其他同案犯人则在押待处。不久,康熙帝的祖母(即孝庄文皇后)对辅臣如此对待汤若望深表不满,命令立即释放。同年八月,其余各地集中在京的传教士,均被驱逐出京,限期到达广州。杨光先因此而升任钦天监监正之职,住进汤若望馆所(天主教西堂)。康熙五年(1666)七月十五日,汤若望在京病逝,时年七十四岁。康熙八年(1669)八月,康熙帝为汤若望、李祖白等平冤昭雪。恢复汤若望的“通微教师”称号、追赐其原官、归还其教堂建堂基地、按照原品赐予祭恤费用。至于天主教,康熙帝只准南怀仁等照常活动,严禁各省立堂传教,并命严行晓谕。
李来亨以死抗清
康熙三年(1664),原明末大顺农民起义军,只有李来亨率部众坚守茅麓山,奋力抗清。是年,清军集结二十万人,三路进兵。大败后,将满汉三省兵“分汛连营,树立木城,挑堑排桩,密匝围之。”同年六月和闰六月,李来亨两次亲自率将士出击,力图冲破清军的封锁,但由于双方实力悬殊,李来亨又孤军作战,更无援军,未能取胜。当双方相持到九月时,农民军粮食用尽,清军重重围困。李来亨自知不能久存,但他镇静自若,大义凛然,在会集了众将、安排好农民军的撤离等事后,当月二十四日,举火焚烧了山寨,并和妻子、亲随等人投火自焚,宁死不屈。李来亨部的三万余名战士,被俘者仅一百五十人。
朱舜水赴日本讲学
舜水,是朱氏家乡浙江绍兴府余姚县的水名(浙江省余姚市),本名之瑜,字鲁屿,流寓日本后遂以故乡水名取为号。朱舜水成长于明末清初,勤奋好学,疾恶如仇,对于官场的腐败现状,尤为痛恨。南明弘光政权建立后,他意识到决不能与以马士英等奸佞同党,免受世人唾骂,于是,力辞做官之命,马士英等恨他,下令逮捕。朱舜水闻讯,连夜逃往通向日本的海上贸易要道舟山。此后,他坚决支持黄宗羲、王翊、张名振、郑成功等人的抗清斗争。往返日本,乞师发兵,未成。清军围其船,他突围而出。顺治十六年冬末(1659),他年届花甲,孑然一身,来到长崎,度日维艰,以教书为生,日本关西的著名学者安东省庵是朱舜水早年好友,对他的学识与气节深表敬佩。在安东省庵的倡导下,另外几位友好人士,为朱舜水连名申请讲学,几经周折,破例获准。自此,他开始在日本讲学著述,并把中国的许多进步思想家的批准精神和研究成果广为宣传,倡议日本注重经世致用的思想,成为中国在日本的著名学者。清康熙三年秋(1664),日本水户潘主德川光国派儒生小宅生顺赴长崎会见朱舜水,相互研讨学问。小宅对朱舜水非常尊崇,鼎力举荐。德川以懿亲辅政,礼贤下士,事朱舜水为师,相谈非常溶洽。其间,朱舜水不断提倡改革、兴办学校、培养人才。两年后,德川在水户盖好学宫,请朱舜水主持。在日本的二十余年间,朱舜水与思想、教育、学术各界和农业、匠作、建筑、园艺、医界等方面的学士进行了广泛交流,影响深远,成就卓著,是中日友好往史的突出代表。康熙二十一年(1682)二月他在日本江户(东京)逝世,年八十三岁,著有《朱舜水集》等。</div></td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="4">
<table border="0" width="100%">
<tr>
<td valign="top">
<b>注释</b></td>
<td>
<div></div></td>
</tr>
</table>
</td>
</tr>
<tr>
</tr></table>
|
apache-2.0
|
edersonmf/flickring
|
src/main/java/com/emf/flickring/manager/ApiKeysCommand.java
|
7638
|
package com.emf.flickring.manager;
import static com.emf.flickring.Command.Response.END;
import static com.emf.flickring.deploy.DeployModule.Constant.API_KEY;
import static com.emf.flickring.deploy.DeployModule.Constant.BASE_PICS_DIR;
import static com.emf.flickring.deploy.DeployModule.Constant.SECRET;
import static com.emf.flickring.deploy.DeployModule.Constant.SECRET_KEY;
import static com.emf.flickring.deploy.DeployModule.Constant.TOKEN;
import static com.emf.flickring.deploy.DeployModule.Constant.USER_ID;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.FileConfiguration;
import org.scribe.exceptions.OAuthException;
import org.scribe.model.Token;
import org.scribe.model.Verifier;
import com.emf.flickring.Command;
import com.emf.flickring.deploy.DeployModule;
import com.emf.flickring.model.ConfigInput;
import com.flickr4java.flickr.Flickr;
import com.flickr4java.flickr.FlickrException;
import com.flickr4java.flickr.RequestContext;
import com.flickr4java.flickr.auth.Auth;
import com.flickr4java.flickr.auth.AuthInterface;
import com.flickr4java.flickr.auth.Permission;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.io.Files;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
@Slf4j
public class ApiKeysCommand implements Command {
private final FileConfiguration config;
private final Flickr flickr;
@Inject
public ApiKeysCommand(final Configuration config, final Flickr flickr) {
this.config = (FileConfiguration) config;
this.flickr = flickr;
}
@Override
public Response process(final Chain chain) {
log.debug("Running api keys command...");
String apikey = config.getString(API_KEY, null);
String secret = config.getString(SECRET_KEY, null);
String tokenValue = config.getString(TOKEN, null);
String basePicsDir = config.getString(BASE_PICS_DIR, null);
String userId = config.getString(USER_ID, null);
final File configFile = config.getFile();
if (!configFile.exists()) {
log.debug("Config file does not exist");
try {
Files.touch(configFile);
} catch (IOException e) {
log.warn("Could not create config file. {}", e.getMessage());
return END;
}
}
final Scanner scanner = new Scanner(System.in);
try {
// Check api key
if (Strings.isNullOrEmpty(apikey)) {
log.debug("Api key is null");
final ConfigInput apiKeyInput = ConfigInput.builder().label("Enter your Flickr api key:").scanner(scanner).build();
apiKeyInput.read();
apikey = apiKeyInput.getInputedValue();
if (Strings.isNullOrEmpty(apikey)) {
log.warn("Api key is empty...");
return END;
} else {
config.addProperty(API_KEY, apikey);
}
} else {
log.debug("Api key is not null");
}
// Check secret key
if (Strings.isNullOrEmpty(secret)) {
log.debug("Secret key is null");
final ConfigInput secretKeyInput = ConfigInput.builder().label("Enter your Flickr secret key:").scanner(scanner).build();
secretKeyInput.read();
secret = secretKeyInput.getInputedValue();
if (Strings.isNullOrEmpty(secret)) {
log.warn("Secret key is empty...");
return END;
} else {
config.addProperty(SECRET_KEY, secret);
}
} else {
log.debug("Secret key is not null");
}
// Check token
final RequestContext requestContext = RequestContext.getRequestContext();
Flickr.debugStream = false;
flickr.setApiKey(config.getString(API_KEY));
flickr.setSharedSecret(config.getString(SECRET_KEY));
final AuthInterface authInterface = flickr.getAuthInterface();
if (Strings.isNullOrEmpty(tokenValue)) {
log.debug("Flickr token is null");
final Token token = authInterface.getRequestToken();
final String url = authInterface.getAuthorizationUrl(token, Permission.WRITE);
final StringBuilder label = new StringBuilder("Follow this URL to authorise yourself on Flickr");
label.append("\n")
.append(url).append("\n")
.append("Paste in the token it gives you:").append("\n");
final ConfigInput tokenInput = ConfigInput.builder().label(label.toString()).scanner(scanner).build();
tokenInput.read();
tokenValue = tokenInput.getInputedValue();
final Token requestToken = authInterface.getAccessToken(token, new Verifier(tokenValue));
// Check userId
if (Strings.isNullOrEmpty(userId)) {
try {
final Auth auth = authInterface.checkToken(requestToken);
userId = auth.getUser().getId();
if (Strings.isNullOrEmpty(userId)) {
log.error("Could not get user id.");
return END;
}
config.addProperty(USER_ID, userId);
requestContext.setAuth(auth);
log.info("User is authenticated.");
} catch (FlickrException e) {
log.error("Could not get user id", e);
return END;
}
}
if (requestToken == null || requestToken.isEmpty()) {
log.debug("User token is empty...");
return END;
} else {
config.addProperty(TOKEN, requestToken.getToken());
config.addProperty(SECRET, requestToken.getSecret());
log.info("Authentication success");
}
} else {
log.debug("Authenticating flickr user...");
Auth auth;
try {
auth = authInterface.checkToken(config.getString(TOKEN), config.getString(SECRET));
log.debug("User is authenticated.");
requestContext.setAuth(auth);
} catch (FlickrException e) {
log.error("Could not authenticate user", e);
}
}
log.debug("Checking base pictures directory");
// Check base pictures dir
if (Strings.isNullOrEmpty(basePicsDir)) {
final ConfigInput basePicsDirInput = ConfigInput.builder().label("Enter your pictures folder location:").scanner(scanner).build();
basePicsDirInput.read();
basePicsDir = basePicsDirInput.getInputedValue();
if (Strings.isNullOrEmpty(basePicsDir)) {
log.error("Base pictures location is empty...");
return END;
} else {
config.addProperty(BASE_PICS_DIR, basePicsDir);
}
log.debug("Base picture dir: {}", basePicsDir);
}
} catch (OAuthException ex) {
log.error("Could not authenticate user.", ex);
} finally {
scanner.close();
}
log.debug("Calling next in charge in the chain...");
return chain.execute();
}
@Override
public void stop() {
// Does nothing
}
public static void main(final String[] args) {
Preconditions.checkNotNull(args);
Preconditions.checkArgument(args.length > 0);
final Injector injector = Guice.createInjector(new DeployModule(args[0]));
final ApiKeysCommand command = injector.getInstance(ApiKeysCommand.class);
command.process(new Chain() {
@SuppressWarnings("unchecked")
@Override
public <T> T execute() {
log.info("API Keys Command is success");
return (T) Response.SUCCESS;
}
@Override
public void breakIt() {
log.info("API Keys Command has failed");
}
});
}
}
|
apache-2.0
|
am0e/commons
|
src/main/java/com/github/am0e/utils/Handler.java
|
1071
|
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.github.am0e.utils;
public interface Handler<T> {
public void handle(T ctx) throws Exception;
}
|
apache-2.0
|
google/kube-node-tracer
|
Dockerfile
|
419
|
FROM gcr.io/google.com/cloudsdktool/cloud-sdk:alpine
VOLUME ["/dump"]
RUN apk add --no-cache --update bash coreutils which curl tcpdump inotify-tools
COPY ./kube_node_tracer.sh /
COPY ./rolling_tcpdump.sh /
COPY ./file_watcher.sh /
RUN mkdir -p /dump
RUN chmod +x /kube_node_tracer.sh
RUN chmod +x /rolling_tcpdump.sh
RUN chmod +x /file_watcher.sh
ENTRYPOINT ["bash", "/kube_node_tracer.sh"]
|
apache-2.0
|
armstrong/armstrong.core.arm_layout
|
tests/templatetags/__init__.py
|
30
|
from .layout_helpers import *
|
apache-2.0
|
Youngman619/cwkz
|
src/wx/sunl/entry/WeixinOauth2Token.java
|
1035
|
package wx.sunl.entry;
/**
* WeixinUserInfo(΢ÐÅÓû§µÄ»ù±¾ÐÅÏ¢)
* @author Youngman
*/
public class WeixinOauth2Token {
// ÍøÒ³ÊÚȨ½Ó¿Úµ÷ÓÃÆ¾Ö¤
private String accessToken;
// ƾ֤ÓÐЧʱ³¤
private int expiresIn;
// ÓÃÓÚË¢ÐÂÆ¾Ö¤
private String refreshToken;
// Óû§±êʶ
private String openId;
// Óû§ÊÚȨ×÷ÓÃÓò
private String scope;
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public int getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(int expiresIn) {
this.expiresIn = expiresIn;
}
public String getRefreshToken() {
return refreshToken;
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
}
|
apache-2.0
|
craigacgomez/flaming_monkey_packages_apps_Email
|
src/com/android/email/provider/AttachmentProvider.java
|
13480
|
/*
* Copyright (C) 2008 The Android Open Source Project
*
* 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.android.email.provider;
import com.android.emailcommon.Logging;
import com.android.emailcommon.internet.MimeUtility;
import com.android.emailcommon.provider.EmailContent;
import com.android.emailcommon.provider.EmailContent.Attachment;
import com.android.emailcommon.provider.EmailContent.AttachmentColumns;
import com.android.emailcommon.utility.AttachmentUtilities;
import com.android.emailcommon.utility.AttachmentUtilities.Columns;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Binder;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/*
* A simple ContentProvider that allows file access to Email's attachments.
*
* The URI scheme is as follows. For raw file access:
* content://com.android.email.attachmentprovider/acct#/attach#/RAW
*
* And for access to thumbnails:
* content://com.android.email.attachmentprovider/acct#/attach#/THUMBNAIL/width#/height#
*
* The on-disk (storage) schema is as follows.
*
* Attachments are stored at: <database-path>/account#.db_att/item#
* Thumbnails are stored at: <cache-path>/thmb_account#_item#
*
* Using the standard application context, account #10 and attachment # 20, this would be:
* /data/data/com.android.email/databases/10.db_att/20
* /data/data/com.android.email/cache/thmb_10_20
*/
public class AttachmentProvider extends ContentProvider {
private static final String[] MIME_TYPE_PROJECTION = new String[] {
AttachmentColumns.MIME_TYPE, AttachmentColumns.FILENAME };
private static final int MIME_TYPE_COLUMN_MIME_TYPE = 0;
private static final int MIME_TYPE_COLUMN_FILENAME = 1;
private static final String[] PROJECTION_QUERY = new String[] { AttachmentColumns.FILENAME,
AttachmentColumns.SIZE, AttachmentColumns.CONTENT_URI };
@Override
public boolean onCreate() {
/*
* We use the cache dir as a temporary directory (since Android doesn't give us one) so
* on startup we'll clean up any .tmp files from the last run.
*/
File[] files = getContext().getCacheDir().listFiles();
for (File file : files) {
String filename = file.getName();
if (filename.endsWith(".tmp") || filename.startsWith("thmb_")) {
file.delete();
}
}
return true;
}
/**
* Returns the mime type for a given attachment. There are three possible results:
* - If thumbnail Uri, always returns "image/png" (even if there's no attachment)
* - If the attachment does not exist, returns null
* - Returns the mime type of the attachment
*/
@Override
public String getType(Uri uri) {
long callingId = Binder.clearCallingIdentity();
try {
List<String> segments = uri.getPathSegments();
String id = segments.get(1);
String format = segments.get(2);
if (AttachmentUtilities.FORMAT_THUMBNAIL.equals(format)) {
return "image/png";
} else {
uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, Long.parseLong(id));
Cursor c = getContext().getContentResolver().query(uri, MIME_TYPE_PROJECTION, null,
null, null);
try {
if (c.moveToFirst()) {
String mimeType = c.getString(MIME_TYPE_COLUMN_MIME_TYPE);
String fileName = c.getString(MIME_TYPE_COLUMN_FILENAME);
mimeType = AttachmentUtilities.inferMimeType(fileName, mimeType);
return mimeType;
}
} finally {
c.close();
}
return null;
}
} finally {
Binder.restoreCallingIdentity(callingId);
}
}
/**
* Open an attachment file. There are two "formats" - "raw", which returns an actual file,
* and "thumbnail", which attempts to generate a thumbnail image.
*
* Thumbnails are cached for easy space recovery and cleanup.
*
* TODO: The thumbnail format returns null for its failure cases, instead of throwing
* FileNotFoundException, and should be fixed for consistency.
*
* @throws FileNotFoundException
*/
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
// If this is a write, the caller must have the EmailProvider permission, which is
// based on signature only
if (mode.equals("w")) {
Context context = getContext();
if (context.checkCallingPermission(EmailContent.PROVIDER_PERMISSION)
!= PackageManager.PERMISSION_GRANTED) {
throw new FileNotFoundException();
}
List<String> segments = uri.getPathSegments();
String accountId = segments.get(0);
String id = segments.get(1);
File saveIn =
AttachmentUtilities.getAttachmentDirectory(context, Long.parseLong(accountId));
if (!saveIn.exists()) {
saveIn.mkdirs();
}
File newFile = new File(saveIn, id);
return ParcelFileDescriptor.open(
newFile, ParcelFileDescriptor.MODE_READ_WRITE |
ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_TRUNCATE);
}
long callingId = Binder.clearCallingIdentity();
try {
List<String> segments = uri.getPathSegments();
String accountId = segments.get(0);
String id = segments.get(1);
String format = segments.get(2);
if (AttachmentUtilities.FORMAT_THUMBNAIL.equals(format)) {
int width = Integer.parseInt(segments.get(3));
int height = Integer.parseInt(segments.get(4));
String filename = "thmb_" + accountId + "_" + id;
File dir = getContext().getCacheDir();
File file = new File(dir, filename);
if (!file.exists()) {
Uri attachmentUri = AttachmentUtilities.
getAttachmentUri(Long.parseLong(accountId), Long.parseLong(id));
Cursor c = query(attachmentUri,
new String[] { Columns.DATA }, null, null, null);
if (c != null) {
try {
if (c.moveToFirst()) {
attachmentUri = Uri.parse(c.getString(0));
} else {
return null;
}
} finally {
c.close();
}
}
String type = getContext().getContentResolver().getType(attachmentUri);
try {
InputStream in =
getContext().getContentResolver().openInputStream(attachmentUri);
Bitmap thumbnail = createThumbnail(type, in);
if (thumbnail == null) {
return null;
}
thumbnail = Bitmap.createScaledBitmap(thumbnail, width, height, true);
FileOutputStream out = new FileOutputStream(file);
thumbnail.compress(Bitmap.CompressFormat.PNG, 100, out);
out.close();
in.close();
} catch (IOException ioe) {
Log.d(Logging.LOG_TAG, "openFile/thumbnail failed with " +
ioe.getMessage());
return null;
} catch (OutOfMemoryError oome) {
Log.d(Logging.LOG_TAG, "openFile/thumbnail failed with " +
oome.getMessage());
return null;
}
}
return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
}
else {
return ParcelFileDescriptor.open(
new File(getContext().getDatabasePath(accountId + ".db_att"), id),
ParcelFileDescriptor.MODE_READ_ONLY);
}
} finally {
Binder.restoreCallingIdentity(callingId);
}
}
@Override
public int delete(Uri uri, String arg1, String[] arg2) {
return 0;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
return null;
}
/**
* Returns a cursor based on the data in the attachments table, or null if the attachment
* is not recorded in the table.
*
* Supports REST Uri only, for a single row - selection, selection args, and sortOrder are
* ignored (non-null values should probably throw an exception....)
*/
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
long callingId = Binder.clearCallingIdentity();
try {
if (projection == null) {
projection =
new String[] {
Columns._ID,
Columns.DATA,
Columns.DISPLAY_NAME, // matched the DISPLAY_NAME of {@link OpenableColumns}
Columns.SIZE, // matched the SIZE of {@link OpenableColumns}
};
}
List<String> segments = uri.getPathSegments();
String accountId = segments.get(0);
String id = segments.get(1);
String format = segments.get(2);
String name = null;
int size = -1;
String contentUri = null;
uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, Long.parseLong(id));
Cursor c = getContext().getContentResolver().query(uri, PROJECTION_QUERY,
null, null, null);
try {
if (c.moveToFirst()) {
name = c.getString(0);
size = c.getInt(1);
contentUri = c.getString(2);
} else {
return null;
}
} finally {
c.close();
}
MatrixCursor ret = new MatrixCursor(projection);
Object[] values = new Object[projection.length];
for (int i = 0, count = projection.length; i < count; i++) {
String column = projection[i];
if (Columns._ID.equals(column)) {
values[i] = id;
}
else if (Columns.DATA.equals(column)) {
values[i] = contentUri;
}
else if (Columns.DISPLAY_NAME.equals(column)) {
values[i] = name;
}
else if (Columns.SIZE.equals(column)) {
values[i] = size;
}
}
ret.addRow(values);
return ret;
} finally {
Binder.restoreCallingIdentity(callingId);
}
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
private Bitmap createThumbnail(String type, InputStream data) {
if(MimeUtility.mimeTypeMatches(type, "image/*")) {
return createImageThumbnail(data);
}
return null;
}
private Bitmap createImageThumbnail(InputStream data) {
try {
Bitmap bitmap = BitmapFactory.decodeStream(data);
return bitmap;
} catch (OutOfMemoryError oome) {
Log.d(Logging.LOG_TAG, "createImageThumbnail failed with " + oome.getMessage());
return null;
} catch (Exception e) {
Log.d(Logging.LOG_TAG, "createImageThumbnail failed with " + e.getMessage());
return null;
}
}
/**
* Need this to suppress warning in unit tests.
*/
@Override
public void shutdown() {
// Don't call super.shutdown(), which emits a warning...
}
}
|
apache-2.0
|
inbloom/secure-data-service
|
tools/data-tools/src/org/slc/sli/test/edfi/entitiesR1/Program.java
|
6094
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.08.31 at 10:43:34 AM EDT
//
package org.slc.sli.test.edfi.entitiesR1;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
*
* This entity represents any program designed to work
* in conjunction with or to supplement the main
* academic program.
* Programs may provide instruction, training, services or benefits
* through federal,
* state, or local agencies. Programs may also include
* organized extracurricular activities for students.
*
*
* <p>Java class for program complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="program">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="programId" type="{http://slc-sli/ed-org/0.1}programId" minOccurs="0"/>
* <element name="programType" type="{http://slc-sli/ed-org/0.1}programType"/>
* <element name="programSponsor" type="{http://slc-sli/ed-org/0.1}programSponsorType" minOccurs="0"/>
* <element name="services" type="{http://slc-sli/ed-org/0.1}serviceDescriptorReferenceType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="staffAssociations" type="{http://slc-sli/ed-org/0.1}staffProgramAssociation" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "program", propOrder = {
"programId",
"programType",
"programSponsor",
"services",
"staffAssociations"
})
public class Program {
protected String programId;
@XmlElement(required = true)
protected ProgramType programType;
protected ProgramSponsorType programSponsor;
protected List<ServiceDescriptorReferenceType> services;
protected List<StaffProgramAssociation> staffAssociations;
/**
* Gets the value of the programId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getProgramId() {
return programId;
}
/**
* Sets the value of the programId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setProgramId(String value) {
this.programId = value;
}
/**
* Gets the value of the programType property.
*
* @return
* possible object is
* {@link ProgramType }
*
*/
public ProgramType getProgramType() {
return programType;
}
/**
* Sets the value of the programType property.
*
* @param value
* allowed object is
* {@link ProgramType }
*
*/
public void setProgramType(ProgramType value) {
this.programType = value;
}
/**
* Gets the value of the programSponsor property.
*
* @return
* possible object is
* {@link ProgramSponsorType }
*
*/
public ProgramSponsorType getProgramSponsor() {
return programSponsor;
}
/**
* Sets the value of the programSponsor property.
*
* @param value
* allowed object is
* {@link ProgramSponsorType }
*
*/
public void setProgramSponsor(ProgramSponsorType value) {
this.programSponsor = value;
}
/**
* Gets the value of the services property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the services property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getServices().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ServiceDescriptorReferenceType }
*
*
*/
public List<ServiceDescriptorReferenceType> getServices() {
if (services == null) {
services = new ArrayList<ServiceDescriptorReferenceType>();
}
return this.services;
}
/**
* Gets the value of the staffAssociations property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the staffAssociations property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getStaffAssociations().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link StaffProgramAssociation }
*
*
*/
public List<StaffProgramAssociation> getStaffAssociations() {
if (staffAssociations == null) {
staffAssociations = new ArrayList<StaffProgramAssociation>();
}
return this.staffAssociations;
}
}
|
apache-2.0
|
pebble2015/cpoi
|
ext/stub/java/awt/geom/Path2D_Float_CopyIterator-stub.cpp
|
1586
|
// Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar
#include <java/awt/geom/Path2D_Float_CopyIterator.hpp>
extern void unimplemented_(const char16_t* name);
java::awt::geom::Path2D_Float_CopyIterator::Path2D_Float_CopyIterator(const ::default_init_tag&)
: super(*static_cast< ::default_init_tag* >(0))
{
clinit();
}
java::awt::geom::Path2D_Float_CopyIterator::Path2D_Float_CopyIterator(Path2D_Float* p2df)
: Path2D_Float_CopyIterator(*static_cast< ::default_init_tag* >(0))
{
ctor(p2df);
}
void ::java::awt::geom::Path2D_Float_CopyIterator::ctor(Path2D_Float* p2df)
{ /* stub */
/* super::ctor(); */
unimplemented_(u"void ::java::awt::geom::Path2D_Float_CopyIterator::ctor(Path2D_Float* p2df)");
}
int32_t java::awt::geom::Path2D_Float_CopyIterator::currentSegment(::floatArray* coords)
{ /* stub */
unimplemented_(u"int32_t java::awt::geom::Path2D_Float_CopyIterator::currentSegment(::floatArray* coords)");
return 0;
}
int32_t java::awt::geom::Path2D_Float_CopyIterator::currentSegment(::doubleArray* coords)
{ /* stub */
unimplemented_(u"int32_t java::awt::geom::Path2D_Float_CopyIterator::currentSegment(::doubleArray* coords)");
return 0;
}
extern java::lang::Class *class_(const char16_t *c, int n);
java::lang::Class* java::awt::geom::Path2D_Float_CopyIterator::class_()
{
static ::java::lang::Class* c = ::class_(u"java.awt.geom.Path2D.Float.CopyIterator", 39);
return c;
}
java::lang::Class* java::awt::geom::Path2D_Float_CopyIterator::getClass0()
{
return class_();
}
|
apache-2.0
|
IHTSDO/snow-owl
|
commons/com.b2international.index/src/com/b2international/index/es/AwaitPendingTasks.java
|
1558
|
/*
* Copyright 2017 B2i Healthcare Pte Ltd, http://b2i.sg
*
* 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.b2international.index.es;
import java.util.List;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.service.PendingClusterTask;
import org.slf4j.Logger;
/**
* @since 5.10
*/
public final class AwaitPendingTasks {
private static final int PENDING_CLUSTER_TASKS_RETRY_INTERVAL = 50;
private AwaitPendingTasks() {}
public static final void await(Client client, Logger log) {
int pendingTaskCount = 0;
do {
List<PendingClusterTask> pendingTasks = client.admin()
.cluster()
.preparePendingClusterTasks()
.get()
.getPendingTasks();
pendingTaskCount = pendingTasks.size();
if (pendingTaskCount > 0) {
log.info("Waiting for pending cluster tasks to finish.");
try {
Thread.sleep(PENDING_CLUSTER_TASKS_RETRY_INTERVAL);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
} while (pendingTaskCount > 0);
}
}
|
apache-2.0
|
milpol/jwt4j
|
src/main/java/jwt4j/checkers/IssuerChecker.java
|
614
|
package jwt4j.checkers;
import com.google.gson.JsonObject;
import jwt4j.TokenChecker;
import jwt4j.exceptions.InvalidIssuerException;
import static jwt4j.JWTConstants.ISSUER;
public class IssuerChecker implements TokenChecker
{
private final String issuer;
public IssuerChecker(final String issuer)
{
this.issuer = issuer;
}
@Override
public void check(JsonObject payloadJson)
{
if (!payloadJson.has(ISSUER) || !payloadJson.get(ISSUER).getAsString().equals(issuer)) {
throw new InvalidIssuerException("Expected " + issuer + " issuer");
}
}
}
|
apache-2.0
|
Mashape/kong
|
kong/plugins/request-size-limiting/handler.lua
|
1150
|
-- Copyright (C) Kong Inc.
local strip = require("pl.stringx").strip
local tonumber = tonumber
local MB = 2^20
local RequestSizeLimitingHandler = {}
RequestSizeLimitingHandler.PRIORITY = 951
RequestSizeLimitingHandler.VERSION = "2.0.0"
local function check_size(length, allowed_size, headers)
local allowed_bytes_size = allowed_size * MB
if length > allowed_bytes_size then
if headers.expect and strip(headers.expect:lower()) == "100-continue" then
return kong.response.exit(417, { message = "Request size limit exceeded" })
else
return kong.response.exit(413, { message = "Request size limit exceeded" })
end
end
end
function RequestSizeLimitingHandler:access(conf)
local headers = kong.request.get_headers()
local cl = headers["content-length"]
if cl and tonumber(cl) then
check_size(tonumber(cl), conf.allowed_payload_size, headers)
else
-- If the request body is too big, this could consume too much memory (to check)
local data = kong.request.get_raw_body()
if data then
check_size(#data, conf.allowed_payload_size, headers)
end
end
end
return RequestSizeLimitingHandler
|
apache-2.0
|
Gubancs/TypeUI
|
typeui-framework/src/main/resources/typescript/ui/TabPanel.ts
|
4557
|
/**
* A TabPanel osztály egységbe foglal több Panel-t, és segíti azok kezelését.
*
*
* @author Gabor Kokeny
*/
class TabPanel extends Container {
/**
* Ez a változó tárolja az aktív index értékét, amely egy pozitív egész szám.
*
* @property {number} activeTabIndex
*/
private activeIndex: number = null;
private activePanel: Panel;
private menu: TabPanelMenu;
/**
*
* @param {Container} parent
* @constructor
*/
constructor(parent: Container) {
super(parent, true);
this.setClass("ui-tabpanel");
this.getContainer().setClass("ui-tabpanel-wrapper");
this.menu = new TabPanelMenu(this.getContainer());
}
add(panel: Panel) {
if (!(panel instanceof Panel)) {
Log.error("Item couldn't add to tabpanel, because it is not a Panel", panel);
}
super.add(panel);
var me = this;
var listener = function(e:Event) {
var menuItem = new MenuItem(me.menu);
menuItem.setText(panel.getTitle());
menuItem.setIconClass(panel.getIconClass());
menuItem.addClickListener(function(e:MouseEvent){
me.setActivePanel(panel);
});
panel.removeListener(TabPanel.EVENT_BEFORE_RENDER, listener);
}
panel.addListener(TabPanel.EVENT_BEFORE_RENDER, listener);
//Log.debug("TabPanel children :", this.getChildren());
this.setActiveTabIndex(0);
}
/**
* Ezzel a metódussal lehet beállítani, hogy melyik legyen az aktív panel.
* Paraméterként egy számot kell megadnunk, ami nem lehet null, undifined, vagy negatív érték.
* A TabPanel 0 bázisindexű, így ha azt szeretnénk, hogy az első Panel legyen aktív akkor 0-t kell
* paraméterként megadni.
*
* Ha a paraméterként megadott index megegyezik az aktuális aktív index értékével, akkor a metódus kilép.
*
* @param {number} activeIndex
*/
setActiveTabIndex(index: number) {
this.checkTabIndex(index);
if (this.activeIndex == index) {
return;
}
var panel = this.getPanel(index);
this.setActivePanel(panel);
this.activeIndex = index;
}
/**
*
* @param {Panel} panel
* @private
*/
private setActivePanel(panel: Panel) {
Assert.notNull(panel, "panel");
if (this.activePanel) {
this.activePanel.removeClass("active");
}
this.activePanel = panel;
this.activePanel.addClass("active");
}
/**
* Ez a metódus vissza adja az aktív panel indexét.
* @return {number} Vissza adja a jelenleg aktív panel indexet. Ha nincs még panel hozzáadva a TabPanel-hez,
* akkor a -1 értékkel tér vissza.
*/
getActiveTabIndex(): number {
return this.activeIndex ? this.activeIndex : -1;
}
/**
* Ez a helper metódus eldönti, hogy a paraméterként kapott egész szám az megfelel-e
* a TabPanel által megkövetelt elvárásoknak.
*
* - Nem lehet null vagy undifined
* - Nem lehet negatív érték
* - Kisebb kell, hogy legyen mint a panelek száma.
*
* @param {number} tabIndex Az ellenőrizni kívánt index.
* @private
*/
private checkTabIndex(tabIndex: number) {
if (tabIndex === null || tabIndex === undefined) {
Log.error("The active tab index cannot be null or undifined");
}
if (tabIndex < 0) {
Log.error("The active tab index cannot be negative, it is should be a positve number!");
}
if (tabIndex >= this.getChildren().size()) {
Log.error("The active tab index should be less then " + this.getChildren().size());
}
}
/**
* Vissza adja a jelenleg aktív panelt. Az aktív panel módosítása
* a setActiveTabIndex metódus meghívásával lehetséges.
*
* @return {Panel} Az aktív panel vagy null érték, ha a TapPanel még üres.
*/
getActivePanel(): Panel {
return this.activePanel;
}
/**
*
* @param {number} index
* @return {Panel}
*/
getPanel(index: number): Panel {
//TODO check it
return <Panel>super.getComponent(index);
}
}
/**
*
* @author Gabor Kokeny
*/
class TabPanelMenu extends Menu {
constructor(parent: Container) {
super(parent);
}
}
|
apache-2.0
|
phenoxim/nova
|
nova/tests/unit/scheduler/client/test_report.py
|
143398
|
# 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.
import time
from keystoneauth1 import exceptions as ks_exc
import mock
from six.moves.urllib import parse
import nova.conf
from nova import context
from nova import exception
from nova import objects
from nova import rc_fields as fields
from nova.scheduler.client import report
from nova.scheduler import utils as scheduler_utils
from nova import test
from nova.tests.unit import fake_requests
from nova.tests import uuidsentinel as uuids
CONF = nova.conf.CONF
class SafeConnectedTestCase(test.NoDBTestCase):
"""Test the safe_connect decorator for the scheduler client."""
def setUp(self):
super(SafeConnectedTestCase, self).setUp()
self.context = context.get_admin_context()
with mock.patch('keystoneauth1.loading.load_auth_from_conf_options'):
self.client = report.SchedulerReportClient()
@mock.patch('keystoneauth1.session.Session.request')
def test_missing_endpoint(self, req):
"""Test EndpointNotFound behavior.
A missing endpoint entry should not explode.
"""
req.side_effect = ks_exc.EndpointNotFound()
self.client._get_resource_provider(self.context, "fake")
# reset the call count to demonstrate that future calls still
# work
req.reset_mock()
self.client._get_resource_provider(self.context, "fake")
self.assertTrue(req.called)
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_create_client')
@mock.patch('keystoneauth1.session.Session.request')
def test_missing_endpoint_create_client(self, req, create_client):
"""Test EndpointNotFound retry behavior.
A missing endpoint should cause _create_client to be called.
"""
req.side_effect = ks_exc.EndpointNotFound()
self.client._get_resource_provider(self.context, "fake")
# This is the second time _create_client is called, but the first since
# the mock was created.
self.assertTrue(create_client.called)
@mock.patch('keystoneauth1.session.Session.request')
def test_missing_auth(self, req):
"""Test Missing Auth handled correctly.
A missing auth configuration should not explode.
"""
req.side_effect = ks_exc.MissingAuthPlugin()
self.client._get_resource_provider(self.context, "fake")
# reset the call count to demonstrate that future calls still
# work
req.reset_mock()
self.client._get_resource_provider(self.context, "fake")
self.assertTrue(req.called)
@mock.patch('keystoneauth1.session.Session.request')
def test_unauthorized(self, req):
"""Test Unauthorized handled correctly.
An unauthorized configuration should not explode.
"""
req.side_effect = ks_exc.Unauthorized()
self.client._get_resource_provider(self.context, "fake")
# reset the call count to demonstrate that future calls still
# work
req.reset_mock()
self.client._get_resource_provider(self.context, "fake")
self.assertTrue(req.called)
@mock.patch('keystoneauth1.session.Session.request')
def test_connect_fail(self, req):
"""Test Connect Failure handled correctly.
If we get a connect failure, this is transient, and we expect
that this will end up working correctly later.
"""
req.side_effect = ks_exc.ConnectFailure()
self.client._get_resource_provider(self.context, "fake")
# reset the call count to demonstrate that future calls do
# work
req.reset_mock()
self.client._get_resource_provider(self.context, "fake")
self.assertTrue(req.called)
@mock.patch.object(report, 'LOG')
def test_warning_limit(self, mock_log):
# Assert that __init__ initializes _warn_count as we expect
self.assertEqual(0, self.client._warn_count)
mock_self = mock.MagicMock()
mock_self._warn_count = 0
for i in range(0, report.WARN_EVERY + 3):
report.warn_limit(mock_self, 'warning')
mock_log.warning.assert_has_calls([mock.call('warning'),
mock.call('warning')])
@mock.patch('keystoneauth1.session.Session.request')
def test_failed_discovery(self, req):
"""Test DiscoveryFailure behavior.
Failed discovery should not blow up.
"""
req.side_effect = ks_exc.DiscoveryFailure()
self.client._get_resource_provider(self.context, "fake")
# reset the call count to demonstrate that future calls still
# work
req.reset_mock()
self.client._get_resource_provider(self.context, "fake")
self.assertTrue(req.called)
class TestConstructor(test.NoDBTestCase):
@mock.patch('keystoneauth1.loading.load_session_from_conf_options')
@mock.patch('keystoneauth1.loading.load_auth_from_conf_options')
def test_constructor(self, load_auth_mock, load_sess_mock):
client = report.SchedulerReportClient()
load_auth_mock.assert_called_once_with(CONF, 'placement')
load_sess_mock.assert_called_once_with(CONF, 'placement',
auth=load_auth_mock.return_value)
self.assertEqual(['internal', 'public'], client._client.interface)
self.assertEqual({'accept': 'application/json'},
client._client.additional_headers)
@mock.patch('keystoneauth1.loading.load_session_from_conf_options')
@mock.patch('keystoneauth1.loading.load_auth_from_conf_options')
def test_constructor_admin_interface(self, load_auth_mock, load_sess_mock):
self.flags(valid_interfaces='admin', group='placement')
client = report.SchedulerReportClient()
load_auth_mock.assert_called_once_with(CONF, 'placement')
load_sess_mock.assert_called_once_with(CONF, 'placement',
auth=load_auth_mock.return_value)
self.assertEqual(['admin'], client._client.interface)
self.assertEqual({'accept': 'application/json'},
client._client.additional_headers)
class SchedulerReportClientTestCase(test.NoDBTestCase):
def setUp(self):
super(SchedulerReportClientTestCase, self).setUp()
self.context = context.get_admin_context()
self.ks_adap_mock = mock.Mock()
self.compute_node = objects.ComputeNode(
uuid=uuids.compute_node,
hypervisor_hostname='foo',
vcpus=8,
cpu_allocation_ratio=16.0,
memory_mb=1024,
ram_allocation_ratio=1.5,
local_gb=10,
disk_allocation_ratio=1.0,
)
with test.nested(
mock.patch('keystoneauth1.adapter.Adapter',
return_value=self.ks_adap_mock),
mock.patch('keystoneauth1.loading.load_auth_from_conf_options')
):
self.client = report.SchedulerReportClient()
def _init_provider_tree(self, generation_override=None,
resources_override=None):
cn = self.compute_node
resources = resources_override
if resources_override is None:
resources = {
'VCPU': {
'total': cn.vcpus,
'reserved': 0,
'min_unit': 1,
'max_unit': cn.vcpus,
'step_size': 1,
'allocation_ratio': cn.cpu_allocation_ratio,
},
'MEMORY_MB': {
'total': cn.memory_mb,
'reserved': 512,
'min_unit': 1,
'max_unit': cn.memory_mb,
'step_size': 1,
'allocation_ratio': cn.ram_allocation_ratio,
},
'DISK_GB': {
'total': cn.local_gb,
'reserved': 0,
'min_unit': 1,
'max_unit': cn.local_gb,
'step_size': 1,
'allocation_ratio': cn.disk_allocation_ratio,
},
}
generation = generation_override or 1
rp_uuid = self.client._provider_tree.new_root(
cn.hypervisor_hostname,
cn.uuid,
generation=generation,
)
self.client._provider_tree.update_inventory(rp_uuid, resources)
def _validate_provider(self, name_or_uuid, **kwargs):
"""Validates existence and values of a provider in this client's
_provider_tree.
:param name_or_uuid: The name or UUID of the provider to validate.
:param kwargs: Optional keyword arguments of ProviderData attributes
whose values are to be validated.
"""
found = self.client._provider_tree.data(name_or_uuid)
# If kwargs provided, their names indicate ProviderData attributes
for attr, expected in kwargs.items():
try:
self.assertEqual(getattr(found, attr), expected)
except AttributeError:
self.fail("Provider with name or UUID %s doesn't have "
"attribute %s (expected value: %s)" %
(name_or_uuid, attr, expected))
class TestPutAllocations(SchedulerReportClientTestCase):
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.put')
def test_put_allocations(self, mock_put):
mock_put.return_value.status_code = 204
mock_put.return_value.text = "cool"
rp_uuid = mock.sentinel.rp
consumer_uuid = mock.sentinel.consumer
data = {"MEMORY_MB": 1024}
expected_url = "/allocations/%s" % consumer_uuid
resp = self.client.put_allocations(self.context, rp_uuid,
consumer_uuid, data,
mock.sentinel.project_id,
mock.sentinel.user_id)
self.assertTrue(resp)
mock_put.assert_called_once_with(
expected_url, mock.ANY, version='1.8',
global_request_id=self.context.global_id)
@mock.patch.object(report.LOG, 'warning')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.put')
def test_put_allocations_fail(self, mock_put, mock_warn):
mock_put.return_value.status_code = 400
mock_put.return_value.text = "not cool"
rp_uuid = mock.sentinel.rp
consumer_uuid = mock.sentinel.consumer
data = {"MEMORY_MB": 1024}
expected_url = "/allocations/%s" % consumer_uuid
resp = self.client.put_allocations(self.context, rp_uuid,
consumer_uuid, data,
mock.sentinel.project_id,
mock.sentinel.user_id)
self.assertFalse(resp)
mock_put.assert_called_once_with(
expected_url, mock.ANY, version='1.8',
global_request_id=self.context.global_id)
log_msg = mock_warn.call_args[0][0]
self.assertIn("Unable to submit allocation for instance", log_msg)
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.put')
def test_put_allocations_retries_conflict(self, mock_put):
failed = mock.MagicMock()
failed.status_code = 409
failed.text = "concurrently updated"
succeeded = mock.MagicMock()
succeeded.status_code = 204
mock_put.side_effect = (failed, succeeded)
rp_uuid = mock.sentinel.rp
consumer_uuid = mock.sentinel.consumer
data = {"MEMORY_MB": 1024}
expected_url = "/allocations/%s" % consumer_uuid
resp = self.client.put_allocations(self.context, rp_uuid,
consumer_uuid, data,
mock.sentinel.project_id,
mock.sentinel.user_id)
self.assertTrue(resp)
mock_put.assert_has_calls([
mock.call(expected_url, mock.ANY, version='1.8',
global_request_id=self.context.global_id)] * 2)
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.put')
def test_put_allocations_retry_gives_up(self, mock_put):
failed = mock.MagicMock()
failed.status_code = 409
failed.text = "concurrently updated"
mock_put.return_value = failed
rp_uuid = mock.sentinel.rp
consumer_uuid = mock.sentinel.consumer
data = {"MEMORY_MB": 1024}
expected_url = "/allocations/%s" % consumer_uuid
resp = self.client.put_allocations(self.context, rp_uuid,
consumer_uuid, data,
mock.sentinel.project_id,
mock.sentinel.user_id)
self.assertFalse(resp)
mock_put.assert_has_calls([
mock.call(expected_url, mock.ANY, version='1.8',
global_request_id=self.context.global_id)] * 3)
def test_claim_resources_success_with_old_version(self):
get_resp_mock = mock.Mock(status_code=200)
get_resp_mock.json.return_value = {
'allocations': {}, # build instance, not move
}
self.ks_adap_mock.get.return_value = get_resp_mock
resp_mock = mock.Mock(status_code=204)
self.ks_adap_mock.put.return_value = resp_mock
consumer_uuid = uuids.consumer_uuid
alloc_req = {
'allocations': [
{
'resource_provider': {
'uuid': uuids.cn1
},
'resources': {
'VCPU': 1,
'MEMORY_MB': 1024,
}
},
],
}
project_id = uuids.project_id
user_id = uuids.user_id
res = self.client.claim_resources(
self.context, consumer_uuid, alloc_req, project_id, user_id)
expected_url = "/allocations/%s" % consumer_uuid
expected_payload = {
'allocations': {
alloc['resource_provider']['uuid']: {
'resources': alloc['resources']
}
for alloc in alloc_req['allocations']
}
}
expected_payload['project_id'] = project_id
expected_payload['user_id'] = user_id
self.ks_adap_mock.put.assert_called_once_with(
expected_url, microversion='1.12', json=expected_payload,
raise_exc=False,
headers={'X-Openstack-Request-Id': self.context.global_id})
self.assertTrue(res)
def test_claim_resources_success(self):
get_resp_mock = mock.Mock(status_code=200)
get_resp_mock.json.return_value = {
'allocations': {}, # build instance, not move
}
self.ks_adap_mock.get.return_value = get_resp_mock
resp_mock = mock.Mock(status_code=204)
self.ks_adap_mock.put.return_value = resp_mock
consumer_uuid = uuids.consumer_uuid
alloc_req = {
'allocations': {
uuids.cn1: {
'resources': {
'VCPU': 1,
'MEMORY_MB': 1024,
}
},
},
}
project_id = uuids.project_id
user_id = uuids.user_id
res = self.client.claim_resources(self.context, consumer_uuid,
alloc_req, project_id, user_id,
allocation_request_version='1.12')
expected_url = "/allocations/%s" % consumer_uuid
expected_payload = {'allocations': {
rp_uuid: alloc
for rp_uuid, alloc in alloc_req['allocations'].items()}}
expected_payload['project_id'] = project_id
expected_payload['user_id'] = user_id
self.ks_adap_mock.put.assert_called_once_with(
expected_url, microversion='1.12', json=expected_payload,
raise_exc=False,
headers={'X-Openstack-Request-Id': self.context.global_id})
self.assertTrue(res)
def test_claim_resources_success_move_operation_no_shared(self):
"""Tests that when a move operation is detected (existing allocations
for the same instance UUID) that we end up constructing an appropriate
allocation that contains the original resources on the source host
as well as the resources on the destination host.
"""
get_resp_mock = mock.Mock(status_code=200)
get_resp_mock.json.return_value = {
'allocations': {
uuids.source: {
'resource_provider_generation': 42,
'resources': {
'VCPU': 1,
'MEMORY_MB': 1024,
},
},
},
}
self.ks_adap_mock.get.return_value = get_resp_mock
resp_mock = mock.Mock(status_code=204)
self.ks_adap_mock.put.return_value = resp_mock
consumer_uuid = uuids.consumer_uuid
alloc_req = {
'allocations': {
uuids.destination: {
'resources': {
'VCPU': 1,
'MEMORY_MB': 1024
}
},
},
}
project_id = uuids.project_id
user_id = uuids.user_id
res = self.client.claim_resources(self.context, consumer_uuid,
alloc_req, project_id, user_id,
allocation_request_version='1.12')
expected_url = "/allocations/%s" % consumer_uuid
# New allocation should include resources claimed on both the source
# and destination hosts
expected_payload = {
'allocations': {
uuids.source: {
'resources': {
'VCPU': 1,
'MEMORY_MB': 1024
}
},
uuids.destination: {
'resources': {
'VCPU': 1,
'MEMORY_MB': 1024
}
},
},
}
expected_payload['project_id'] = project_id
expected_payload['user_id'] = user_id
self.ks_adap_mock.put.assert_called_once_with(
expected_url, microversion='1.12', json=mock.ANY,
raise_exc=False,
headers={'X-Openstack-Request-Id': self.context.global_id})
# We have to pull the json body from the mock call_args to validate
# it separately otherwise hash seed issues get in the way.
actual_payload = self.ks_adap_mock.put.call_args[1]['json']
self.assertEqual(expected_payload, actual_payload)
self.assertTrue(res)
def test_claim_resources_success_move_operation_with_shared(self):
"""Tests that when a move operation is detected (existing allocations
for the same instance UUID) that we end up constructing an appropriate
allocation that contains the original resources on the source host
as well as the resources on the destination host but that when a shared
storage provider is claimed against in both the original allocation as
well as the new allocation request, we don't double that allocation
resource request up.
"""
get_resp_mock = mock.Mock(status_code=200)
get_resp_mock.json.return_value = {
'allocations': {
uuids.source: {
'resource_provider_generation': 42,
'resources': {
'VCPU': 1,
'MEMORY_MB': 1024,
},
},
uuids.shared_storage: {
'resource_provider_generation': 42,
'resources': {
'DISK_GB': 100,
},
},
},
}
self.ks_adap_mock.get.return_value = get_resp_mock
resp_mock = mock.Mock(status_code=204)
self.ks_adap_mock.put.return_value = resp_mock
consumer_uuid = uuids.consumer_uuid
alloc_req = {
'allocations': {
uuids.destination: {
'resources': {
'VCPU': 1,
'MEMORY_MB': 1024,
}
},
uuids.shared_storage: {
'resources': {
'DISK_GB': 100,
}
},
}
}
project_id = uuids.project_id
user_id = uuids.user_id
res = self.client.claim_resources(self.context, consumer_uuid,
alloc_req, project_id, user_id,
allocation_request_version='1.12')
expected_url = "/allocations/%s" % consumer_uuid
# New allocation should include resources claimed on both the source
# and destination hosts but not have a doubled-up request for the disk
# resources on the shared provider
expected_payload = {
'allocations': {
uuids.source: {
'resources': {
'VCPU': 1,
'MEMORY_MB': 1024
}
},
uuids.shared_storage: {
'resources': {
'DISK_GB': 100
}
},
uuids.destination: {
'resources': {
'VCPU': 1,
'MEMORY_MB': 1024
}
},
},
}
expected_payload['project_id'] = project_id
expected_payload['user_id'] = user_id
self.ks_adap_mock.put.assert_called_once_with(
expected_url, microversion='1.12', json=mock.ANY,
raise_exc=False,
headers={'X-Openstack-Request-Id': self.context.global_id})
# We have to pull the allocations from the json body from the
# mock call_args to validate it separately otherwise hash seed
# issues get in the way.
actual_payload = self.ks_adap_mock.put.call_args[1]['json']
self.assertEqual(expected_payload, actual_payload)
self.assertTrue(res)
def test_claim_resources_success_resize_to_same_host_no_shared(self):
"""Tests that when a resize to the same host operation is detected
(existing allocations for the same instance UUID and same resource
provider) that we end up constructing an appropriate allocation that
contains the original resources on the source host as well as the
resources on the destination host, which in this case are the same.
"""
get_current_allocations_resp_mock = mock.Mock(status_code=200)
get_current_allocations_resp_mock.json.return_value = {
'allocations': {
uuids.same_host: {
'resource_provider_generation': 42,
'resources': {
'VCPU': 1,
'MEMORY_MB': 1024,
'DISK_GB': 20
},
},
},
}
self.ks_adap_mock.get.return_value = get_current_allocations_resp_mock
put_allocations_resp_mock = mock.Mock(status_code=204)
self.ks_adap_mock.put.return_value = put_allocations_resp_mock
consumer_uuid = uuids.consumer_uuid
# This is the resize-up allocation where VCPU, MEMORY_MB and DISK_GB
# are all being increased but on the same host. We also throw a custom
# resource class in the new allocation to make sure it's not lost and
# that we don't have a KeyError when merging the allocations.
alloc_req = {
'allocations': {
uuids.same_host: {
'resources': {
'VCPU': 2,
'MEMORY_MB': 2048,
'DISK_GB': 40,
'CUSTOM_FOO': 1
}
},
},
}
project_id = uuids.project_id
user_id = uuids.user_id
res = self.client.claim_resources(self.context, consumer_uuid,
alloc_req, project_id, user_id,
allocation_request_version='1.12')
expected_url = "/allocations/%s" % consumer_uuid
# New allocation should include doubled resources claimed on the same
# host.
expected_payload = {
'allocations': {
uuids.same_host: {
'resources': {
'VCPU': 3,
'MEMORY_MB': 3072,
'DISK_GB': 60,
'CUSTOM_FOO': 1
}
},
},
}
expected_payload['project_id'] = project_id
expected_payload['user_id'] = user_id
self.ks_adap_mock.put.assert_called_once_with(
expected_url, microversion='1.12', json=mock.ANY, raise_exc=False,
headers={'X-Openstack-Request-Id': self.context.global_id})
# We have to pull the json body from the mock call_args to validate
# it separately otherwise hash seed issues get in the way.
actual_payload = self.ks_adap_mock.put.call_args[1]['json']
self.assertEqual(expected_payload, actual_payload)
self.assertTrue(res)
def test_claim_resources_success_resize_to_same_host_with_shared(self):
"""Tests that when a resize to the same host operation is detected
(existing allocations for the same instance UUID and same resource
provider) that we end up constructing an appropriate allocation that
contains the original resources on the source host as well as the
resources on the destination host, which in this case are the same.
This test adds the fun wrinkle of throwing a shared storage provider
in the mix when doing resize to the same host.
"""
get_current_allocations_resp_mock = mock.Mock(status_code=200)
get_current_allocations_resp_mock.json.return_value = {
'allocations': {
uuids.same_host: {
'resource_provider_generation': 42,
'resources': {
'VCPU': 1,
'MEMORY_MB': 1024
},
},
uuids.shared_storage: {
'resource_provider_generation': 42,
'resources': {
'DISK_GB': 20,
},
},
},
}
self.ks_adap_mock.get.return_value = get_current_allocations_resp_mock
put_allocations_resp_mock = mock.Mock(status_code=204)
self.ks_adap_mock.put.return_value = put_allocations_resp_mock
consumer_uuid = uuids.consumer_uuid
# This is the resize-up allocation where VCPU, MEMORY_MB and DISK_GB
# are all being increased but DISK_GB is on a shared storage provider.
alloc_req = {
'allocations': {
uuids.same_host: {
'resources': {
'VCPU': 2,
'MEMORY_MB': 2048
}
},
uuids.shared_storage: {
'resources': {
'DISK_GB': 40,
}
},
},
}
project_id = uuids.project_id
user_id = uuids.user_id
res = self.client.claim_resources(self.context, consumer_uuid,
alloc_req, project_id, user_id,
allocation_request_version='1.12')
expected_url = "/allocations/%s" % consumer_uuid
# New allocation should include doubled resources claimed on the same
# host.
expected_payload = {
'allocations': {
uuids.same_host: {
'resources': {
'VCPU': 3,
'MEMORY_MB': 3072
}
},
uuids.shared_storage: {
'resources': {
'DISK_GB': 60
}
},
},
}
expected_payload['project_id'] = project_id
expected_payload['user_id'] = user_id
self.ks_adap_mock.put.assert_called_once_with(
expected_url, microversion='1.12', json=mock.ANY, raise_exc=False,
headers={'X-Openstack-Request-Id': self.context.global_id})
# We have to pull the json body from the mock call_args to validate
# it separately otherwise hash seed issues get in the way.
actual_payload = self.ks_adap_mock.put.call_args[1]['json']
self.assertEqual(expected_payload, actual_payload)
self.assertTrue(res)
def test_claim_resources_fail_retry_success(self):
get_resp_mock = mock.Mock(status_code=200)
get_resp_mock.json.return_value = {
'allocations': {}, # build instance, not move
}
self.ks_adap_mock.get.return_value = get_resp_mock
resp_mocks = [
mock.Mock(
status_code=409,
text='Inventory changed while attempting to allocate: '
'Another thread concurrently updated the data. '
'Please retry your update'),
mock.Mock(status_code=204),
]
self.ks_adap_mock.put.side_effect = resp_mocks
consumer_uuid = uuids.consumer_uuid
alloc_req = {
'allocations': {
uuids.cn1: {
'resources': {
'VCPU': 1,
'MEMORY_MB': 1024,
}
},
},
}
project_id = uuids.project_id
user_id = uuids.user_id
res = self.client.claim_resources(self.context, consumer_uuid,
alloc_req, project_id, user_id,
allocation_request_version='1.12')
expected_url = "/allocations/%s" % consumer_uuid
expected_payload = {
'allocations':
{rp_uuid: res
for rp_uuid, res in alloc_req['allocations'].items()}
}
expected_payload['project_id'] = project_id
expected_payload['user_id'] = user_id
# We should have exactly two calls to the placement API that look
# identical since we're retrying the same HTTP request
expected_calls = [
mock.call(expected_url, microversion='1.12', json=expected_payload,
raise_exc=False,
headers={'X-Openstack-Request-Id':
self.context.global_id})] * 2
self.assertEqual(len(expected_calls),
self.ks_adap_mock.put.call_count)
self.ks_adap_mock.put.assert_has_calls(expected_calls)
self.assertTrue(res)
@mock.patch.object(report.LOG, 'warning')
def test_claim_resources_failure(self, mock_log):
get_resp_mock = mock.Mock(status_code=200)
get_resp_mock.json.return_value = {
'allocations': {}, # build instance, not move
}
self.ks_adap_mock.get.return_value = get_resp_mock
resp_mock = mock.Mock(status_code=409, text='not cool')
self.ks_adap_mock.put.return_value = resp_mock
consumer_uuid = uuids.consumer_uuid
alloc_req = {
'allocations': {
uuids.cn1: {
'resources': {
'VCPU': 1,
'MEMORY_MB': 1024,
}
},
},
}
project_id = uuids.project_id
user_id = uuids.user_id
res = self.client.claim_resources(self.context, consumer_uuid,
alloc_req, project_id, user_id,
allocation_request_version='1.12')
expected_url = "/allocations/%s" % consumer_uuid
expected_payload = {
'allocations':
{rp_uuid: res
for rp_uuid, res in alloc_req['allocations'].items()}
}
expected_payload['project_id'] = project_id
expected_payload['user_id'] = user_id
self.ks_adap_mock.put.assert_called_once_with(
expected_url, microversion='1.12', json=expected_payload,
raise_exc=False,
headers={'X-Openstack-Request-Id': self.context.global_id})
self.assertFalse(res)
self.assertTrue(mock_log.called)
def test_remove_provider_from_inst_alloc_no_shared(self):
"""Tests that the method which manipulates an existing doubled-up
allocation for a move operation to remove the source host results in
sending placement the proper payload to PUT
/allocations/{consumer_uuid} call.
"""
get_resp_mock = mock.Mock(status_code=200)
get_resp_mock.json.return_value = {
'allocations': {
uuids.source: {
'resource_provider_generation': 42,
'resources': {
'VCPU': 1,
'MEMORY_MB': 1024,
},
},
uuids.destination: {
'resource_provider_generation': 42,
'resources': {
'VCPU': 1,
'MEMORY_MB': 1024,
},
},
},
}
self.ks_adap_mock.get.return_value = get_resp_mock
resp_mock = mock.Mock(status_code=204)
self.ks_adap_mock.put.return_value = resp_mock
consumer_uuid = uuids.consumer_uuid
project_id = uuids.project_id
user_id = uuids.user_id
res = self.client.remove_provider_from_instance_allocation(
self.context, consumer_uuid, uuids.source, user_id, project_id,
mock.Mock())
expected_url = "/allocations/%s" % consumer_uuid
# New allocations should only include the destination...
expected_payload = {
'allocations': [
{
'resource_provider': {
'uuid': uuids.destination,
},
'resources': {
'VCPU': 1,
'MEMORY_MB': 1024,
},
},
],
}
expected_payload['project_id'] = project_id
expected_payload['user_id'] = user_id
# We have to pull the json body from the mock call_args to validate
# it separately otherwise hash seed issues get in the way.
actual_payload = self.ks_adap_mock.put.call_args[1]['json']
sort_by_uuid = lambda x: x['resource_provider']['uuid']
expected_allocations = sorted(expected_payload['allocations'],
key=sort_by_uuid)
actual_allocations = sorted(actual_payload['allocations'],
key=sort_by_uuid)
self.assertEqual(expected_allocations, actual_allocations)
self.ks_adap_mock.put.assert_called_once_with(
expected_url, microversion='1.10', json=mock.ANY, raise_exc=False,
headers={'X-Openstack-Request-Id': self.context.global_id})
self.assertTrue(res)
def test_remove_provider_from_inst_alloc_with_shared(self):
"""Tests that the method which manipulates an existing doubled-up
allocation with DISK_GB being consumed from a shared storage provider
for a move operation to remove the source host results in sending
placement the proper payload to PUT /allocations/{consumer_uuid}
call.
"""
get_resp_mock = mock.Mock(status_code=200)
get_resp_mock.json.return_value = {
'allocations': {
uuids.source: {
'resource_provider_generation': 42,
'resources': {
'VCPU': 1,
'MEMORY_MB': 1024,
},
},
uuids.shared_storage: {
'resource_provider_generation': 42,
'resources': {
'DISK_GB': 100,
},
},
uuids.destination: {
'resource_provider_generation': 42,
'resources': {
'VCPU': 1,
'MEMORY_MB': 1024,
},
},
},
}
self.ks_adap_mock.get.return_value = get_resp_mock
resp_mock = mock.Mock(status_code=204)
self.ks_adap_mock.put.return_value = resp_mock
consumer_uuid = uuids.consumer_uuid
project_id = uuids.project_id
user_id = uuids.user_id
res = self.client.remove_provider_from_instance_allocation(
self.context, consumer_uuid, uuids.source, user_id, project_id,
mock.Mock())
expected_url = "/allocations/%s" % consumer_uuid
# New allocations should only include the destination...
expected_payload = {
'allocations': [
{
'resource_provider': {
'uuid': uuids.shared_storage,
},
'resources': {
'DISK_GB': 100,
},
},
{
'resource_provider': {
'uuid': uuids.destination,
},
'resources': {
'VCPU': 1,
'MEMORY_MB': 1024,
},
},
],
}
expected_payload['project_id'] = project_id
expected_payload['user_id'] = user_id
# We have to pull the json body from the mock call_args to validate
# it separately otherwise hash seed issues get in the way.
actual_payload = self.ks_adap_mock.put.call_args[1]['json']
sort_by_uuid = lambda x: x['resource_provider']['uuid']
expected_allocations = sorted(expected_payload['allocations'],
key=sort_by_uuid)
actual_allocations = sorted(actual_payload['allocations'],
key=sort_by_uuid)
self.assertEqual(expected_allocations, actual_allocations)
self.ks_adap_mock.put.assert_called_once_with(
expected_url, microversion='1.10', json=mock.ANY, raise_exc=False,
headers={'X-Openstack-Request-Id': self.context.global_id})
self.assertTrue(res)
def test_remove_provider_from_inst_alloc_no_source(self):
"""Tests that if remove_provider_from_instance_allocation() fails to
find any allocations for the source host, it just returns True and
does not attempt to rewrite the allocation for the consumer.
"""
get_resp_mock = mock.Mock(status_code=200)
# Act like the allocations already did not include the source host for
# some reason
get_resp_mock.json.return_value = {
'allocations': {
uuids.shared_storage: {
'resource_provider_generation': 42,
'resources': {
'DISK_GB': 100,
},
},
uuids.destination: {
'resource_provider_generation': 42,
'resources': {
'VCPU': 1,
'MEMORY_MB': 1024,
},
},
},
}
self.ks_adap_mock.get.return_value = get_resp_mock
consumer_uuid = uuids.consumer_uuid
project_id = uuids.project_id
user_id = uuids.user_id
res = self.client.remove_provider_from_instance_allocation(
self.context, consumer_uuid, uuids.source, user_id, project_id,
mock.Mock())
self.ks_adap_mock.get.assert_called()
self.ks_adap_mock.put.assert_not_called()
self.assertTrue(res)
def test_remove_provider_from_inst_alloc_fail_get_allocs(self):
"""Tests that we gracefully exit with False from
remove_provider_from_instance_allocation() if the call to get the
existing allocations fails for some reason
"""
get_resp_mock = mock.Mock(status_code=500)
self.ks_adap_mock.get.return_value = get_resp_mock
consumer_uuid = uuids.consumer_uuid
project_id = uuids.project_id
user_id = uuids.user_id
res = self.client.remove_provider_from_instance_allocation(
self.context, consumer_uuid, uuids.source, user_id, project_id,
mock.Mock())
self.ks_adap_mock.get.assert_called()
self.ks_adap_mock.put.assert_not_called()
self.assertFalse(res)
class TestSetAndClearAllocations(SchedulerReportClientTestCase):
def setUp(self):
super(TestSetAndClearAllocations, self).setUp()
# We want to reuse the mock throughout the class, but with
# different return values.
self.mock_post = mock.patch(
'nova.scheduler.client.report.SchedulerReportClient.post').start()
self.addCleanup(self.mock_post.stop)
self.mock_post.return_value.status_code = 204
self.rp_uuid = mock.sentinel.rp
self.consumer_uuid = mock.sentinel.consumer
self.data = {"MEMORY_MB": 1024}
self.project_id = mock.sentinel.project_id
self.user_id = mock.sentinel.user_id
self.expected_url = '/allocations'
def test_url_microversion(self):
expected_microversion = '1.13'
resp = self.client.set_and_clear_allocations(
self.context, self.rp_uuid, self.consumer_uuid, self.data,
self.project_id, self.user_id)
self.assertTrue(resp)
self.mock_post.assert_called_once_with(
self.expected_url, mock.ANY,
version=expected_microversion,
global_request_id=self.context.global_id)
def test_payload_no_clear(self):
expected_payload = {
self.consumer_uuid: {
'user_id': self.user_id,
'project_id': self.project_id,
'allocations': {
self.rp_uuid: {
'resources': {
'MEMORY_MB': 1024
}
}
}
}
}
resp = self.client.set_and_clear_allocations(
self.context, self.rp_uuid, self.consumer_uuid, self.data,
self.project_id, self.user_id)
self.assertTrue(resp)
args, kwargs = self.mock_post.call_args
payload = args[1]
self.assertEqual(expected_payload, payload)
def test_payload_with_clear(self):
expected_payload = {
self.consumer_uuid: {
'user_id': self.user_id,
'project_id': self.project_id,
'allocations': {
self.rp_uuid: {
'resources': {
'MEMORY_MB': 1024
}
}
}
},
mock.sentinel.migration_uuid: {
'user_id': self.user_id,
'project_id': self.project_id,
'allocations': {}
}
}
resp = self.client.set_and_clear_allocations(
self.context, self.rp_uuid, self.consumer_uuid, self.data,
self.project_id, self.user_id,
consumer_to_clear=mock.sentinel.migration_uuid)
self.assertTrue(resp)
args, kwargs = self.mock_post.call_args
payload = args[1]
self.assertEqual(expected_payload, payload)
@mock.patch('time.sleep')
def test_409_concurrent_update(self, mock_sleep):
self.mock_post.return_value.status_code = 409
self.mock_post.return_value.text = 'concurrently updated'
resp = self.client.set_and_clear_allocations(
self.context, self.rp_uuid, self.consumer_uuid, self.data,
self.project_id, self.user_id,
consumer_to_clear=mock.sentinel.migration_uuid)
self.assertFalse(resp)
# Post was attempted four times.
self.assertEqual(4, self.mock_post.call_count)
@mock.patch('nova.scheduler.client.report.LOG.warning')
def test_not_409_failure(self, mock_log):
error_message = 'placement not there'
self.mock_post.return_value.status_code = 503
self.mock_post.return_value.text = error_message
resp = self.client.set_and_clear_allocations(
self.context, self.rp_uuid, self.consumer_uuid, self.data,
self.project_id, self.user_id,
consumer_to_clear=mock.sentinel.migration_uuid)
self.assertFalse(resp)
args, kwargs = mock_log.call_args
log_message = args[0]
log_args = args[1]
self.assertIn('Unable to post allocations', log_message)
self.assertEqual(error_message, log_args['text'])
class TestProviderOperations(SchedulerReportClientTestCase):
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_create_resource_provider')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_get_inventory')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_get_provider_aggregates')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_get_provider_traits')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_get_sharing_providers')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_get_providers_in_tree')
def test_ensure_resource_provider_get(self, get_rpt_mock, get_shr_mock,
get_trait_mock, get_agg_mock, get_inv_mock, create_rp_mock):
# No resource provider exists in the client's cache, so validate that
# if we get the resource provider from the placement API that we don't
# try to create the resource provider.
get_rpt_mock.return_value = [{
'uuid': uuids.compute_node,
'name': mock.sentinel.name,
'generation': 1,
}]
get_inv_mock.return_value = None
get_agg_mock.return_value = set([uuids.agg1])
get_trait_mock.return_value = set(['CUSTOM_GOLD'])
get_shr_mock.return_value = []
self.client._ensure_resource_provider(self.context, uuids.compute_node)
get_rpt_mock.assert_called_once_with(self.context, uuids.compute_node)
self.assertTrue(self.client._provider_tree.exists(uuids.compute_node))
get_agg_mock.assert_called_once_with(self.context, uuids.compute_node)
self.assertTrue(
self.client._provider_tree.in_aggregates(uuids.compute_node,
[uuids.agg1]))
self.assertFalse(
self.client._provider_tree.in_aggregates(uuids.compute_node,
[uuids.agg2]))
get_trait_mock.assert_called_once_with(self.context,
uuids.compute_node)
self.assertTrue(
self.client._provider_tree.has_traits(uuids.compute_node,
['CUSTOM_GOLD']))
self.assertFalse(
self.client._provider_tree.has_traits(uuids.compute_node,
['CUSTOM_SILVER']))
get_shr_mock.assert_called_once_with(self.context, set([uuids.agg1]))
self.assertTrue(self.client._provider_tree.exists(uuids.compute_node))
self.assertFalse(create_rp_mock.called)
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_create_resource_provider')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_refresh_associations')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_get_providers_in_tree')
def test_ensure_resource_provider_create_fail(self, get_rpt_mock,
refresh_mock, create_rp_mock):
# No resource provider exists in the client's cache, and
# _create_provider raises, indicating there was an error with the
# create call. Ensure we don't populate the resource provider cache
get_rpt_mock.return_value = []
create_rp_mock.side_effect = exception.ResourceProviderCreationFailed(
name=uuids.compute_node)
self.assertRaises(
exception.ResourceProviderCreationFailed,
self.client._ensure_resource_provider, self.context,
uuids.compute_node)
get_rpt_mock.assert_called_once_with(self.context, uuids.compute_node)
create_rp_mock.assert_called_once_with(
self.context, uuids.compute_node, uuids.compute_node,
parent_provider_uuid=None)
self.assertFalse(self.client._provider_tree.exists(uuids.compute_node))
self.assertFalse(refresh_mock.called)
self.assertRaises(
ValueError,
self.client._provider_tree.in_aggregates, uuids.compute_node, [])
self.assertRaises(
ValueError,
self.client._provider_tree.has_traits, uuids.compute_node, [])
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_create_resource_provider', return_value=None)
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_refresh_associations')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_get_providers_in_tree')
def test_ensure_resource_provider_create_no_placement(self, get_rpt_mock,
refresh_mock, create_rp_mock):
# No resource provider exists in the client's cache, and
# @safe_connect on _create_resource_provider returns None because
# Placement isn't running yet. Ensure we don't populate the resource
# provider cache.
get_rpt_mock.return_value = []
self.assertRaises(
exception.ResourceProviderCreationFailed,
self.client._ensure_resource_provider, self.context,
uuids.compute_node)
get_rpt_mock.assert_called_once_with(self.context, uuids.compute_node)
create_rp_mock.assert_called_once_with(
self.context, uuids.compute_node, uuids.compute_node,
parent_provider_uuid=None)
self.assertFalse(self.client._provider_tree.exists(uuids.compute_node))
refresh_mock.assert_not_called()
self.assertRaises(
ValueError,
self.client._provider_tree.in_aggregates, uuids.compute_node, [])
self.assertRaises(
ValueError,
self.client._provider_tree.has_traits, uuids.compute_node, [])
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_create_resource_provider')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_refresh_and_get_inventory')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_refresh_associations')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_get_providers_in_tree')
def test_ensure_resource_provider_create(self, get_rpt_mock,
refresh_inv_mock,
refresh_assoc_mock,
create_rp_mock):
# No resource provider exists in the client's cache and no resource
# provider was returned from the placement API, so verify that in this
# case we try to create the resource provider via the placement API.
get_rpt_mock.return_value = []
create_rp_mock.return_value = {
'uuid': uuids.compute_node,
'name': 'compute-name',
'generation': 1,
}
self.assertEqual(
uuids.compute_node,
self.client._ensure_resource_provider(self.context,
uuids.compute_node))
self._validate_provider(uuids.compute_node, name='compute-name',
generation=1, parent_uuid=None,
aggregates=set(), traits=set())
# We don't refresh for a just-created provider
refresh_inv_mock.assert_not_called()
refresh_assoc_mock.assert_not_called()
get_rpt_mock.assert_called_once_with(self.context, uuids.compute_node)
create_rp_mock.assert_called_once_with(
self.context,
uuids.compute_node,
uuids.compute_node, # name param defaults to UUID if None
parent_provider_uuid=None,
)
self.assertTrue(self.client._provider_tree.exists(uuids.compute_node))
create_rp_mock.reset_mock()
# Validate the path where we specify a name (don't default to the UUID)
self.client._ensure_resource_provider(
self.context, uuids.cn2, 'a-name')
create_rp_mock.assert_called_once_with(
self.context, uuids.cn2, 'a-name', parent_provider_uuid=None)
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_refresh_associations', new=mock.Mock())
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_create_resource_provider')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_get_providers_in_tree')
def test_ensure_resource_provider_tree(self, get_rpt_mock, create_rp_mock):
"""Test _ensure_resource_provider with a tree of providers."""
def _create_resource_provider(context, uuid, name,
parent_provider_uuid=None):
"""Mock side effect for creating the RP with the specified args."""
return {
'uuid': uuid,
'name': name,
'generation': 0,
'parent_provider_uuid': parent_provider_uuid
}
create_rp_mock.side_effect = _create_resource_provider
# Not initially in the placement database, so we have to create it.
get_rpt_mock.return_value = []
# Create the root
root = self.client._ensure_resource_provider(self.context, uuids.root)
self.assertEqual(uuids.root, root)
# Now create a child
child1 = self.client._ensure_resource_provider(
self.context, uuids.child1, name='junior',
parent_provider_uuid=uuids.root)
self.assertEqual(uuids.child1, child1)
# If we re-ensure the child, we get the object from the tree, not a
# newly-created one - i.e. the early .find() works like it should.
self.assertIs(child1,
self.client._ensure_resource_provider(self.context,
uuids.child1))
# Make sure we can create a grandchild
grandchild = self.client._ensure_resource_provider(
self.context, uuids.grandchild,
parent_provider_uuid=uuids.child1)
self.assertEqual(uuids.grandchild, grandchild)
# Now create a second child of the root and make sure it doesn't wind
# up in some crazy wrong place like under child1 or grandchild
child2 = self.client._ensure_resource_provider(
self.context, uuids.child2, parent_provider_uuid=uuids.root)
self.assertEqual(uuids.child2, child2)
# At this point we should get all the providers.
self.assertEqual(
set([uuids.root, uuids.child1, uuids.child2, uuids.grandchild]),
set(self.client._provider_tree.get_provider_uuids()))
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_get_providers_in_tree')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_refresh_and_get_inventory')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_refresh_associations')
def test_ensure_resource_provider_refresh_fetch(self, mock_ref_assoc,
mock_ref_inv, mock_gpit):
"""Make sure refreshes are called with the appropriate UUIDs and flags
when we fetch the provider tree from placement.
"""
tree_uuids = set([uuids.root, uuids.one, uuids.two])
mock_gpit.return_value = [{'uuid': u, 'name': u, 'generation': 42}
for u in tree_uuids]
self.assertEqual(uuids.root,
self.client._ensure_resource_provider(self.context,
uuids.root))
mock_gpit.assert_called_once_with(self.context, uuids.root)
mock_ref_inv.assert_has_calls([mock.call(self.context, uuid)
for uuid in tree_uuids])
mock_ref_assoc.assert_has_calls(
[mock.call(self.context, uuid, generation=42, force=True)
for uuid in tree_uuids])
self.assertEqual(tree_uuids,
set(self.client._provider_tree.get_provider_uuids()))
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_get_providers_in_tree')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_create_resource_provider')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_refresh_associations')
def test_ensure_resource_provider_refresh_create(self, mock_refresh,
mock_create, mock_gpit):
"""Make sure refresh is not called when we create the RP."""
mock_gpit.return_value = []
mock_create.return_value = {'name': 'cn', 'uuid': uuids.cn,
'generation': 42}
self.assertEqual(uuids.root,
self.client._ensure_resource_provider(self.context,
uuids.root))
mock_gpit.assert_called_once_with(self.context, uuids.root)
mock_create.assert_called_once_with(self.context, uuids.root,
uuids.root,
parent_provider_uuid=None)
mock_refresh.assert_not_called()
self.assertEqual([uuids.cn],
self.client._provider_tree.get_provider_uuids())
def test_get_allocation_candidates(self):
resp_mock = mock.Mock(status_code=200)
json_data = {
'allocation_requests': mock.sentinel.alloc_reqs,
'provider_summaries': mock.sentinel.p_sums,
}
resources = scheduler_utils.ResourceRequest.from_extra_specs({
'resources:VCPU': '1',
'resources:MEMORY_MB': '1024',
'trait:HW_CPU_X86_AVX': 'required',
'trait:CUSTOM_TRAIT1': 'required',
'trait:CUSTOM_TRAIT2': 'preferred',
'trait:CUSTOM_TRAIT3': 'forbidden',
'trait:CUSTOM_TRAIT4': 'forbidden',
'resources1:DISK_GB': '30',
'trait1:STORAGE_DISK_SSD': 'required',
'resources2:VGPU': '2',
'trait2:HW_GPU_RESOLUTION_W2560H1600': 'required',
'trait2:HW_GPU_API_VULKAN': 'required',
'resources3:SRIOV_NET_VF': '1',
'resources3:CUSTOM_NET_EGRESS_BYTES_SEC': '125000',
'group_policy': 'isolate',
# These are ignored because misspelled, bad value, etc.
'resources02:CUSTOM_WIDGET': '123',
'trait:HW_NIC_OFFLOAD_LRO': 'preferred',
'group_policy3': 'none',
})
resources.get_request_group(None).member_of = [
('agg1', 'agg2', 'agg3'), ('agg1', 'agg2')]
expected_path = '/allocation_candidates'
expected_query = [
('group_policy', 'isolate'),
('limit', '1000'),
('member_of', 'in:agg1,agg2'),
('member_of', 'in:agg1,agg2,agg3'),
('required', 'CUSTOM_TRAIT1,HW_CPU_X86_AVX,!CUSTOM_TRAIT3,'
'!CUSTOM_TRAIT4'),
('required1', 'STORAGE_DISK_SSD'),
('required2', 'HW_GPU_API_VULKAN,HW_GPU_RESOLUTION_W2560H1600'),
('resources', 'MEMORY_MB:1024,VCPU:1'),
('resources1', 'DISK_GB:30'),
('resources2', 'VGPU:2'),
('resources3', 'CUSTOM_NET_EGRESS_BYTES_SEC:125000,SRIOV_NET_VF:1')
]
resp_mock.json.return_value = json_data
self.ks_adap_mock.get.return_value = resp_mock
alloc_reqs, p_sums, allocation_request_version = (
self.client.get_allocation_candidates(self.context, resources))
url = self.ks_adap_mock.get.call_args[0][0]
split_url = parse.urlsplit(url)
query = parse.parse_qsl(split_url.query)
self.assertEqual(expected_path, split_url.path)
self.assertEqual(expected_query, query)
expected_url = '/allocation_candidates?%s' % parse.urlencode(
expected_query)
self.ks_adap_mock.get.assert_called_once_with(
expected_url, raise_exc=False, microversion='1.25',
headers={'X-Openstack-Request-Id': self.context.global_id})
self.assertEqual(mock.sentinel.alloc_reqs, alloc_reqs)
self.assertEqual(mock.sentinel.p_sums, p_sums)
def test_get_ac_no_trait_bogus_group_policy_custom_limit(self):
self.flags(max_placement_results=42, group='scheduler')
resp_mock = mock.Mock(status_code=200)
json_data = {
'allocation_requests': mock.sentinel.alloc_reqs,
'provider_summaries': mock.sentinel.p_sums,
}
resources = scheduler_utils.ResourceRequest.from_extra_specs({
'resources:VCPU': '1',
'resources:MEMORY_MB': '1024',
'resources1:DISK_GB': '30',
'group_policy': 'bogus',
})
expected_path = '/allocation_candidates'
expected_query = [
('limit', '42'),
('resources', 'MEMORY_MB:1024,VCPU:1'),
('resources1', 'DISK_GB:30'),
]
resp_mock.json.return_value = json_data
self.ks_adap_mock.get.return_value = resp_mock
alloc_reqs, p_sums, allocation_request_version = (
self.client.get_allocation_candidates(self.context, resources))
url = self.ks_adap_mock.get.call_args[0][0]
split_url = parse.urlsplit(url)
query = parse.parse_qsl(split_url.query)
self.assertEqual(expected_path, split_url.path)
self.assertEqual(expected_query, query)
expected_url = '/allocation_candidates?%s' % parse.urlencode(
expected_query)
self.assertEqual(mock.sentinel.alloc_reqs, alloc_reqs)
self.ks_adap_mock.get.assert_called_once_with(
expected_url, raise_exc=False, microversion='1.25',
headers={'X-Openstack-Request-Id': self.context.global_id})
self.assertEqual(mock.sentinel.p_sums, p_sums)
def test_get_allocation_candidates_not_found(self):
# Ensure _get_resource_provider() just returns None when the placement
# API doesn't find a resource provider matching a UUID
resp_mock = mock.Mock(status_code=404)
self.ks_adap_mock.get.return_value = resp_mock
expected_path = '/allocation_candidates'
expected_query = {'resources': ['MEMORY_MB:1024'],
'limit': ['100']}
# Make sure we're also honoring the configured limit
self.flags(max_placement_results=100, group='scheduler')
resources = scheduler_utils.ResourceRequest.from_extra_specs(
{'resources:MEMORY_MB': '1024'})
res = self.client.get_allocation_candidates(self.context, resources)
self.ks_adap_mock.get.assert_called_once_with(
mock.ANY, raise_exc=False, microversion='1.25',
headers={'X-Openstack-Request-Id': self.context.global_id})
url = self.ks_adap_mock.get.call_args[0][0]
split_url = parse.urlsplit(url)
query = parse.parse_qs(split_url.query)
self.assertEqual(expected_path, split_url.path)
self.assertEqual(expected_query, query)
self.assertIsNone(res[0])
def test_get_resource_provider_found(self):
# Ensure _get_resource_provider() returns a dict of resource provider
# if it finds a resource provider record from the placement API
uuid = uuids.compute_node
resp_mock = mock.Mock(status_code=200)
json_data = {
'uuid': uuid,
'name': uuid,
'generation': 42,
'parent_provider_uuid': None,
}
resp_mock.json.return_value = json_data
self.ks_adap_mock.get.return_value = resp_mock
result = self.client._get_resource_provider(self.context, uuid)
expected_provider_dict = dict(
uuid=uuid,
name=uuid,
generation=42,
parent_provider_uuid=None,
)
expected_url = '/resource_providers/' + uuid
self.ks_adap_mock.get.assert_called_once_with(
expected_url, raise_exc=False, microversion='1.14',
headers={'X-Openstack-Request-Id': self.context.global_id})
self.assertEqual(expected_provider_dict, result)
def test_get_resource_provider_not_found(self):
# Ensure _get_resource_provider() just returns None when the placement
# API doesn't find a resource provider matching a UUID
resp_mock = mock.Mock(status_code=404)
self.ks_adap_mock.get.return_value = resp_mock
uuid = uuids.compute_node
result = self.client._get_resource_provider(self.context, uuid)
expected_url = '/resource_providers/' + uuid
self.ks_adap_mock.get.assert_called_once_with(
expected_url, raise_exc=False, microversion='1.14',
headers={'X-Openstack-Request-Id': self.context.global_id})
self.assertIsNone(result)
@mock.patch.object(report.LOG, 'error')
def test_get_resource_provider_error(self, logging_mock):
# Ensure _get_resource_provider() sets the error flag when trying to
# communicate with the placement API and not getting an error we can
# deal with
resp_mock = mock.Mock(status_code=503)
self.ks_adap_mock.get.return_value = resp_mock
self.ks_adap_mock.get.return_value.headers = {
'x-openstack-request-id': uuids.request_id}
uuid = uuids.compute_node
self.assertRaises(
exception.ResourceProviderRetrievalFailed,
self.client._get_resource_provider, self.context, uuid)
expected_url = '/resource_providers/' + uuid
self.ks_adap_mock.get.assert_called_once_with(
expected_url, raise_exc=False, microversion='1.14',
headers={'X-Openstack-Request-Id': self.context.global_id})
# A 503 Service Unavailable should trigger an error log that
# includes the placement request id and return None
# from _get_resource_provider()
self.assertTrue(logging_mock.called)
self.assertEqual(uuids.request_id,
logging_mock.call_args[0][1]['placement_req_id'])
def test_get_sharing_providers(self):
resp_mock = mock.Mock(status_code=200)
rpjson = [
{
'uuid': uuids.sharing1,
'name': 'bandwidth_provider',
'generation': 42,
'parent_provider_uuid': None,
'root_provider_uuid': None,
'links': [],
},
{
'uuid': uuids.sharing2,
'name': 'storage_provider',
'generation': 42,
'parent_provider_uuid': None,
'root_provider_uuid': None,
'links': [],
},
]
resp_mock.json.return_value = {'resource_providers': rpjson}
self.ks_adap_mock.get.return_value = resp_mock
result = self.client._get_sharing_providers(
self.context, [uuids.agg1, uuids.agg2])
expected_url = ('/resource_providers?member_of=in:' +
','.join((uuids.agg1, uuids.agg2)) +
'&required=MISC_SHARES_VIA_AGGREGATE')
self.ks_adap_mock.get.assert_called_once_with(
expected_url, microversion='1.18', raise_exc=False,
headers={'X-Openstack-Request-Id': self.context.global_id})
self.assertEqual(rpjson, result)
def test_get_sharing_providers_emptylist(self):
self.assertEqual(
[], self.client._get_sharing_providers(self.context, []))
self.ks_adap_mock.get.assert_not_called()
@mock.patch.object(report.LOG, 'error')
def test_get_sharing_providers_error(self, logging_mock):
# Ensure _get_sharing_providers() logs an error and raises if the
# placement API call doesn't respond 200
resp_mock = mock.Mock(status_code=503)
self.ks_adap_mock.get.return_value = resp_mock
self.ks_adap_mock.get.return_value.headers = {
'x-openstack-request-id': uuids.request_id}
uuid = uuids.agg
self.assertRaises(exception.ResourceProviderRetrievalFailed,
self.client._get_sharing_providers,
self.context, [uuid])
expected_url = ('/resource_providers?member_of=in:' + uuid +
'&required=MISC_SHARES_VIA_AGGREGATE')
self.ks_adap_mock.get.assert_called_once_with(
expected_url, raise_exc=False, microversion='1.18',
headers={'X-Openstack-Request-Id': self.context.global_id})
# A 503 Service Unavailable should trigger an error log that
# includes the placement request id
self.assertTrue(logging_mock.called)
self.assertEqual(uuids.request_id,
logging_mock.call_args[0][1]['placement_req_id'])
def test_get_providers_in_tree(self):
# Ensure _get_providers_in_tree() returns a list of resource
# provider dicts if it finds a resource provider record from the
# placement API
root = uuids.compute_node
child = uuids.child
resp_mock = mock.Mock(status_code=200)
rpjson = [
{
'uuid': root,
'name': 'daddy', 'generation': 42,
'parent_provider_uuid': None,
},
{
'uuid': child,
'name': 'junior',
'generation': 42,
'parent_provider_uuid': root,
},
]
resp_mock.json.return_value = {'resource_providers': rpjson}
self.ks_adap_mock.get.return_value = resp_mock
result = self.client._get_providers_in_tree(self.context, root)
expected_url = '/resource_providers?in_tree=' + root
self.ks_adap_mock.get.assert_called_once_with(
expected_url, raise_exc=False, microversion='1.14',
headers={'X-Openstack-Request-Id': self.context.global_id})
self.assertEqual(rpjson, result)
@mock.patch.object(report.LOG, 'error')
def test_get_providers_in_tree_error(self, logging_mock):
# Ensure _get_providers_in_tree() logs an error and raises if the
# placement API call doesn't respond 200
resp_mock = mock.Mock(status_code=503)
self.ks_adap_mock.get.return_value = resp_mock
self.ks_adap_mock.get.return_value.headers = {
'x-openstack-request-id': 'req-' + uuids.request_id}
uuid = uuids.compute_node
self.assertRaises(exception.ResourceProviderRetrievalFailed,
self.client._get_providers_in_tree, self.context,
uuid)
expected_url = '/resource_providers?in_tree=' + uuid
self.ks_adap_mock.get.assert_called_once_with(
expected_url, raise_exc=False, microversion='1.14',
headers={'X-Openstack-Request-Id': self.context.global_id})
# A 503 Service Unavailable should trigger an error log that includes
# the placement request id
self.assertTrue(logging_mock.called)
self.assertEqual('req-' + uuids.request_id,
logging_mock.call_args[0][1]['placement_req_id'])
def test_create_resource_provider(self):
"""Test that _create_resource_provider() sends a dict of resource
provider information without a parent provider UUID.
"""
uuid = uuids.compute_node
name = 'computehost'
resp_mock = mock.Mock(status_code=200)
self.ks_adap_mock.post.return_value = resp_mock
self.assertEqual(
resp_mock.json.return_value,
self.client._create_resource_provider(self.context, uuid, name))
expected_payload = {
'uuid': uuid,
'name': name,
}
expected_url = '/resource_providers'
self.ks_adap_mock.post.assert_called_once_with(
expected_url, json=expected_payload, raise_exc=False,
microversion='1.20',
headers={'X-Openstack-Request-Id': self.context.global_id})
def test_create_resource_provider_with_parent(self):
"""Test that when specifying a parent provider UUID, that the
parent_provider_uuid part of the payload is properly specified.
"""
parent_uuid = uuids.parent
uuid = uuids.compute_node
name = 'computehost'
resp_mock = mock.Mock(status_code=200)
self.ks_adap_mock.post.return_value = resp_mock
self.assertEqual(
resp_mock.json.return_value,
self.client._create_resource_provider(
self.context,
uuid,
name,
parent_provider_uuid=parent_uuid,
)
)
expected_payload = {
'uuid': uuid,
'name': name,
'parent_provider_uuid': parent_uuid,
}
expected_url = '/resource_providers'
self.ks_adap_mock.post.assert_called_once_with(
expected_url, json=expected_payload, raise_exc=False,
microversion='1.20',
headers={'X-Openstack-Request-Id': self.context.global_id})
@mock.patch.object(report.LOG, 'info')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_get_resource_provider')
def test_create_resource_provider_concurrent_create(self, get_rp_mock,
logging_mock):
# Ensure _create_resource_provider() returns a dict of resource
# provider gotten from _get_resource_provider() if the call to create
# the resource provider in the placement API returned a 409 Conflict,
# indicating another thread concurrently created the resource provider
# record.
uuid = uuids.compute_node
name = 'computehost'
self.ks_adap_mock.post.return_value = fake_requests.FakeResponse(
409, content='not a name conflict',
headers={'x-openstack-request-id': uuids.request_id})
get_rp_mock.return_value = mock.sentinel.get_rp
result = self.client._create_resource_provider(self.context, uuid,
name)
expected_payload = {
'uuid': uuid,
'name': name,
}
expected_url = '/resource_providers'
self.ks_adap_mock.post.assert_called_once_with(
expected_url, json=expected_payload, raise_exc=False,
microversion='1.20',
headers={'X-Openstack-Request-Id': self.context.global_id})
self.assertEqual(mock.sentinel.get_rp, result)
# The 409 response will produce a message to the info log.
self.assertTrue(logging_mock.called)
self.assertEqual(uuids.request_id,
logging_mock.call_args[0][1]['placement_req_id'])
def test_create_resource_provider_name_conflict(self):
# When the API call to create the resource provider fails 409 with a
# name conflict, we raise an exception.
self.ks_adap_mock.post.return_value = fake_requests.FakeResponse(
409, content='<stuff>Conflicting resource provider name: foo '
'already exists.</stuff>')
self.assertRaises(
exception.ResourceProviderCreationFailed,
self.client._create_resource_provider, self.context,
uuids.compute_node, 'foo')
@mock.patch.object(report.LOG, 'error')
def test_create_resource_provider_error(self, logging_mock):
# Ensure _create_resource_provider() sets the error flag when trying to
# communicate with the placement API and not getting an error we can
# deal with
uuid = uuids.compute_node
name = 'computehost'
self.ks_adap_mock.post.return_value = fake_requests.FakeResponse(
503, headers={'x-openstack-request-id': uuids.request_id})
self.assertRaises(
exception.ResourceProviderCreationFailed,
self.client._create_resource_provider, self.context, uuid, name)
expected_payload = {
'uuid': uuid,
'name': name,
}
expected_url = '/resource_providers'
self.ks_adap_mock.post.assert_called_once_with(
expected_url, json=expected_payload, raise_exc=False,
microversion='1.20',
headers={'X-Openstack-Request-Id': self.context.global_id})
# A 503 Service Unavailable should log an error that
# includes the placement request id and
# _create_resource_provider() should return None
self.assertTrue(logging_mock.called)
self.assertEqual(uuids.request_id,
logging_mock.call_args[0][1]['placement_req_id'])
def test_put_empty(self):
# A simple put with an empty (not None) payload should send the empty
# payload through.
# Bug #1744786
url = '/resource_providers/%s/aggregates' % uuids.foo
self.client.put(url, [])
self.ks_adap_mock.put.assert_called_once_with(
url, json=[], raise_exc=False, microversion=None, headers={})
def test_delete_provider(self):
delete_mock = fake_requests.FakeResponse(None)
self.ks_adap_mock.delete.return_value = delete_mock
for status_code in (204, 404):
delete_mock.status_code = status_code
# Seed the caches
self.client._provider_tree.new_root('compute', uuids.root,
generation=0)
self.client._association_refresh_time[uuids.root] = 1234
self.client._delete_provider(uuids.root, global_request_id='gri')
self.ks_adap_mock.delete.assert_called_once_with(
'/resource_providers/' + uuids.root,
headers={'X-Openstack-Request-Id': 'gri'}, microversion=None,
raise_exc=False)
self.assertFalse(self.client._provider_tree.exists(uuids.root))
self.assertNotIn(uuids.root, self.client._association_refresh_time)
self.ks_adap_mock.delete.reset_mock()
def test_delete_provider_fail(self):
delete_mock = fake_requests.FakeResponse(None)
self.ks_adap_mock.delete.return_value = delete_mock
resp_exc_map = {409: exception.ResourceProviderInUse,
503: exception.ResourceProviderDeletionFailed}
for status_code, exc in resp_exc_map.items():
delete_mock.status_code = status_code
self.assertRaises(exc, self.client._delete_provider, uuids.root)
self.ks_adap_mock.delete.assert_called_once_with(
'/resource_providers/' + uuids.root, microversion=None,
headers={}, raise_exc=False)
self.ks_adap_mock.delete.reset_mock()
def test_set_aggregates_for_provider(self):
aggs = [uuids.agg1, uuids.agg2]
resp_mock = mock.Mock(status_code=200)
resp_mock.json.return_value = {
'aggregates': aggs,
}
self.ks_adap_mock.put.return_value = resp_mock
# Prime the provider tree cache
self.client._provider_tree.new_root('rp', uuids.rp, generation=0)
self.assertEqual(set(),
self.client._provider_tree.data(uuids.rp).aggregates)
self.client.set_aggregates_for_provider(self.context, uuids.rp, aggs)
self.ks_adap_mock.put.assert_called_once_with(
'/resource_providers/%s/aggregates' % uuids.rp, json=aggs,
raise_exc=False, microversion='1.1',
headers={'X-Openstack-Request-Id': self.context.global_id})
# Cache was updated
self.assertEqual(set(aggs),
self.client._provider_tree.data(uuids.rp).aggregates)
def test_set_aggregates_for_provider_fail(self):
self.ks_adap_mock.put.return_value = mock.Mock(status_code=503)
# Prime the provider tree cache
self.client._provider_tree.new_root('rp', uuids.rp, generation=0)
self.assertRaises(
exception.ResourceProviderUpdateFailed,
self.client.set_aggregates_for_provider,
self.context, uuids.rp, [uuids.agg])
# The cache wasn't updated
self.assertEqual(set(),
self.client._provider_tree.data(uuids.rp).aggregates)
class TestAggregates(SchedulerReportClientTestCase):
def test_get_provider_aggregates_found(self):
uuid = uuids.compute_node
resp_mock = mock.Mock(status_code=200)
aggs = [
uuids.agg1,
uuids.agg2,
]
resp_mock.json.return_value = {'aggregates': aggs}
self.ks_adap_mock.get.return_value = resp_mock
result = self.client._get_provider_aggregates(self.context, uuid)
expected_url = '/resource_providers/' + uuid + '/aggregates'
self.ks_adap_mock.get.assert_called_once_with(
expected_url, raise_exc=False, microversion='1.1',
headers={'X-Openstack-Request-Id': self.context.global_id})
self.assertEqual(set(aggs), result)
@mock.patch.object(report.LOG, 'error')
def test_get_provider_aggregates_error(self, log_mock):
"""Test that when the placement API returns any error when looking up a
provider's aggregates, we raise an exception.
"""
uuid = uuids.compute_node
resp_mock = mock.Mock(headers={
'x-openstack-request-id': uuids.request_id})
self.ks_adap_mock.get.return_value = resp_mock
for status_code in (400, 404, 503):
resp_mock.status_code = status_code
self.assertRaises(
exception.ResourceProviderAggregateRetrievalFailed,
self.client._get_provider_aggregates, self.context, uuid)
expected_url = '/resource_providers/' + uuid + '/aggregates'
self.ks_adap_mock.get.assert_called_once_with(
expected_url, raise_exc=False, microversion='1.1',
headers={'X-Openstack-Request-Id': self.context.global_id})
self.assertTrue(log_mock.called)
self.assertEqual(uuids.request_id,
log_mock.call_args[0][1]['placement_req_id'])
self.ks_adap_mock.get.reset_mock()
log_mock.reset_mock()
class TestTraits(SchedulerReportClientTestCase):
trait_api_kwargs = {'raise_exc': False, 'microversion': '1.6'}
def test_get_provider_traits_found(self):
uuid = uuids.compute_node
resp_mock = mock.Mock(status_code=200)
traits = [
'CUSTOM_GOLD',
'CUSTOM_SILVER',
]
resp_mock.json.return_value = {'traits': traits}
self.ks_adap_mock.get.return_value = resp_mock
result = self.client._get_provider_traits(self.context, uuid)
expected_url = '/resource_providers/' + uuid + '/traits'
self.ks_adap_mock.get.assert_called_once_with(
expected_url,
headers={'X-Openstack-Request-Id': self.context.global_id},
**self.trait_api_kwargs)
self.assertEqual(set(traits), result)
@mock.patch.object(report.LOG, 'error')
def test_get_provider_traits_error(self, log_mock):
"""Test that when the placement API returns any error when looking up a
provider's traits, we raise an exception.
"""
uuid = uuids.compute_node
resp_mock = mock.Mock(headers={
'x-openstack-request-id': uuids.request_id})
self.ks_adap_mock.get.return_value = resp_mock
for status_code in (400, 404, 503):
resp_mock.status_code = status_code
self.assertRaises(
exception.ResourceProviderTraitRetrievalFailed,
self.client._get_provider_traits, self.context, uuid)
expected_url = '/resource_providers/' + uuid + '/traits'
self.ks_adap_mock.get.assert_called_once_with(
expected_url,
headers={'X-Openstack-Request-Id': self.context.global_id},
**self.trait_api_kwargs)
self.assertTrue(log_mock.called)
self.assertEqual(uuids.request_id,
log_mock.call_args[0][1]['placement_req_id'])
self.ks_adap_mock.get.reset_mock()
log_mock.reset_mock()
def test_ensure_traits(self):
"""Successful paths, various permutations of traits existing or needing
to be created.
"""
standard_traits = ['HW_NIC_OFFLOAD_UCS', 'HW_NIC_OFFLOAD_RDMA']
custom_traits = ['CUSTOM_GOLD', 'CUSTOM_SILVER']
all_traits = standard_traits + custom_traits
get_mock = mock.Mock(status_code=200)
self.ks_adap_mock.get.return_value = get_mock
# Request all traits; custom traits need to be created
get_mock.json.return_value = {'traits': standard_traits}
self.client._ensure_traits(self.context, all_traits)
self.ks_adap_mock.get.assert_called_once_with(
'/traits?name=in:' + ','.join(all_traits),
headers={'X-Openstack-Request-Id': self.context.global_id},
**self.trait_api_kwargs)
self.ks_adap_mock.put.assert_has_calls(
[mock.call('/traits/' + trait,
headers={'X-Openstack-Request-Id': self.context.global_id},
**self.trait_api_kwargs)
for trait in custom_traits], any_order=True)
self.ks_adap_mock.reset_mock()
# Request standard traits; no traits need to be created
get_mock.json.return_value = {'traits': standard_traits}
self.client._ensure_traits(self.context, standard_traits)
self.ks_adap_mock.get.assert_called_once_with(
'/traits?name=in:' + ','.join(standard_traits),
headers={'X-Openstack-Request-Id': self.context.global_id},
**self.trait_api_kwargs)
self.ks_adap_mock.put.assert_not_called()
self.ks_adap_mock.reset_mock()
# Request no traits - short circuit
self.client._ensure_traits(self.context, None)
self.client._ensure_traits(self.context, [])
self.ks_adap_mock.get.assert_not_called()
self.ks_adap_mock.put.assert_not_called()
def test_ensure_traits_fail_retrieval(self):
self.ks_adap_mock.get.return_value = mock.Mock(status_code=400)
self.assertRaises(exception.TraitRetrievalFailed,
self.client._ensure_traits,
self.context, ['FOO'])
self.ks_adap_mock.get.assert_called_once_with(
'/traits?name=in:FOO',
headers={'X-Openstack-Request-Id': self.context.global_id},
**self.trait_api_kwargs)
self.ks_adap_mock.put.assert_not_called()
def test_ensure_traits_fail_creation(self):
get_mock = mock.Mock(status_code=200)
get_mock.json.return_value = {'traits': []}
self.ks_adap_mock.get.return_value = get_mock
self.ks_adap_mock.put.return_value = fake_requests.FakeResponse(400)
self.assertRaises(exception.TraitCreationFailed,
self.client._ensure_traits,
self.context, ['FOO'])
self.ks_adap_mock.get.assert_called_once_with(
'/traits?name=in:FOO',
headers={'X-Openstack-Request-Id': self.context.global_id},
**self.trait_api_kwargs)
self.ks_adap_mock.put.assert_called_once_with(
'/traits/FOO',
headers={'X-Openstack-Request-Id': self.context.global_id},
**self.trait_api_kwargs)
def test_set_traits_for_provider(self):
traits = ['HW_NIC_OFFLOAD_UCS', 'HW_NIC_OFFLOAD_RDMA']
# Make _ensure_traits succeed without PUTting
get_mock = mock.Mock(status_code=200)
get_mock.json.return_value = {'traits': traits}
self.ks_adap_mock.get.return_value = get_mock
# Prime the provider tree cache
self.client._provider_tree.new_root('rp', uuids.rp, generation=0)
# Mock the /rp/{u}/traits PUT to succeed
put_mock = mock.Mock(status_code=200)
put_mock.json.return_value = {'traits': traits,
'resource_provider_generation': 1}
self.ks_adap_mock.put.return_value = put_mock
# Invoke
self.client.set_traits_for_provider(self.context, uuids.rp, traits)
# Verify API calls
self.ks_adap_mock.get.assert_called_once_with(
'/traits?name=in:' + ','.join(traits),
headers={'X-Openstack-Request-Id': self.context.global_id},
**self.trait_api_kwargs)
self.ks_adap_mock.put.assert_called_once_with(
'/resource_providers/%s/traits' % uuids.rp,
json={'traits': traits, 'resource_provider_generation': 0},
headers={'X-Openstack-Request-Id': self.context.global_id},
**self.trait_api_kwargs)
# And ensure the provider tree cache was updated appropriately
self.assertFalse(
self.client._provider_tree.have_traits_changed(uuids.rp, traits))
# Validate the generation
self.assertEqual(
1, self.client._provider_tree.data(uuids.rp).generation)
def test_set_traits_for_provider_fail(self):
traits = ['HW_NIC_OFFLOAD_UCS', 'HW_NIC_OFFLOAD_RDMA']
get_mock = mock.Mock()
self.ks_adap_mock.get.return_value = get_mock
# Prime the provider tree cache
self.client._provider_tree.new_root('rp', uuids.rp, generation=0)
# _ensure_traits exception bubbles up
get_mock.status_code = 400
self.assertRaises(
exception.TraitRetrievalFailed,
self.client.set_traits_for_provider,
self.context, uuids.rp, traits)
self.ks_adap_mock.put.assert_not_called()
get_mock.status_code = 200
get_mock.json.return_value = {'traits': traits}
# Conflict
self.ks_adap_mock.put.return_value = mock.Mock(status_code=409)
self.assertRaises(
exception.ResourceProviderUpdateConflict,
self.client.set_traits_for_provider,
self.context, uuids.rp, traits)
# Other error
self.ks_adap_mock.put.return_value = mock.Mock(status_code=503)
self.assertRaises(
exception.ResourceProviderUpdateFailed,
self.client.set_traits_for_provider,
self.context, uuids.rp, traits)
class TestAssociations(SchedulerReportClientTestCase):
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_get_provider_aggregates')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_get_provider_traits')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_get_sharing_providers')
def test_refresh_associations_no_last(self, mock_shr_get, mock_trait_get,
mock_agg_get):
"""Test that associations are refreshed when stale."""
uuid = uuids.compute_node
# Seed the provider tree so _refresh_associations finds the provider
self.client._provider_tree.new_root('compute', uuid, generation=1)
mock_agg_get.return_value = set([uuids.agg1])
mock_trait_get.return_value = set(['CUSTOM_GOLD'])
self.client._refresh_associations(self.context, uuid)
mock_agg_get.assert_called_once_with(self.context, uuid)
mock_trait_get.assert_called_once_with(self.context, uuid)
mock_shr_get.assert_called_once_with(
self.context, mock_agg_get.return_value)
self.assertIn(uuid, self.client._association_refresh_time)
self.assertTrue(
self.client._provider_tree.in_aggregates(uuid, [uuids.agg1]))
self.assertFalse(
self.client._provider_tree.in_aggregates(uuid, [uuids.agg2]))
self.assertTrue(
self.client._provider_tree.has_traits(uuid, ['CUSTOM_GOLD']))
self.assertFalse(
self.client._provider_tree.has_traits(uuid, ['CUSTOM_SILVER']))
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_get_provider_aggregates')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_get_provider_traits')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_get_sharing_providers')
def test_refresh_associations_no_refresh_sharing(self, mock_shr_get,
mock_trait_get,
mock_agg_get):
"""Test refresh_sharing=False."""
uuid = uuids.compute_node
# Seed the provider tree so _refresh_associations finds the provider
self.client._provider_tree.new_root('compute', uuid, generation=1)
mock_agg_get.return_value = set([uuids.agg1])
mock_trait_get.return_value = set(['CUSTOM_GOLD'])
self.client._refresh_associations(self.context, uuid,
refresh_sharing=False)
mock_agg_get.assert_called_once_with(self.context, uuid)
mock_trait_get.assert_called_once_with(self.context, uuid)
mock_shr_get.assert_not_called()
self.assertIn(uuid, self.client._association_refresh_time)
self.assertTrue(
self.client._provider_tree.in_aggregates(uuid, [uuids.agg1]))
self.assertFalse(
self.client._provider_tree.in_aggregates(uuid, [uuids.agg2]))
self.assertTrue(
self.client._provider_tree.has_traits(uuid, ['CUSTOM_GOLD']))
self.assertFalse(
self.client._provider_tree.has_traits(uuid, ['CUSTOM_SILVER']))
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_get_provider_aggregates')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_get_provider_traits')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_get_sharing_providers')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_associations_stale')
def test_refresh_associations_not_stale(self, mock_stale, mock_shr_get,
mock_trait_get, mock_agg_get):
"""Test that refresh associations is not called when the map is
not stale.
"""
mock_stale.return_value = False
uuid = uuids.compute_node
self.client._refresh_associations(self.context, uuid)
mock_agg_get.assert_not_called()
mock_trait_get.assert_not_called()
mock_shr_get.assert_not_called()
self.assertFalse(self.client._association_refresh_time)
@mock.patch.object(report.LOG, 'debug')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_get_provider_aggregates')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_get_provider_traits')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_get_sharing_providers')
def test_refresh_associations_time(self, mock_shr_get, mock_trait_get,
mock_agg_get, log_mock):
"""Test that refresh associations is called when the map is stale."""
uuid = uuids.compute_node
# Seed the provider tree so _refresh_associations finds the provider
self.client._provider_tree.new_root('compute', uuid, generation=1)
mock_agg_get.return_value = set([])
mock_trait_get.return_value = set([])
mock_shr_get.return_value = []
# Called a first time because association_refresh_time is empty.
now = time.time()
self.client._refresh_associations(self.context, uuid)
mock_agg_get.assert_called_once_with(self.context, uuid)
mock_trait_get.assert_called_once_with(self.context, uuid)
mock_shr_get.assert_called_once_with(self.context, set())
log_mock.assert_has_calls([
mock.call('Refreshing aggregate associations for resource '
'provider %s, aggregates: %s', uuid, 'None'),
mock.call('Refreshing trait associations for resource '
'provider %s, traits: %s', uuid, 'None')
])
self.assertIn(uuid, self.client._association_refresh_time)
# Clear call count.
mock_agg_get.reset_mock()
mock_trait_get.reset_mock()
mock_shr_get.reset_mock()
with mock.patch('time.time') as mock_future:
# Not called a second time because not enough time has passed.
mock_future.return_value = (now +
CONF.compute.resource_provider_association_refresh / 2)
self.client._refresh_associations(self.context, uuid)
mock_agg_get.assert_not_called()
mock_trait_get.assert_not_called()
mock_shr_get.assert_not_called()
# Called because time has passed.
mock_future.return_value = (now +
CONF.compute.resource_provider_association_refresh + 1)
self.client._refresh_associations(self.context, uuid)
mock_agg_get.assert_called_once_with(self.context, uuid)
mock_trait_get.assert_called_once_with(self.context, uuid)
mock_shr_get.assert_called_once_with(self.context, set())
class TestComputeNodeToInventoryDict(test.NoDBTestCase):
def test_compute_node_inventory(self):
uuid = uuids.compute_node
name = 'computehost'
compute_node = objects.ComputeNode(uuid=uuid,
hypervisor_hostname=name,
vcpus=2,
cpu_allocation_ratio=16.0,
memory_mb=1024,
ram_allocation_ratio=1.5,
local_gb=10,
disk_allocation_ratio=1.0)
self.flags(reserved_host_memory_mb=1000)
self.flags(reserved_host_disk_mb=200)
self.flags(reserved_host_cpus=1)
result = report._compute_node_to_inventory_dict(compute_node)
expected = {
'VCPU': {
'total': compute_node.vcpus,
'reserved': CONF.reserved_host_cpus,
'min_unit': 1,
'max_unit': compute_node.vcpus,
'step_size': 1,
'allocation_ratio': compute_node.cpu_allocation_ratio,
},
'MEMORY_MB': {
'total': compute_node.memory_mb,
'reserved': CONF.reserved_host_memory_mb,
'min_unit': 1,
'max_unit': compute_node.memory_mb,
'step_size': 1,
'allocation_ratio': compute_node.ram_allocation_ratio,
},
'DISK_GB': {
'total': compute_node.local_gb,
'reserved': 1, # this is ceil(1000/1024)
'min_unit': 1,
'max_unit': compute_node.local_gb,
'step_size': 1,
'allocation_ratio': compute_node.disk_allocation_ratio,
},
}
self.assertEqual(expected, result)
def test_compute_node_inventory_empty(self):
uuid = uuids.compute_node
name = 'computehost'
compute_node = objects.ComputeNode(uuid=uuid,
hypervisor_hostname=name,
vcpus=0,
cpu_allocation_ratio=16.0,
memory_mb=0,
ram_allocation_ratio=1.5,
local_gb=0,
disk_allocation_ratio=1.0)
result = report._compute_node_to_inventory_dict(compute_node)
self.assertEqual({}, result)
class TestInventory(SchedulerReportClientTestCase):
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_ensure_resource_provider')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_update_inventory')
def test_update_compute_node(self, mock_ui, mock_erp):
cn = self.compute_node
self.client.update_compute_node(self.context, cn)
mock_erp.assert_called_once_with(self.context, cn.uuid,
cn.hypervisor_hostname)
expected_inv_data = {
'VCPU': {
'total': 8,
'reserved': CONF.reserved_host_cpus,
'min_unit': 1,
'max_unit': 8,
'step_size': 1,
'allocation_ratio': 16.0,
},
'MEMORY_MB': {
'total': 1024,
'reserved': 512,
'min_unit': 1,
'max_unit': 1024,
'step_size': 1,
'allocation_ratio': 1.5,
},
'DISK_GB': {
'total': 10,
'reserved': 0,
'min_unit': 1,
'max_unit': 10,
'step_size': 1,
'allocation_ratio': 1.0,
},
}
mock_ui.assert_called_once_with(
self.context,
cn.uuid,
expected_inv_data,
)
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_ensure_resource_provider')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_update_inventory')
def test_update_compute_node_no_inv(self, mock_ui, mock_erp):
"""Ensure that if there are no inventory records, we still call
_update_inventory().
"""
cn = self.compute_node
cn.vcpus = 0
cn.memory_mb = 0
cn.local_gb = 0
self.client.update_compute_node(self.context, cn)
mock_erp.assert_called_once_with(self.context, cn.uuid,
cn.hypervisor_hostname)
mock_ui.assert_called_once_with(self.context, cn.uuid, {})
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'get')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'put')
def test_update_inventory_initial_empty(self, mock_put, mock_get):
# Ensure _update_inventory() returns a list of Inventories objects
# after creating or updating the existing values
uuid = uuids.compute_node
compute_node = self.compute_node
# Make sure the resource provider exists for preventing to call the API
self._init_provider_tree(resources_override={})
mock_get.return_value.json.return_value = {
'resource_provider_generation': 43,
'inventories': {
'VCPU': {'total': 16},
'MEMORY_MB': {'total': 1024},
'DISK_GB': {'total': 10},
}
}
mock_put.return_value.status_code = 200
mock_put.return_value.json.return_value = {
'resource_provider_generation': 44,
'inventories': {
'VCPU': {'total': 16},
'MEMORY_MB': {'total': 1024},
'DISK_GB': {'total': 10},
}
}
inv_data = report._compute_node_to_inventory_dict(compute_node)
result = self.client._update_inventory_attempt(
self.context, compute_node.uuid, inv_data
)
self.assertTrue(result)
exp_url = '/resource_providers/%s/inventories' % uuid
mock_get.assert_called_once_with(
exp_url, global_request_id=self.context.global_id)
# Updated with the new inventory from the PUT call
self._validate_provider(uuid, generation=44)
expected = {
# Called with the newly-found generation from the existing
# inventory
'resource_provider_generation': 43,
'inventories': {
'VCPU': {
'total': 8,
'reserved': CONF.reserved_host_cpus,
'min_unit': 1,
'max_unit': compute_node.vcpus,
'step_size': 1,
'allocation_ratio': compute_node.cpu_allocation_ratio,
},
'MEMORY_MB': {
'total': 1024,
'reserved': CONF.reserved_host_memory_mb,
'min_unit': 1,
'max_unit': compute_node.memory_mb,
'step_size': 1,
'allocation_ratio': compute_node.ram_allocation_ratio,
},
'DISK_GB': {
'total': 10,
'reserved': 0, # reserved_host_disk_mb is 0 by default
'min_unit': 1,
'max_unit': compute_node.local_gb,
'step_size': 1,
'allocation_ratio': compute_node.disk_allocation_ratio,
},
}
}
mock_put.assert_called_once_with(
exp_url, expected, global_request_id=self.context.global_id)
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'get')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'put')
def test_update_inventory(self, mock_put, mock_get):
self.flags(reserved_host_disk_mb=1000)
# Ensure _update_inventory() returns a list of Inventories objects
# after creating or updating the existing values
uuid = uuids.compute_node
compute_node = self.compute_node
# Make sure the resource provider exists for preventing to call the API
self._init_provider_tree()
new_vcpus_total = 240
mock_get.return_value.json.return_value = {
'resource_provider_generation': 43,
'inventories': {
'VCPU': {'total': 16},
'MEMORY_MB': {'total': 1024},
'DISK_GB': {'total': 10},
}
}
mock_put.return_value.status_code = 200
mock_put.return_value.json.return_value = {
'resource_provider_generation': 44,
'inventories': {
'VCPU': {'total': new_vcpus_total},
'MEMORY_MB': {'total': 1024},
'DISK_GB': {'total': 10},
}
}
inv_data = report._compute_node_to_inventory_dict(compute_node)
# Make a change to trigger the update...
inv_data['VCPU']['total'] = new_vcpus_total
result = self.client._update_inventory_attempt(
self.context, compute_node.uuid, inv_data
)
self.assertTrue(result)
exp_url = '/resource_providers/%s/inventories' % uuid
mock_get.assert_called_once_with(
exp_url, global_request_id=self.context.global_id)
# Updated with the new inventory from the PUT call
self._validate_provider(uuid, generation=44)
expected = {
# Called with the newly-found generation from the existing
# inventory
'resource_provider_generation': 43,
'inventories': {
'VCPU': {
'total': new_vcpus_total,
'reserved': 0,
'min_unit': 1,
'max_unit': compute_node.vcpus,
'step_size': 1,
'allocation_ratio': compute_node.cpu_allocation_ratio,
},
'MEMORY_MB': {
'total': 1024,
'reserved': CONF.reserved_host_memory_mb,
'min_unit': 1,
'max_unit': compute_node.memory_mb,
'step_size': 1,
'allocation_ratio': compute_node.ram_allocation_ratio,
},
'DISK_GB': {
'total': 10,
'reserved': 1, # this is ceil for 1000MB
'min_unit': 1,
'max_unit': compute_node.local_gb,
'step_size': 1,
'allocation_ratio': compute_node.disk_allocation_ratio,
},
}
}
mock_put.assert_called_once_with(
exp_url, expected, global_request_id=self.context.global_id)
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'get')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'put')
def test_update_inventory_no_update(self, mock_put, mock_get):
"""Simulate situation where scheduler client is first starting up and
ends up loading information from the placement API via a GET against
the resource provider's inventory but has no local cached inventory
information for a resource provider.
"""
uuid = uuids.compute_node
compute_node = self.compute_node
# Make sure the resource provider exists for preventing to call the API
self._init_provider_tree(generation_override=42, resources_override={})
mock_get.return_value.json.return_value = {
'resource_provider_generation': 43,
'inventories': {
'VCPU': {
'total': 8,
'reserved': CONF.reserved_host_cpus,
'min_unit': 1,
'max_unit': compute_node.vcpus,
'step_size': 1,
'allocation_ratio': compute_node.cpu_allocation_ratio,
},
'MEMORY_MB': {
'total': 1024,
'reserved': CONF.reserved_host_memory_mb,
'min_unit': 1,
'max_unit': compute_node.memory_mb,
'step_size': 1,
'allocation_ratio': compute_node.ram_allocation_ratio,
},
'DISK_GB': {
'total': 10,
'reserved': 0,
'min_unit': 1,
'max_unit': compute_node.local_gb,
'step_size': 1,
'allocation_ratio': compute_node.disk_allocation_ratio,
},
}
}
inv_data = report._compute_node_to_inventory_dict(compute_node)
result = self.client._update_inventory_attempt(
self.context, compute_node.uuid, inv_data
)
self.assertTrue(result)
exp_url = '/resource_providers/%s/inventories' % uuid
mock_get.assert_called_once_with(
exp_url, global_request_id=self.context.global_id)
# No update so put should not be called
self.assertFalse(mock_put.called)
# Make sure we updated the generation from the inventory records
self._validate_provider(uuid, generation=43)
@mock.patch.object(report.LOG, 'info')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_get_inventory')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'put')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_ensure_resource_provider')
def test_update_inventory_concurrent_update(self, mock_ensure,
mock_put, mock_get, mock_info):
# Ensure _update_inventory() returns a list of Inventories objects
# after creating or updating the existing values
uuid = uuids.compute_node
compute_node = self.compute_node
# Make sure the resource provider exists for preventing to call the API
self.client._provider_tree.new_root(
compute_node.hypervisor_hostname,
compute_node.uuid,
generation=42,
)
mock_get.return_value = {
'resource_provider_generation': 42,
'inventories': {},
}
mock_put.return_value.status_code = 409
mock_put.return_value.text = 'Does not match inventory in use'
mock_put.return_value.headers = {'x-openstack-request-id':
uuids.request_id}
inv_data = report._compute_node_to_inventory_dict(compute_node)
result = self.client._update_inventory_attempt(
self.context, compute_node.uuid, inv_data
)
self.assertFalse(result)
# Invalidated the cache
self.assertFalse(self.client._provider_tree.exists(uuid))
# Refreshed our resource provider
mock_ensure.assert_called_once_with(self.context, uuid)
# Logged the request id in the log message
self.assertEqual(uuids.request_id,
mock_info.call_args[0][1]['placement_req_id'])
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_get_inventory')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'put')
def test_update_inventory_inventory_in_use(self, mock_put, mock_get):
# Ensure _update_inventory() returns a list of Inventories objects
# after creating or updating the existing values
uuid = uuids.compute_node
compute_node = self.compute_node
# Make sure the resource provider exists for preventing to call the API
self.client._provider_tree.new_root(
compute_node.hypervisor_hostname,
compute_node.uuid,
generation=42,
)
mock_get.return_value = {
'resource_provider_generation': 42,
'inventories': {},
}
mock_put.return_value.status_code = 409
mock_put.return_value.text = (
"update conflict: Inventory for VCPU on "
"resource provider 123 in use"
)
inv_data = report._compute_node_to_inventory_dict(compute_node)
self.assertRaises(
exception.InventoryInUse,
self.client._update_inventory_attempt,
self.context,
compute_node.uuid,
inv_data,
)
# Did NOT invalidate the cache
self.assertTrue(self.client._provider_tree.exists(uuid))
@mock.patch.object(report.LOG, 'info')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_get_inventory')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'put')
def test_update_inventory_unknown_response(self, mock_put, mock_get,
mock_info):
# Ensure _update_inventory() returns a list of Inventories objects
# after creating or updating the existing values
uuid = uuids.compute_node
compute_node = self.compute_node
# Make sure the resource provider exists for preventing to call the API
self.client._provider_tree.new_root(
compute_node.hypervisor_hostname,
compute_node.uuid,
generation=42,
)
mock_get.return_value = {
'resource_provider_generation': 42,
'inventories': {},
}
mock_put.return_value.status_code = 234
mock_put.return_value.headers = {'x-openstack-request-id':
uuids.request_id}
inv_data = report._compute_node_to_inventory_dict(compute_node)
result = self.client._update_inventory_attempt(
self.context, compute_node.uuid, inv_data
)
self.assertFalse(result)
# No cache invalidation
self.assertTrue(self.client._provider_tree.exists(uuid))
@mock.patch.object(report.LOG, 'warning')
@mock.patch.object(report.LOG, 'debug')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_get_inventory')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'put')
def test_update_inventory_failed(self, mock_put, mock_get,
mock_debug, mock_warn):
# Ensure _update_inventory() returns a list of Inventories objects
# after creating or updating the existing values
uuid = uuids.compute_node
compute_node = self.compute_node
# Make sure the resource provider exists for preventing to call the API
self.client._provider_tree.new_root(
compute_node.hypervisor_hostname,
compute_node.uuid,
generation=42,
)
mock_get.return_value = {
'resource_provider_generation': 42,
'inventories': {},
}
mock_put.return_value = fake_requests.FakeResponse(
400, headers={'x-openstack-request-id': uuids.request_id})
inv_data = report._compute_node_to_inventory_dict(compute_node)
result = self.client._update_inventory_attempt(
self.context, compute_node.uuid, inv_data
)
self.assertFalse(result)
# No cache invalidation
self.assertTrue(self.client._provider_tree.exists(uuid))
# Logged the request id in the log messages
self.assertEqual(uuids.request_id,
mock_debug.call_args[0][1]['placement_req_id'])
self.assertEqual(uuids.request_id,
mock_warn.call_args[0][1]['placement_req_id'])
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_ensure_resource_provider')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_update_inventory_attempt')
@mock.patch('time.sleep')
def test_update_inventory_fails_and_then_succeeds(self, mock_sleep,
mock_update,
mock_ensure):
# Ensure _update_inventory() fails if we have a conflict when updating
# but retries correctly.
cn = self.compute_node
mock_update.side_effect = (False, True)
self.client._provider_tree.new_root(
cn.hypervisor_hostname,
cn.uuid,
generation=42,
)
result = self.client._update_inventory(
self.context, cn.uuid, mock.sentinel.inv_data
)
self.assertTrue(result)
# Only slept once
mock_sleep.assert_called_once_with(1)
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_ensure_resource_provider')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_update_inventory_attempt')
@mock.patch('time.sleep')
def test_update_inventory_never_succeeds(self, mock_sleep,
mock_update,
mock_ensure):
# but retries correctly.
cn = self.compute_node
mock_update.side_effect = (False, False, False)
self.client._provider_tree.new_root(
cn.hypervisor_hostname,
cn.uuid,
generation=42,
)
result = self.client._update_inventory(
self.context, cn.uuid, mock.sentinel.inv_data
)
self.assertFalse(result)
# Slept three times
mock_sleep.assert_has_calls([mock.call(1), mock.call(1), mock.call(1)])
# Three attempts to update
mock_update.assert_has_calls([
mock.call(self.context, cn.uuid, mock.sentinel.inv_data),
mock.call(self.context, cn.uuid, mock.sentinel.inv_data),
mock.call(self.context, cn.uuid, mock.sentinel.inv_data),
])
# Slept three times
mock_sleep.assert_has_calls([mock.call(1), mock.call(1), mock.call(1)])
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_update_inventory')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_ensure_resource_classes')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_ensure_resource_provider')
def test_set_inventory_for_provider_no_custom(self, mock_erp, mock_erc,
mock_upd):
"""Tests that inventory records of all standard resource classes are
passed to the report client's _update_inventory() method.
"""
inv_data = {
'VCPU': {
'total': 24,
'reserved': 0,
'min_unit': 1,
'max_unit': 24,
'step_size': 1,
'allocation_ratio': 1.0,
},
'MEMORY_MB': {
'total': 1024,
'reserved': 0,
'min_unit': 1,
'max_unit': 1024,
'step_size': 1,
'allocation_ratio': 1.0,
},
'DISK_GB': {
'total': 100,
'reserved': 0,
'min_unit': 1,
'max_unit': 100,
'step_size': 1,
'allocation_ratio': 1.0,
},
}
self.client.set_inventory_for_provider(
self.context,
mock.sentinel.rp_uuid,
mock.sentinel.rp_name,
inv_data,
)
mock_erp.assert_called_once_with(
self.context,
mock.sentinel.rp_uuid,
mock.sentinel.rp_name,
parent_provider_uuid=None,
)
# No custom resource classes to ensure...
mock_erc.assert_called_once_with(self.context,
set(['VCPU', 'MEMORY_MB', 'DISK_GB']))
mock_upd.assert_called_once_with(
self.context,
mock.sentinel.rp_uuid,
inv_data,
)
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_update_inventory')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_ensure_resource_classes')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_ensure_resource_provider')
def test_set_inventory_for_provider_no_inv(self, mock_erp, mock_erc,
mock_upd):
"""Tests that passing empty set of inventory records triggers a delete
of inventory for the provider.
"""
inv_data = {}
self.client.set_inventory_for_provider(
self.context,
mock.sentinel.rp_uuid,
mock.sentinel.rp_name,
inv_data,
)
mock_erp.assert_called_once_with(
self.context,
mock.sentinel.rp_uuid,
mock.sentinel.rp_name,
parent_provider_uuid=None,
)
mock_erc.assert_called_once_with(self.context, set())
mock_upd.assert_called_once_with(
self.context, mock.sentinel.rp_uuid, {})
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_update_inventory')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_ensure_resource_classes')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_ensure_resource_provider')
def test_set_inventory_for_provider_with_custom(self, mock_erp, mock_erc,
mock_upd):
"""Tests that inventory records that include a custom resource class
are passed to the report client's _update_inventory() method and that
the custom resource class is auto-created.
"""
inv_data = {
'VCPU': {
'total': 24,
'reserved': 0,
'min_unit': 1,
'max_unit': 24,
'step_size': 1,
'allocation_ratio': 1.0,
},
'MEMORY_MB': {
'total': 1024,
'reserved': 0,
'min_unit': 1,
'max_unit': 1024,
'step_size': 1,
'allocation_ratio': 1.0,
},
'DISK_GB': {
'total': 100,
'reserved': 0,
'min_unit': 1,
'max_unit': 100,
'step_size': 1,
'allocation_ratio': 1.0,
},
'CUSTOM_IRON_SILVER': {
'total': 1,
'reserved': 0,
'min_unit': 1,
'max_unit': 1,
'step_size': 1,
'allocation_ratio': 1.0,
}
}
self.client.set_inventory_for_provider(
self.context,
mock.sentinel.rp_uuid,
mock.sentinel.rp_name,
inv_data,
)
mock_erp.assert_called_once_with(
self.context,
mock.sentinel.rp_uuid,
mock.sentinel.rp_name,
parent_provider_uuid=None,
)
mock_erc.assert_called_once_with(
self.context,
set(['VCPU', 'MEMORY_MB', 'DISK_GB', 'CUSTOM_IRON_SILVER']))
mock_upd.assert_called_once_with(
self.context,
mock.sentinel.rp_uuid,
inv_data,
)
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_ensure_resource_classes', new=mock.Mock())
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'_ensure_resource_provider')
def test_set_inventory_for_provider_with_parent(self, mock_erp):
"""Ensure parent UUID is sent through."""
self.client.set_inventory_for_provider(
self.context, uuids.child, 'junior', {},
parent_provider_uuid=uuids.parent)
mock_erp.assert_called_once_with(
self.context, uuids.child, 'junior',
parent_provider_uuid=uuids.parent)
class TestAllocations(SchedulerReportClientTestCase):
@mock.patch('nova.compute.utils.is_volume_backed_instance')
def test_instance_to_allocations_dict(self, mock_vbi):
mock_vbi.return_value = False
inst = objects.Instance(
uuid=uuids.inst,
flavor=objects.Flavor(root_gb=10,
swap=1023,
ephemeral_gb=100,
memory_mb=1024,
vcpus=2,
extra_specs={}))
result = report._instance_to_allocations_dict(inst)
expected = {
'MEMORY_MB': 1024,
'VCPU': 2,
'DISK_GB': 111,
}
self.assertEqual(expected, result)
@mock.patch('nova.compute.utils.is_volume_backed_instance')
def test_instance_to_allocations_dict_overrides(self, mock_vbi):
"""Test that resource overrides in an instance's flavor extra_specs
are reported to placement.
"""
mock_vbi.return_value = False
specs = {
'resources:CUSTOM_DAN': '123',
'resources:%s' % fields.ResourceClass.VCPU: '4',
'resources:NOTATHING': '456',
'resources:NOTEVENANUMBER': 'catfood',
'resources:': '7',
'resources:ferret:weasel': 'smelly',
'foo': 'bar',
}
inst = objects.Instance(
uuid=uuids.inst,
flavor=objects.Flavor(root_gb=10,
swap=1023,
ephemeral_gb=100,
memory_mb=1024,
vcpus=2,
extra_specs=specs))
result = report._instance_to_allocations_dict(inst)
expected = {
'MEMORY_MB': 1024,
'VCPU': 4,
'DISK_GB': 111,
'CUSTOM_DAN': 123,
}
self.assertEqual(expected, result)
@mock.patch('nova.compute.utils.is_volume_backed_instance')
def test_instance_to_allocations_dict_boot_from_volume(self, mock_vbi):
mock_vbi.return_value = True
inst = objects.Instance(
uuid=uuids.inst,
flavor=objects.Flavor(root_gb=10,
swap=1,
ephemeral_gb=100,
memory_mb=1024,
vcpus=2,
extra_specs={}))
result = report._instance_to_allocations_dict(inst)
expected = {
'MEMORY_MB': 1024,
'VCPU': 2,
'DISK_GB': 101,
}
self.assertEqual(expected, result)
@mock.patch('nova.compute.utils.is_volume_backed_instance')
def test_instance_to_allocations_dict_zero_disk(self, mock_vbi):
mock_vbi.return_value = True
inst = objects.Instance(
uuid=uuids.inst,
flavor=objects.Flavor(root_gb=10,
swap=0,
ephemeral_gb=0,
memory_mb=1024,
vcpus=2,
extra_specs={}))
result = report._instance_to_allocations_dict(inst)
expected = {
'MEMORY_MB': 1024,
'VCPU': 2,
}
self.assertEqual(expected, result)
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'put')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'get')
@mock.patch('nova.scheduler.client.report.'
'_instance_to_allocations_dict')
def test_update_instance_allocation_new(self, mock_a, mock_get,
mock_put):
cn = objects.ComputeNode(uuid=uuids.cn)
inst = objects.Instance(uuid=uuids.inst, project_id=uuids.project,
user_id=uuids.user)
mock_get.return_value.json.return_value = {'allocations': {}}
expected = {
'allocations': [
{'resource_provider': {'uuid': cn.uuid},
'resources': mock_a.return_value}],
'project_id': inst.project_id,
'user_id': inst.user_id,
}
self.client.update_instance_allocation(self.context, cn, inst, 1)
mock_put.assert_called_once_with(
'/allocations/%s' % inst.uuid,
expected, version='1.8',
global_request_id=self.context.global_id)
self.assertTrue(mock_get.called)
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'put')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'get')
@mock.patch('nova.scheduler.client.report.'
'_instance_to_allocations_dict')
def test_update_instance_allocation_existing(self, mock_a, mock_get,
mock_put):
cn = objects.ComputeNode(uuid=uuids.cn)
inst = objects.Instance(uuid=uuids.inst)
mock_get.return_value.json.return_value = {'allocations': {
cn.uuid: {
'generation': 2,
'resources': {
'DISK_GB': 123,
'MEMORY_MB': 456,
}
}}
}
mock_a.return_value = {
'DISK_GB': 123,
'MEMORY_MB': 456,
}
self.client.update_instance_allocation(self.context, cn, inst, 1)
self.assertFalse(mock_put.called)
mock_get.assert_called_once_with(
'/allocations/%s' % inst.uuid,
global_request_id=self.context.global_id)
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'get')
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'put')
@mock.patch('nova.scheduler.client.report.'
'_instance_to_allocations_dict')
@mock.patch.object(report.LOG, 'warning')
def test_update_instance_allocation_new_failed(self, mock_warn, mock_a,
mock_put, mock_get):
cn = objects.ComputeNode(uuid=uuids.cn)
inst = objects.Instance(uuid=uuids.inst, project_id=uuids.project,
user_id=uuids.user)
mock_put.return_value = fake_requests.FakeResponse(400)
self.client.update_instance_allocation(self.context, cn, inst, 1)
self.assertTrue(mock_warn.called)
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'delete')
def test_update_instance_allocation_delete(self, mock_delete):
cn = objects.ComputeNode(uuid=uuids.cn)
inst = objects.Instance(uuid=uuids.inst)
self.client.update_instance_allocation(self.context, cn, inst, -1)
mock_delete.assert_called_once_with(
'/allocations/%s' % inst.uuid,
global_request_id=self.context.global_id)
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'delete')
@mock.patch.object(report.LOG, 'warning')
def test_update_instance_allocation_delete_failed(self, mock_warn,
mock_delete):
cn = objects.ComputeNode(uuid=uuids.cn)
inst = objects.Instance(uuid=uuids.inst)
mock_delete.return_value = fake_requests.FakeResponse(400)
self.client.update_instance_allocation(self.context, cn, inst, -1)
self.assertTrue(mock_warn.called)
@mock.patch('nova.scheduler.client.report.SchedulerReportClient.'
'delete')
@mock.patch('nova.scheduler.client.report.LOG')
def test_delete_allocation_for_instance_ignore_404(self, mock_log,
mock_delete):
"""Tests that we don't log a warning on a 404 response when trying to
delete an allocation record.
"""
mock_delete.return_value = fake_requests.FakeResponse(404)
self.client.delete_allocation_for_instance(self.context, uuids.rp_uuid)
# make sure we didn't screw up the logic or the mock
mock_log.info.assert_not_called()
# make sure warning wasn't called for the 404
mock_log.warning.assert_not_called()
@mock.patch("nova.scheduler.client.report.SchedulerReportClient."
"delete")
@mock.patch("nova.scheduler.client.report.SchedulerReportClient."
"delete_allocation_for_instance")
@mock.patch("nova.objects.InstanceList.get_by_host_and_node")
def test_delete_resource_provider_cascade(self, mock_by_host,
mock_del_alloc, mock_delete):
self.client._provider_tree.new_root(uuids.cn, uuids.cn, generation=1)
cn = objects.ComputeNode(uuid=uuids.cn, host="fake_host",
hypervisor_hostname="fake_hostname", )
inst1 = objects.Instance(uuid=uuids.inst1)
inst2 = objects.Instance(uuid=uuids.inst2)
mock_by_host.return_value = objects.InstanceList(
objects=[inst1, inst2])
resp_mock = mock.Mock(status_code=204)
mock_delete.return_value = resp_mock
self.client.delete_resource_provider(self.context, cn, cascade=True)
self.assertEqual(2, mock_del_alloc.call_count)
exp_url = "/resource_providers/%s" % uuids.cn
mock_delete.assert_called_once_with(
exp_url, global_request_id=self.context.global_id)
self.assertFalse(self.client._provider_tree.exists(uuids.cn))
@mock.patch("nova.scheduler.client.report.SchedulerReportClient."
"delete")
@mock.patch("nova.scheduler.client.report.SchedulerReportClient."
"delete_allocation_for_instance")
@mock.patch("nova.objects.InstanceList.get_by_host_and_node")
def test_delete_resource_provider_no_cascade(self, mock_by_host,
mock_del_alloc, mock_delete):
self.client._provider_tree.new_root(uuids.cn, uuids.cn, generation=1)
self.client._association_refresh_time[uuids.cn] = mock.Mock()
cn = objects.ComputeNode(uuid=uuids.cn, host="fake_host",
hypervisor_hostname="fake_hostname", )
inst1 = objects.Instance(uuid=uuids.inst1)
inst2 = objects.Instance(uuid=uuids.inst2)
mock_by_host.return_value = objects.InstanceList(
objects=[inst1, inst2])
resp_mock = mock.Mock(status_code=204)
mock_delete.return_value = resp_mock
self.client.delete_resource_provider(self.context, cn)
mock_del_alloc.assert_not_called()
exp_url = "/resource_providers/%s" % uuids.cn
mock_delete.assert_called_once_with(
exp_url, global_request_id=self.context.global_id)
self.assertNotIn(uuids.cn, self.client._association_refresh_time)
@mock.patch("nova.scheduler.client.report.SchedulerReportClient."
"delete")
@mock.patch('nova.scheduler.client.report.LOG')
def test_delete_resource_provider_log_calls(self, mock_log, mock_delete):
# First, check a successful call
self.client._provider_tree.new_root(uuids.cn, uuids.cn, generation=1)
cn = objects.ComputeNode(uuid=uuids.cn, host="fake_host",
hypervisor_hostname="fake_hostname", )
resp_mock = fake_requests.FakeResponse(204)
mock_delete.return_value = resp_mock
self.client.delete_resource_provider(self.context, cn)
# With a 204, only the info should be called
self.assertEqual(1, mock_log.info.call_count)
self.assertEqual(0, mock_log.warning.call_count)
# Now check a 404 response
mock_log.reset_mock()
resp_mock.status_code = 404
self.client.delete_resource_provider(self.context, cn)
# With a 404, neither log message should be called
self.assertEqual(0, mock_log.info.call_count)
self.assertEqual(0, mock_log.warning.call_count)
# Finally, check a 409 response
mock_log.reset_mock()
resp_mock.status_code = 409
self.client.delete_resource_provider(self.context, cn)
# With a 409, only the error should be called
self.assertEqual(0, mock_log.info.call_count)
self.assertEqual(1, mock_log.error.call_count)
class TestResourceClass(SchedulerReportClientTestCase):
def setUp(self):
super(TestResourceClass, self).setUp()
_put_patch = mock.patch(
"nova.scheduler.client.report.SchedulerReportClient.put")
self.addCleanup(_put_patch.stop)
self.mock_put = _put_patch.start()
def test_ensure_resource_classes(self):
rcs = ['VCPU', 'CUSTOM_FOO', 'MEMORY_MB', 'CUSTOM_BAR']
self.client._ensure_resource_classes(self.context, rcs)
self.mock_put.assert_has_calls([
mock.call('/resource_classes/%s' % rc, None, version='1.7',
global_request_id=self.context.global_id)
for rc in ('CUSTOM_FOO', 'CUSTOM_BAR')
], any_order=True)
def test_ensure_resource_classes_none(self):
for empty in ([], (), set(), {}):
self.client._ensure_resource_classes(self.context, empty)
self.mock_put.assert_not_called()
def test_ensure_resource_classes_put_fail(self):
self.mock_put.return_value = fake_requests.FakeResponse(503)
rcs = ['VCPU', 'MEMORY_MB', 'CUSTOM_BAD']
self.assertRaises(
exception.InvalidResourceClass,
self.client._ensure_resource_classes, self.context, rcs)
# Only called with the "bad" one
self.mock_put.assert_called_once_with(
'/resource_classes/CUSTOM_BAD', None, version='1.7',
global_request_id=self.context.global_id)
|
apache-2.0
|
bnsantos/android-javarx-example
|
app/src/main/java/com/bnsantos/movies/model/Links.java
|
1305
|
package com.bnsantos.movies.model;
import com.j256.ormlite.field.DatabaseField;
/**
* Created by bruno on 14/11/14.
*/
public class Links {
@DatabaseField(generatedId = true, columnName = "id")
private Integer id;
@DatabaseField()
private String self;
@DatabaseField()
private String alternate;
@DatabaseField()
private String cast;
@DatabaseField()
private String reviews;
@DatabaseField()
private String similar;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSelf() {
return self;
}
public void setSelf(String self) {
this.self = self;
}
public String getAlternate() {
return alternate;
}
public void setAlternate(String alternate) {
this.alternate = alternate;
}
public String getCast() {
return cast;
}
public void setCast(String cast) {
this.cast = cast;
}
public String getReviews() {
return reviews;
}
public void setReviews(String reviews) {
this.reviews = reviews;
}
public String getSimilar() {
return similar;
}
public void setSimilar(String similar) {
this.similar = similar;
}
}
|
apache-2.0
|
google/myelin-acorn-electron-hardware
|
third_party/arm-trusted-firmware/memset.c
|
402
|
/*
* Copyright (c) 2013-2018, ARM Limited and Contributors. All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*
* https://raw.githubusercontent.com/ARM-software/arm-trusted-firmware/6d4f6aea2cd96a4a57ffa2d88b9230e2cab88f28/lib/libc/memset.c
*/
#include <stddef.h>
void *memset(void *dst, int val, size_t count)
{
char *ptr = dst;
while (count--)
*ptr++ = val;
return dst;
}
|
apache-2.0
|
tengbinlive/aibao_demo
|
app/src/main/java/com/mytian/lb/bean/push/UpdateChannelidParam.java
|
1799
|
package com.mytian.lb.bean.push;
import com.core.openapi.OpenApiBaseRequestAdapter;
import com.core.util.StringUtil;
import java.util.HashMap;
import java.util.Map;
public class UpdateChannelidParam extends OpenApiBaseRequestAdapter {
private String uid;
private String token;
private String channelId;
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getChannelId() {
return channelId;
}
public void setChannelId(String channelId) {
this.channelId = channelId;
}
@Override
public boolean validate() {
if (StringUtil.isBlank(this.uid)) return false;
if (StringUtil.isBlank(this.token)) return false;
if (StringUtil.isBlank(this.channelId)) return false;
return true;
}
@Override
public void fill2Map(Map<String, Object> param, boolean includeEmptyAttr) {
if (includeEmptyAttr || (!includeEmptyAttr && StringUtil.isNotBlank(uid)))
param.put("uid", uid);
if (includeEmptyAttr || (!includeEmptyAttr && StringUtil.isNotBlank(token)))
param.put("token", token);
if (includeEmptyAttr || (!includeEmptyAttr && StringUtil.isNotBlank(channelId)))
param.put("parent.channelId", channelId);
}
@Override
public String toString() {
return "UpdateChannelidParam{" +
"uid='" + uid + '\'' +
", token='" + token + '\'' +
", channelId='" + channelId + '\'' +
'}';
}
}
|
apache-2.0
|
robsoncardosoti/flowable-engine
|
modules/flowable-form-rest/src/main/java/org/flowable/rest/form/FormRestUrls.java
|
4399
|
/* 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 org.flowable.rest.form;
import java.text.MessageFormat;
import org.apache.commons.lang3.StringUtils;
/**
* @author Yvo Swillens
*/
public final class FormRestUrls {
public static final String SEGMENT_FORM_RESOURCES = "form";
public static final String SEGMENT_REPOSITORY_RESOURCES = "form-repository";
public static final String SEGMENT_RUNTIME_FORM_DEFINITION = "runtime-form-definition";
public static final String SEGMENT_COMPLETED_FORM_DEFINITION = "completed-form-definition";
public static final String SEGMENT_DEPLOYMENT_RESOURCES = "deployments";
public static final String SEGMENT_DEPLOYMENT_ARTIFACT_RESOURCE_CONTENT = "resourcedata";
public static final String SEGMENT_FORMS_RESOURCES = "forms";
public static final String SEGMENT_FORM_MODEL = "model";
public static final String SEGMENT_FORM_INSTANCES_RESOURCES = "form-instances";
public static final String SEGMENT_QUERY_RESOURCES = "query";
/**
* URL template for a form collection: <i>/form/runtime-form-definition</i>
*/
public static final String[] URL_RUNTIME_TASK_FORM = { SEGMENT_FORM_RESOURCES, SEGMENT_RUNTIME_FORM_DEFINITION };
/**
* URL template for a form collection: <i>/form/completed-form-definition</i>
*/
public static final String[] URL_COMPLETED_TASK_FORM = { SEGMENT_FORM_RESOURCES, SEGMENT_COMPLETED_FORM_DEFINITION };
/**
* URL template for a form collection: <i>/form-repository/forms/{0:formId}</i>
*/
public static final String[] URL_FORM_COLLECTION = { SEGMENT_REPOSITORY_RESOURCES, SEGMENT_FORMS_RESOURCES };
/**
* URL template for a single form: <i>/form-repository/forms/{0:formId}</i>
*/
public static final String[] URL_FORM = { SEGMENT_REPOSITORY_RESOURCES, SEGMENT_FORMS_RESOURCES, "{0}" };
/**
* URL template for a single form model: <i>/form-repository/forms/{0:formId}/model</i>
*/
public static final String[] URL_FORM_MODEL = { SEGMENT_REPOSITORY_RESOURCES, SEGMENT_FORM_RESOURCES, "{0}", SEGMENT_FORM_MODEL };
/**
* URL template for the resource of a single form: <i>/form-repository/forms/{0:formId}/resourcedata</i>
*/
public static final String[] URL_FORM_RESOURCE_CONTENT = { SEGMENT_REPOSITORY_RESOURCES, SEGMENT_FORM_RESOURCES, "{0}", SEGMENT_DEPLOYMENT_ARTIFACT_RESOURCE_CONTENT };
/**
* URL template for a deployment collection: <i>/form-repository/deployments</i>
*/
public static final String[] URL_DEPLOYMENT_COLLECTION = { SEGMENT_REPOSITORY_RESOURCES, SEGMENT_DEPLOYMENT_RESOURCES };
/**
* URL template for a single deployment: <i>/form-repository/deployments/{0:deploymentId}</i>
*/
public static final String[] URL_DEPLOYMENT = { SEGMENT_REPOSITORY_RESOURCES, SEGMENT_DEPLOYMENT_RESOURCES, "{0}" };
/**
* URL template for the resource of a single deployment: <i>/form-repository/deployments/{0:deploymentId}/resourcedata/{1:resourceId}</i>
*/
public static final String[] URL_DEPLOYMENT_RESOURCE_CONTENT = { SEGMENT_REPOSITORY_RESOURCES, SEGMENT_DEPLOYMENT_RESOURCES, "{0}", SEGMENT_DEPLOYMENT_ARTIFACT_RESOURCE_CONTENT, "{1}" };
/**
* URL template for the resource of a form instance query: <i>/query/form-instances</i>
*/
public static final String[] URL_FORM_INSTANCE_QUERY = { SEGMENT_QUERY_RESOURCES, SEGMENT_FORM_INSTANCES_RESOURCES };
/**
* Creates an url based on the passed fragments and replaces any placeholders with the given arguments. The placeholders are following the {@link MessageFormat} convention (eg. {0} is replaced by
* first argument value).
*/
public static final String createRelativeResourceUrl(String[] segments, Object... arguments) {
return MessageFormat.format(StringUtils.join(segments, '/'), arguments);
}
}
|
apache-2.0
|
wildfly-swarm/wildfly-swarm-javadocs
|
2.1.0.Final/apidocs/org/wildfly/swarm/config/messaging/activemq/server/RuntimeQueueSupplier.html
|
9744
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_151) on Tue Aug 14 15:31:42 MST 2018 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>RuntimeQueueSupplier (BOM: * : All 2.1.0.Final API)</title>
<meta name="date" content="2018-08-14">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="RuntimeQueueSupplier (BOM: * : All 2.1.0.Final API)";
}
}
catch(err) {
}
//-->
var methods = {"i0":6};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/RuntimeQueueSupplier.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.1.0.Final</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/RuntimeQueueConsumer.html" title="interface in org.wildfly.swarm.config.messaging.activemq.server"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/SecuritySetting.html" title="class in org.wildfly.swarm.config.messaging.activemq.server"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/wildfly/swarm/config/messaging/activemq/server/RuntimeQueueSupplier.html" target="_top">Frames</a></li>
<li><a href="RuntimeQueueSupplier.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.wildfly.swarm.config.messaging.activemq.server</div>
<h2 title="Interface RuntimeQueueSupplier" class="title">Interface RuntimeQueueSupplier<T extends <a href="../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/RuntimeQueue.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">RuntimeQueue</a>></h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>Functional Interface:</dt>
<dd>This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.</dd>
</dl>
<hr>
<br>
<pre><a href="http://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html?is-external=true" title="class or interface in java.lang">@FunctionalInterface</a>
public interface <span class="typeNameLabel">RuntimeQueueSupplier<T extends <a href="../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/RuntimeQueue.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">RuntimeQueue</a>></span></pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code><a href="../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/RuntimeQueue.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">RuntimeQueue</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/RuntimeQueueSupplier.html#get--">get</a></span>()</code>
<div class="block">Constructed instance of RuntimeQueue resource</div>
</td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="get--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>get</h4>
<pre><a href="../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/RuntimeQueue.html" title="class in org.wildfly.swarm.config.messaging.activemq.server">RuntimeQueue</a> get()</pre>
<div class="block">Constructed instance of RuntimeQueue resource</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The instance</dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/RuntimeQueueSupplier.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.1.0.Final</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/RuntimeQueueConsumer.html" title="interface in org.wildfly.swarm.config.messaging.activemq.server"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../../../org/wildfly/swarm/config/messaging/activemq/server/SecuritySetting.html" title="class in org.wildfly.swarm.config.messaging.activemq.server"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/wildfly/swarm/config/messaging/activemq/server/RuntimeQueueSupplier.html" target="_top">Frames</a></li>
<li><a href="RuntimeQueueSupplier.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2018 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
|
apache-2.0
|
BoxUpp/boxupp
|
page/templates/projects.html
|
6754
|
<!-- <script type="text/javascript-lazy" src="js/projectController.js"></script> -->
<div class="container-fluid">
<div class="project-container col-md-12">
<div class="row">
<div class="col-md-offset-1 col-md-10 text-center">
<h2 class="projectsTitle">
<span class="titleText loginInput">
<span ng-hide="projects.length === 0">Select a workspace below or </span>
<span ng-show="projects.length === 0">Looks like you have not added any workspaces yet !</span>
</span>
<strong>
<a data-toggle="modal" data-target="#newMachineModal" style="cursor:pointer;" class="titleTextAction">
Create a new one
</a>
</strong>
</h2>
</div>
</div>
<div class="row">
<!-- New Machine Modal -->
<div class="modal fade" id="newMachineModal" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
</div>
<div class="modal-body">
<form name="newProjectData">
<div class="container-fluid">
<div class="row">
<div class="projectLogo col-sm-2">
<i class="glyphicon glyphicon-folder-open"></i>
</div>
<div class="boxConfig col-sm-10">
<div class="boxConfigTitles">Enter workspace name<sup>*</sup></div>
<input name="projectTitle" type="text" ng-model="newProject.name" class="form-control">
</div>
<div class="boxConfig col-sm-10">
<div class="boxConfigTitles">Enter workspace description <sup>*</sup></div>
<input name="projectDesc"type="text" ng-model="newProject.description" class="form-control">
</div>
<div class="boxConfig col-sm-10">
<div class="boxConfigTitles">Select a provider type for your workspace<sup>*</sup></div>
<select name="providerNames" ng-model="newProject.providerType" ng-change="checkProviderType(newProject.providerType)" ng-options="provider.providerID as provider.name for provider in providers" class="form-control">
<option value="" >Select a provider</option>
</select>
</div>
<div id="awsCredentials" ng-init="showAwsCredDiv=false;authenticatCred=false;loader.loading=false" ng-show="showAwsCredDiv" class="col-md-10 col-md-push-2">
<div class="boxConfig">
<div class="boxConfigTitles">Enter Aws Access Key Id <sup>*</sup></div>
<input name="awsAccessKeyId" type="text" ng-model="newProject.awsAccessKeyId" class="form-control"
ng-minlength="16" ng-maxlength="32" ng-pattern="/^[a-zA-Z0-9]*$/" required >
<div ng-messages="newProjectData.awsAccessKeyId.$error" >
<div ng-message="pattern" class="errorMessage">Invalid pattern.It should only contain alphanumeric chars</div>
<div ng-message="maxlength" class="errorMessage">Maximum of 32 chars</div>
<div ng-message="minlength" class="errorMessage">Minimum of 16 chars</div>
</div>
</div>
<div class="boxConfig">
<div class="boxConfigTitles">Enter Aws Secret Access Key <sup>*</sup></div>
<input name="awsSecretAccessKey" type="text" ng-model="newProject.awsSecretAccessKey" class="form-control"
required >
</div>
<div class="boxConfig">
<div class="boxConfigTitles">Enter Key Pair Name <sup>*</sup></div>
<input name="awsKeyPair" type="text" ng-model="newProject.awsKeyPair" class="form-control"
required >
</div>
<div class="boxConfig">
<div class="boxConfigTitles">Enter Private Key Path <sup>*</sup></div>
<input name="privateKeyPath" type="text" ng-model="newProject.privateKeyPath" class="form-control"
required>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<div class="row">
<div class="col-md-8 statusMessage" >
<div class="cancel" ng-if="loader.loading">
Validating Credentials <i class="fa fa-spinner fa-spin"></i>
</div>
<div ng-if="newProjectCreated" style="transition-property:all; transition-duration:2.0s"ng-init="newProjectCreated = false">
<span><i class="fa fa-thumbs-up"></i> Your new workspace has been created! </span>
</div>
<div ng-if=awsAuthenticationSuccess style="transition-property:all; transition-duration:2.0s" ng-init="awsAuthenticationSuccess = false">
<span><i class="fa fa-thumbs-up"></i> {{awsAuthenticationMessage}}</span>
</div>
<div ng-if=awsAuthenticationFailure style="transition-property:all; transition-duration:2.0s" ng-init="awsAuthenticationFailure = false">
<span><i class="fa fa-thumbs-down"></i> {{awsAuthenticationMessage}}</span>
</div>
</div>
<!--<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>-->
<div class="modalClose col-md-4">
<a data-dismiss="modal" >Close</a>
<button class="btn btn-success" ng-click="authenticateAwsCredentials()" ng-show="showAwsCredDiv"
ng-disabled="!checkAwsCredentialsStatus()">Verify </button>
<button class="btn btn-success" ng-click="submitNewProjectData()" ng-disabled="checkProjectInput()">Create</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-offset-1 col-md-10" >
<div class="projects">
<ul class="projectsList">
<li class="col-md-4" ng-repeat="project in projects">
<a ng-click="selectProject(project)">
<div class="projectLogo">
<i class="glyphicon glyphicon-folder-open"></i>
</div>
<div class="projectTitle" >
<strong><span ng-bind="project.name"></span></strong>
</div>
<div class="projectDesc">
<span ng-bind="project.description"></span>
</div>
</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
|
apache-2.0
|
garfieldnate/Weka_AnalogicalModeling
|
src/test/java/weka/classifiers/lazy/AM/label/IntLabelerTest.java
|
877
|
package weka.classifiers.lazy.AM.label;
import org.hamcrest.core.StringContains;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import weka.classifiers.lazy.AM.TestUtils;
import weka.core.Instances;
/**
* Test aspects of {@link IntLabeler} that are not applicable to other
* {@link Labeler} implementations.
*
* @author Nathan Glenn
*/
public class IntLabelerTest {
@Rule
public final ExpectedException exception = ExpectedException.none();
@Test
public void testConstructorCardinalityTooHigh() throws Exception {
exception.expect(IllegalArgumentException.class);
exception.expectMessage(new StringContains("Cardinality of instance too high (35)"));
Instances data = TestUtils.getDataSet(TestUtils.SOYBEAN);
new IntLabeler(data.get(0), false, MissingDataCompare.MATCH);
}
}
|
apache-2.0
|
JFixby/libgdx-nightly
|
gdx-nightly/docs/api/com/badlogic/gdx/utils/class-use/Json.Serializable.html
|
44026
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_05) on Tue Feb 02 23:09:49 CET 2016 -->
<title>Uses of Interface com.badlogic.gdx.utils.Json.Serializable (libgdx API)</title>
<meta name="date" content="2016-02-02">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface com.badlogic.gdx.utils.Json.Serializable (libgdx API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../com/badlogic/gdx/utils/Json.Serializable.html" title="interface in com.badlogic.gdx.utils">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">
libgdx API
<style>
body, td, th { font-family:Helvetica, Tahoma, Arial, sans-serif; font-size:10pt }
pre, code, tt { font-size:9pt; font-family:Lucida Console, Courier New, sans-serif }
h1, h2, h3, .FrameTitleFont, .FrameHeadingFont, .TableHeadingColor font { font-size:105%; font-weight:bold }
.TableHeadingColor { background:#EEEEFF; }
a { text-decoration:none }
a:hover { text-decoration:underline }
a:link, a:visited { color:blue }
table { border:0px }
.TableRowColor td:first-child { border-left:1px solid black }
.TableRowColor td { border:0px; border-bottom:1px solid black; border-right:1px solid black }
hr { border:0px; border-bottom:1px solid #333366; }
</style>
</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/badlogic/gdx/utils/class-use/Json.Serializable.html" target="_top">Frames</a></li>
<li><a href="Json.Serializable.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Interface com.badlogic.gdx.utils.Json.Serializable" class="title">Uses of Interface<br>com.badlogic.gdx.utils.Json.Serializable</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../com/badlogic/gdx/utils/Json.Serializable.html" title="interface in com.badlogic.gdx.utils">Json.Serializable</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#com.badlogic.gdx.graphics.g3d.particles">com.badlogic.gdx.graphics.g3d.particles</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#com.badlogic.gdx.graphics.g3d.particles.emitters">com.badlogic.gdx.graphics.g3d.particles.emitters</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="#com.badlogic.gdx.graphics.g3d.particles.influencers">com.badlogic.gdx.graphics.g3d.particles.influencers</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#com.badlogic.gdx.graphics.g3d.particles.renderers">com.badlogic.gdx.graphics.g3d.particles.renderers</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="#com.badlogic.gdx.graphics.g3d.particles.values">com.badlogic.gdx.graphics.g3d.particles.values</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="com.badlogic.gdx.graphics.g3d.particles">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../com/badlogic/gdx/utils/Json.Serializable.html" title="interface in com.badlogic.gdx.utils">Json.Serializable</a> in <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/package-summary.html">com.badlogic.gdx.graphics.g3d.particles</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/package-summary.html">com.badlogic.gdx.graphics.g3d.particles</a> that implement <a href="../../../../../com/badlogic/gdx/utils/Json.Serializable.html" title="interface in com.badlogic.gdx.utils">Json.Serializable</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/ParticleController.html" title="class in com.badlogic.gdx.graphics.g3d.particles">ParticleController</a></span></code>
<div class="block">Base class of all the particle controllers.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/ParticleControllerComponent.html" title="class in com.badlogic.gdx.graphics.g3d.particles">ParticleControllerComponent</a></span></code>
<div class="block">It's the base class of every <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/ParticleController.html" title="class in com.badlogic.gdx.graphics.g3d.particles"><code>ParticleController</code></a> component.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/ResourceData.html" title="class in com.badlogic.gdx.graphics.g3d.particles">ResourceData</a><T></span></code>
<div class="block">This class handles the assets and configurations required by a given resource when de/serialized.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/ResourceData.AssetData.html" title="class in com.badlogic.gdx.graphics.g3d.particles">ResourceData.AssetData</a><T></span></code>
<div class="block">This class contains all the information related to a given asset</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/ResourceData.SaveData.html" title="class in com.badlogic.gdx.graphics.g3d.particles">ResourceData.SaveData</a></span></code>
<div class="block">Contains all the saved data.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.badlogic.gdx.graphics.g3d.particles.emitters">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../com/badlogic/gdx/utils/Json.Serializable.html" title="interface in com.badlogic.gdx.utils">Json.Serializable</a> in <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/emitters/package-summary.html">com.badlogic.gdx.graphics.g3d.particles.emitters</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/emitters/package-summary.html">com.badlogic.gdx.graphics.g3d.particles.emitters</a> that implement <a href="../../../../../com/badlogic/gdx/utils/Json.Serializable.html" title="interface in com.badlogic.gdx.utils">Json.Serializable</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/emitters/Emitter.html" title="class in com.badlogic.gdx.graphics.g3d.particles.emitters">Emitter</a></span></code>
<div class="block">An <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/emitters/Emitter.html" title="class in com.badlogic.gdx.graphics.g3d.particles.emitters"><code>Emitter</code></a> is a <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/ParticleControllerComponent.html" title="class in com.badlogic.gdx.graphics.g3d.particles"><code>ParticleControllerComponent</code></a> which will handle the particles emission.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/emitters/RegularEmitter.html" title="class in com.badlogic.gdx.graphics.g3d.particles.emitters">RegularEmitter</a></span></code>
<div class="block">It's a generic use <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/emitters/Emitter.html" title="class in com.badlogic.gdx.graphics.g3d.particles.emitters"><code>Emitter</code></a> which fits most of the particles simulation scenarios.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.badlogic.gdx.graphics.g3d.particles.influencers">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../com/badlogic/gdx/utils/Json.Serializable.html" title="interface in com.badlogic.gdx.utils">Json.Serializable</a> in <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/package-summary.html">com.badlogic.gdx.graphics.g3d.particles.influencers</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/package-summary.html">com.badlogic.gdx.graphics.g3d.particles.influencers</a> that implement <a href="../../../../../com/badlogic/gdx/utils/Json.Serializable.html" title="interface in com.badlogic.gdx.utils">Json.Serializable</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/ColorInfluencer.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers">ColorInfluencer</a></span></code>
<div class="block">It's an <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/Influencer.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers"><code>Influencer</code></a> which controls particles color and transparency.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/ColorInfluencer.Random.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers">ColorInfluencer.Random</a></span></code>
<div class="block">It's an <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/Influencer.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers"><code>Influencer</code></a> which assigns a random color when a particle is activated.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/ColorInfluencer.Single.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers">ColorInfluencer.Single</a></span></code>
<div class="block">It's an <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/Influencer.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers"><code>Influencer</code></a> which manages the particle color during its life time.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/DynamicsInfluencer.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers">DynamicsInfluencer</a></span></code>
<div class="block">It's an <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/Influencer.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers"><code>Influencer</code></a> which controls the particles dynamics (movement, rotations).</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/DynamicsModifier.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers">DynamicsModifier</a></span></code>
<div class="block">It's the base class for any kind of influencer which operates on angular velocity and acceleration of the particles.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/DynamicsModifier.Angular.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers">DynamicsModifier.Angular</a></span></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/DynamicsModifier.BrownianAcceleration.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers">DynamicsModifier.BrownianAcceleration</a></span></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/DynamicsModifier.CentripetalAcceleration.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers">DynamicsModifier.CentripetalAcceleration</a></span></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/DynamicsModifier.FaceDirection.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers">DynamicsModifier.FaceDirection</a></span></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/DynamicsModifier.PolarAcceleration.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers">DynamicsModifier.PolarAcceleration</a></span></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/DynamicsModifier.Rotational2D.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers">DynamicsModifier.Rotational2D</a></span></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/DynamicsModifier.Rotational3D.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers">DynamicsModifier.Rotational3D</a></span></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/DynamicsModifier.Strength.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers">DynamicsModifier.Strength</a></span></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/DynamicsModifier.TangentialAcceleration.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers">DynamicsModifier.TangentialAcceleration</a></span></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/Influencer.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers">Influencer</a></span></code>
<div class="block">It's a <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/ParticleControllerComponent.html" title="class in com.badlogic.gdx.graphics.g3d.particles"><code>ParticleControllerComponent</code></a> which usually modifies one or more properties
of the particles(i.e color, scale, graphical representation, velocity, etc...).</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/ModelInfluencer.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers">ModelInfluencer</a></span></code>
<div class="block">It's an <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/Influencer.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers"><code>Influencer</code></a> which controls which <a href="../../../../../com/badlogic/gdx/graphics/g3d/Model.html" title="class in com.badlogic.gdx.graphics.g3d"><code>Model</code></a> will be assigned
to the particles as <a href="../../../../../com/badlogic/gdx/graphics/g3d/ModelInstance.html" title="class in com.badlogic.gdx.graphics.g3d"><code>ModelInstance</code></a>.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/ModelInfluencer.Random.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers">ModelInfluencer.Random</a></span></code>
<div class="block">Assigns a random model of <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/ModelInfluencer.html#models"><code>ModelInfluencer.models</code></a> to the particles.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/ModelInfluencer.Single.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers">ModelInfluencer.Single</a></span></code>
<div class="block">Assigns the first model of <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/ModelInfluencer.html#models"><code>ModelInfluencer.models</code></a> to the particles.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/ParticleControllerFinalizerInfluencer.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers">ParticleControllerFinalizerInfluencer</a></span></code>
<div class="block">It's an <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/Influencer.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers"><code>Influencer</code></a> which updates the simulation of particles containing a <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/ParticleController.html" title="class in com.badlogic.gdx.graphics.g3d.particles"><code>ParticleController</code></a>.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/ParticleControllerInfluencer.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers">ParticleControllerInfluencer</a></span></code>
<div class="block">It's an <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/Influencer.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers"><code>Influencer</code></a> which controls which <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/ParticleController.html" title="class in com.badlogic.gdx.graphics.g3d.particles"><code>ParticleController</code></a> will be assigned to a particle.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/ParticleControllerInfluencer.Random.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers">ParticleControllerInfluencer.Random</a></span></code>
<div class="block">Assigns a random controller of <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/ParticleControllerInfluencer.html#templates"><code>ParticleControllerInfluencer.templates</code></a> to the particles.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/ParticleControllerInfluencer.Single.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers">ParticleControllerInfluencer.Single</a></span></code>
<div class="block">Assigns the first controller of <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/ParticleControllerInfluencer.html#templates"><code>ParticleControllerInfluencer.templates</code></a> to the particles.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/RegionInfluencer.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers">RegionInfluencer</a></span></code>
<div class="block">It's an <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/Influencer.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers"><code>Influencer</code></a> which assigns a region of a <a href="../../../../../com/badlogic/gdx/graphics/Texture.html" title="class in com.badlogic.gdx.graphics"><code>Texture</code></a> to the particles.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/RegionInfluencer.Animated.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers">RegionInfluencer.Animated</a></span></code>
<div class="block">Assigns a region to the particles using the particle life percent
to calculate the current index in the <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/RegionInfluencer.html#regions"><code>RegionInfluencer.regions</code></a> array.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/RegionInfluencer.Random.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers">RegionInfluencer.Random</a></span></code>
<div class="block">Assigns a random region of <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/RegionInfluencer.html#regions"><code>RegionInfluencer.regions</code></a> to the particles.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/RegionInfluencer.Single.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers">RegionInfluencer.Single</a></span></code>
<div class="block">Assigns the first region of <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/RegionInfluencer.html#regions"><code>RegionInfluencer.regions</code></a> to the particles.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/ScaleInfluencer.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers">ScaleInfluencer</a></span></code>
<div class="block">It's an <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/Influencer.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers"><code>Influencer</code></a> which controls the scale of the particles.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/SimpleInfluencer.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers">SimpleInfluencer</a></span></code>
<div class="block">It's an <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/Influencer.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers"><code>Influencer</code></a> which controls a generic channel of the particles.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/SpawnInfluencer.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers">SpawnInfluencer</a></span></code>
<div class="block">It's an <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/influencers/Influencer.html" title="class in com.badlogic.gdx.graphics.g3d.particles.influencers"><code>Influencer</code></a> which controls where the particles will be spawned.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.badlogic.gdx.graphics.g3d.particles.renderers">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../com/badlogic/gdx/utils/Json.Serializable.html" title="interface in com.badlogic.gdx.utils">Json.Serializable</a> in <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/renderers/package-summary.html">com.badlogic.gdx.graphics.g3d.particles.renderers</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/renderers/package-summary.html">com.badlogic.gdx.graphics.g3d.particles.renderers</a> that implement <a href="../../../../../com/badlogic/gdx/utils/Json.Serializable.html" title="interface in com.badlogic.gdx.utils">Json.Serializable</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/renderers/BillboardRenderer.html" title="class in com.badlogic.gdx.graphics.g3d.particles.renderers">BillboardRenderer</a></span></code>
<div class="block">A <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/renderers/ParticleControllerRenderer.html" title="class in com.badlogic.gdx.graphics.g3d.particles.renderers"><code>ParticleControllerRenderer</code></a> which will render particles as billboards to a <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/batches/BillboardParticleBatch.html" title="class in com.badlogic.gdx.graphics.g3d.particles.batches"><code>BillboardParticleBatch</code></a> .</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/renderers/ModelInstanceRenderer.html" title="class in com.badlogic.gdx.graphics.g3d.particles.renderers">ModelInstanceRenderer</a></span></code>
<div class="block">A <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/renderers/ParticleControllerRenderer.html" title="class in com.badlogic.gdx.graphics.g3d.particles.renderers"><code>ParticleControllerRenderer</code></a> which will render particles
as <a href="../../../../../com/badlogic/gdx/graphics/g3d/ModelInstance.html" title="class in com.badlogic.gdx.graphics.g3d"><code>ModelInstance</code></a> to a <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/batches/ModelInstanceParticleBatch.html" title="class in com.badlogic.gdx.graphics.g3d.particles.batches"><code>ModelInstanceParticleBatch</code></a>.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/renderers/ParticleControllerControllerRenderer.html" title="class in com.badlogic.gdx.graphics.g3d.particles.renderers">ParticleControllerControllerRenderer</a></span></code>
<div class="block">A <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/renderers/ParticleControllerRenderer.html" title="class in com.badlogic.gdx.graphics.g3d.particles.renderers"><code>ParticleControllerRenderer</code></a> which will render the <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/ParticleController.html" title="class in com.badlogic.gdx.graphics.g3d.particles"><code>ParticleController</code></a> of each particle.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/renderers/ParticleControllerRenderer.html" title="class in com.badlogic.gdx.graphics.g3d.particles.renderers">ParticleControllerRenderer</a><D extends <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/renderers/ParticleControllerRenderData.html" title="class in com.badlogic.gdx.graphics.g3d.particles.renderers">ParticleControllerRenderData</a>,T extends <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/batches/ParticleBatch.html" title="interface in com.badlogic.gdx.graphics.g3d.particles.batches">ParticleBatch</a><D>></span></code>
<div class="block">It's a <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/ParticleControllerComponent.html" title="class in com.badlogic.gdx.graphics.g3d.particles"><code>ParticleControllerComponent</code></a> which determines how the particles are rendered.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/renderers/PointSpriteRenderer.html" title="class in com.badlogic.gdx.graphics.g3d.particles.renderers">PointSpriteRenderer</a></span></code>
<div class="block">A <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/renderers/ParticleControllerRenderer.html" title="class in com.badlogic.gdx.graphics.g3d.particles.renderers"><code>ParticleControllerRenderer</code></a> which will render particles as point sprites to a <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/batches/PointSpriteParticleBatch.html" title="class in com.badlogic.gdx.graphics.g3d.particles.batches"><code>PointSpriteParticleBatch</code></a> .</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.badlogic.gdx.graphics.g3d.particles.values">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../com/badlogic/gdx/utils/Json.Serializable.html" title="interface in com.badlogic.gdx.utils">Json.Serializable</a> in <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/values/package-summary.html">com.badlogic.gdx.graphics.g3d.particles.values</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/values/package-summary.html">com.badlogic.gdx.graphics.g3d.particles.values</a> that implement <a href="../../../../../com/badlogic/gdx/utils/Json.Serializable.html" title="interface in com.badlogic.gdx.utils">Json.Serializable</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/values/CylinderSpawnShapeValue.html" title="class in com.badlogic.gdx.graphics.g3d.particles.values">CylinderSpawnShapeValue</a></span></code>
<div class="block">Encapsulate the formulas to spawn a particle on a cylinder shape.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/values/EllipseSpawnShapeValue.html" title="class in com.badlogic.gdx.graphics.g3d.particles.values">EllipseSpawnShapeValue</a></span></code>
<div class="block">Encapsulate the formulas to spawn a particle on a ellipse shape.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/values/GradientColorValue.html" title="class in com.badlogic.gdx.graphics.g3d.particles.values">GradientColorValue</a></span></code>
<div class="block">Defines a variation of red, green and blue on a given time line.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/values/LineSpawnShapeValue.html" title="class in com.badlogic.gdx.graphics.g3d.particles.values">LineSpawnShapeValue</a></span></code>
<div class="block">Encapsulate the formulas to spawn a particle on a line shape.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/values/MeshSpawnShapeValue.html" title="class in com.badlogic.gdx.graphics.g3d.particles.values">MeshSpawnShapeValue</a></span></code>
<div class="block">The base class of all the <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/values/ParticleValue.html" title="class in com.badlogic.gdx.graphics.g3d.particles.values"><code>ParticleValue</code></a> values which spawn a particle on a mesh shape.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/values/NumericValue.html" title="class in com.badlogic.gdx.graphics.g3d.particles.values">NumericValue</a></span></code>
<div class="block">A value which contains a single float variable.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/values/ParticleValue.html" title="class in com.badlogic.gdx.graphics.g3d.particles.values">ParticleValue</a></span></code>
<div class="block">It's a class which represents a value bound to the particles.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/values/PointSpawnShapeValue.html" title="class in com.badlogic.gdx.graphics.g3d.particles.values">PointSpawnShapeValue</a></span></code>
<div class="block">Encapsulate the formulas to spawn a particle on a point shape.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/values/PrimitiveSpawnShapeValue.html" title="class in com.badlogic.gdx.graphics.g3d.particles.values">PrimitiveSpawnShapeValue</a></span></code>
<div class="block">The base class of all the <a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/values/SpawnShapeValue.html" title="class in com.badlogic.gdx.graphics.g3d.particles.values"><code>SpawnShapeValue</code></a> values which spawn the
particles on a geometric primitive.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/values/RangedNumericValue.html" title="class in com.badlogic.gdx.graphics.g3d.particles.values">RangedNumericValue</a></span></code>
<div class="block">A value which has a defined minimum and maximum bounds.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/values/RectangleSpawnShapeValue.html" title="class in com.badlogic.gdx.graphics.g3d.particles.values">RectangleSpawnShapeValue</a></span></code>
<div class="block">Encapsulate the formulas to spawn a particle on a rectangle shape.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/values/ScaledNumericValue.html" title="class in com.badlogic.gdx.graphics.g3d.particles.values">ScaledNumericValue</a></span></code>
<div class="block">A value which has a defined minimum and maximum upper and lower bounds.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/values/SpawnShapeValue.html" title="class in com.badlogic.gdx.graphics.g3d.particles.values">SpawnShapeValue</a></span></code>
<div class="block">Encapsulate the formulas to spawn a particle on a shape.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/values/UnweightedMeshSpawnShapeValue.html" title="class in com.badlogic.gdx.graphics.g3d.particles.values">UnweightedMeshSpawnShapeValue</a></span></code>
<div class="block">Encapsulate the formulas to spawn a particle on a mesh shape.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/badlogic/gdx/graphics/g3d/particles/values/WeightMeshSpawnShapeValue.html" title="class in com.badlogic.gdx.graphics.g3d.particles.values">WeightMeshSpawnShapeValue</a></span></code>
<div class="block">Encapsulate the formulas to spawn a particle on a mesh shape dealing
with not uniform area triangles.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../com/badlogic/gdx/utils/Json.Serializable.html" title="interface in com.badlogic.gdx.utils">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">libgdx API</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/badlogic/gdx/utils/class-use/Json.Serializable.html" target="_top">Frames</a></li>
<li><a href="Json.Serializable.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<div style="font-size:9pt"><i>
Copyright © 2010-2013 Mario Zechner ([email protected]), Nathan Sweet ([email protected])
</i></div>
</small></p>
</body>
</html>
|
apache-2.0
|
MatrixFrog/closure-compiler
|
src/com/google/javascript/jscomp/Es6RewriteDestructuring.java
|
19873
|
/*
* Copyright 2015 The Closure Compiler Authors.
*
* 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.google.javascript.jscomp;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.javascript.jscomp.Es6ToEs3Util.makeIterator;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.JSDocInfoBuilder;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import com.google.javascript.rhino.TokenStream;
/**
* Rewrites ES6 destructuring patterns and default parameters to valid ES3 code.
*/
public final class Es6RewriteDestructuring implements NodeTraversal.Callback, HotSwapCompilerPass {
private final AbstractCompiler compiler;
static final String DESTRUCTURING_TEMP_VAR = "$jscomp$destructuring$var";
private int destructuringVarCounter = 0;
public Es6RewriteDestructuring(AbstractCompiler compiler) {
this.compiler = compiler;
}
@Override
public void process(Node externs, Node root) {
TranspilationPasses.processTranspile(compiler, externs, this);
TranspilationPasses.processTranspile(compiler, root, this);
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
TranspilationPasses.hotSwapTranspile(compiler, scriptRoot, this);
}
@Override
public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
switch (n.getToken()) {
case FUNCTION:
visitFunction(t, n);
break;
case PARAM_LIST:
visitParamList(t, n, parent);
break;
case FOR_OF:
visitForOf(n);
break;
default:
break;
}
return true;
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (parent != null && parent.isDestructuringLhs()) {
parent = parent.getParent();
}
switch (n.getToken()) {
case ARRAY_PATTERN:
case OBJECT_PATTERN:
visitPattern(t, n, parent);
break;
default:
break;
}
}
/**
* If the function is an arrow function, wrap the body in a block if it is not already a block.
*/
private void visitFunction(NodeTraversal t, Node function) {
Node body = function.getLastChild();
if (!body.isNormalBlock()) {
body.detach();
Node replacement = IR.block(IR.returnNode(body)).useSourceInfoIfMissingFromForTree(body);
function.addChildToBack(replacement);
t.reportCodeChange();
}
}
/**
* Processes trailing default and rest parameters.
*/
private void visitParamList(NodeTraversal t, Node paramList, Node function) {
Node insertSpot = null;
Node body = function.getLastChild();
int i = 0;
Node next = null;
for (Node param = paramList.getFirstChild(); param != null; param = next, i++) {
next = param.getNext();
if (param.isDefaultValue()) {
JSDocInfo jsDoc = param.getJSDocInfo();
Node nameOrPattern = param.removeFirstChild();
Node defaultValue = param.removeFirstChild();
Node newParam;
// Treat name=undefined (and equivalent) as if it was just name. There
// is no need to generate a (name===void 0?void 0:name) statement for
// such arguments.
boolean isNoop = false;
if (!nameOrPattern.isName()) {
// Do not try to optimize unless nameOrPattern is a simple name.
} else if (defaultValue.isName()) {
isNoop = "undefined".equals(defaultValue.getString());
} else if (defaultValue.isVoid()) {
// Any kind of 'void literal' is fine, but 'void fun()' or anything
// else with side effects isn't. We're not trying to be particularly
// smart here and treat 'void {}' for example as if it could cause
// side effects. Any sane person will type 'name=undefined' or
// 'name=void 0' so this should not be an issue.
isNoop = NodeUtil.isImmutableValue(defaultValue.getFirstChild());
}
if (isNoop) {
newParam = nameOrPattern.cloneTree();
} else {
newParam =
nameOrPattern.isName()
? nameOrPattern
: IR.name(getTempParameterName(function, i));
Node lhs = nameOrPattern.cloneTree();
Node rhs = defaultValueHook(newParam.cloneTree(), defaultValue);
Node newStatement =
nameOrPattern.isName() ? IR.exprResult(IR.assign(lhs, rhs)) : IR.var(lhs, rhs);
newStatement.useSourceInfoIfMissingFromForTree(param);
body.addChildAfter(newStatement, insertSpot);
insertSpot = newStatement;
}
paramList.replaceChild(param, newParam);
newParam.setOptionalArg(true);
newParam.setJSDocInfo(jsDoc);
t.reportCodeChange();
} else if (param.isDestructuringPattern()) {
insertSpot =
replacePatternParamWithTempVar(
function, insertSpot, param, getTempParameterName(function, i));
t.reportCodeChange();
} else if (param.isRest() && param.getFirstChild().isDestructuringPattern()) {
insertSpot =
replacePatternParamWithTempVar(
function, insertSpot, param.getFirstChild(), getTempParameterName(function, i));
t.reportCodeChange();
}
}
}
/**
* Replace a destructuring pattern parameter with a a temporary parameter name and add a new
* local variable declaration to the function assigning the temporary parameter to the pattern.
*
* <p> Note: Rewrites of variable declaration destructuring will happen later to rewrite
* this declaration as non-destructured code.
* @param function
* @param insertSpot The local variable declaration will be inserted after this statement.
* @param patternParam
* @param tempVarName the name to use for the temporary variable
* @return the declaration statement that was generated for the local variable
*/
private Node replacePatternParamWithTempVar(
Node function, Node insertSpot, Node patternParam, String tempVarName) {
Node newParam = IR.name(tempVarName);
newParam.setJSDocInfo(patternParam.getJSDocInfo());
patternParam.replaceWith(newParam);
Node newDecl = IR.var(patternParam, IR.name(tempVarName));
function.getLastChild().addChildAfter(newDecl, insertSpot);
return newDecl;
}
/**
* Find or create the best name to use for a parameter we need to rewrite.
*
* <ol>
* <li> Use the JS Doc function parameter name at the given index, if possible.
* <li> Otherwise, build one of our own.
* </ol>
* @param function
* @param parameterIndex
* @return name to use for the given parameter
*/
private String getTempParameterName(Node function, int parameterIndex) {
String tempVarName;
JSDocInfo fnJSDoc = NodeUtil.getBestJSDocInfo(function);
if (fnJSDoc != null && fnJSDoc.getParameterNameAt(parameterIndex) != null) {
tempVarName = fnJSDoc.getParameterNameAt(parameterIndex);
} else {
tempVarName = DESTRUCTURING_TEMP_VAR + (destructuringVarCounter++);
}
checkState(TokenStream.isJSIdentifier(tempVarName));
return tempVarName;
}
private void visitForOf(Node node) {
Node lhs = node.getFirstChild();
if (lhs.isDestructuringLhs()) {
visitDestructuringPatternInEnhancedFor(lhs.getFirstChild());
}
}
private void visitPattern(NodeTraversal t, Node pattern, Node parent) {
if (NodeUtil.isNameDeclaration(parent) && !NodeUtil.isEnhancedFor(parent.getParent())) {
replacePattern(t, pattern, pattern.getNext(), parent, parent);
} else if (parent.isAssign()) {
if (parent.getParent().isExprResult()) {
replacePattern(t, pattern, pattern.getNext(), parent, parent.getParent());
} else {
wrapAssignmentInCallToArrow(t, parent);
}
} else if (parent.isRest()
|| parent.isStringKey()
|| parent.isArrayPattern()
|| parent.isDefaultValue()) {
// Nested pattern; do nothing. We will visit it after rewriting the parent.
} else if (NodeUtil.isEnhancedFor(parent) || NodeUtil.isEnhancedFor(parent.getParent())) {
visitDestructuringPatternInEnhancedFor(pattern);
} else if (parent.isCatch()) {
visitDestructuringPatternInCatch(pattern);
} else {
throw new IllegalStateException("unexpected parent");
}
}
private void replacePattern(
NodeTraversal t, Node pattern, Node rhs, Node parent, Node nodeToDetach) {
switch (pattern.getToken()) {
case ARRAY_PATTERN:
replaceArrayPattern(t, pattern, rhs, parent, nodeToDetach);
break;
case OBJECT_PATTERN:
replaceObjectPattern(t, pattern, rhs, parent, nodeToDetach);
break;
default:
throw new IllegalStateException("unexpected");
}
}
/**
* Convert 'var {a: b, c: d} = rhs' to:
*
* @const var temp = rhs; var b = temp.a; var d = temp.c;
*/
private void replaceObjectPattern(
NodeTraversal t, Node objectPattern, Node rhs, Node parent, Node nodeToDetach) {
String tempVarName = DESTRUCTURING_TEMP_VAR + (destructuringVarCounter++);
Node tempDecl = IR.var(IR.name(tempVarName), rhs.detach())
.useSourceInfoIfMissingFromForTree(objectPattern);
// TODO(tbreisacher): Remove the "if" and add this JSDoc unconditionally.
if (parent.isConst()) {
JSDocInfoBuilder jsDoc = new JSDocInfoBuilder(false);
jsDoc.recordConstancy();
tempDecl.setJSDocInfo(jsDoc.build());
}
nodeToDetach.getParent().addChildBefore(tempDecl, nodeToDetach);
for (Node child = objectPattern.getFirstChild(), next; child != null; child = next) {
next = child.getNext();
Node newLHS;
Node newRHS;
if (child.isStringKey()) {
if (!child.hasChildren()) { // converting shorthand
Node name = IR.name(child.getString());
name.useSourceInfoIfMissingFrom(child);
child.addChildToBack(name);
}
Node getprop =
new Node(
child.isQuotedString() ? Token.GETELEM : Token.GETPROP,
IR.name(tempVarName),
IR.string(child.getString()));
Node value = child.removeFirstChild();
if (!value.isDefaultValue()) {
newLHS = value;
newRHS = getprop;
} else {
newLHS = value.removeFirstChild();
Node defaultValue = value.removeFirstChild();
newRHS = defaultValueHook(getprop, defaultValue);
}
} else if (child.isComputedProp()) {
if (child.getLastChild().isDefaultValue()) {
newLHS = child.getLastChild().removeFirstChild();
Node getelem = IR.getelem(IR.name(tempVarName), child.removeFirstChild());
String intermediateTempVarName = DESTRUCTURING_TEMP_VAR + (destructuringVarCounter++);
Node intermediateDecl = IR.var(IR.name(intermediateTempVarName), getelem);
intermediateDecl.useSourceInfoIfMissingFromForTree(child);
nodeToDetach.getParent().addChildBefore(intermediateDecl, nodeToDetach);
newRHS =
defaultValueHook(
IR.name(intermediateTempVarName), child.getLastChild().removeFirstChild());
} else {
newRHS = IR.getelem(IR.name(tempVarName), child.removeFirstChild());
newLHS = child.removeFirstChild();
}
} else if (child.isDefaultValue()) {
newLHS = child.removeFirstChild();
Node defaultValue = child.removeFirstChild();
Node getprop = IR.getprop(IR.name(tempVarName), IR.string(newLHS.getString()));
newRHS = defaultValueHook(getprop, defaultValue);
} else {
throw new IllegalStateException("unexpected child");
}
Node newNode;
if (NodeUtil.isNameDeclaration(parent)) {
newNode = IR.declaration(newLHS, newRHS, parent.getToken());
} else if (parent.isAssign()) {
newNode = IR.exprResult(IR.assign(newLHS, newRHS));
} else {
throw new IllegalStateException("not reached");
}
newNode.useSourceInfoIfMissingFromForTree(child);
nodeToDetach.getParent().addChildBefore(newNode, nodeToDetach);
// Explicitly visit the LHS of the new node since it may be a nested
// destructuring pattern.
visit(t, newLHS, newLHS.getParent());
}
nodeToDetach.detach();
t.reportCodeChange();
}
/**
* Convert 'var [x, y] = rhs' to: var temp = $jscomp.makeIterator(rhs); var x = temp.next().value;
* var y = temp.next().value;
*/
private void replaceArrayPattern(
NodeTraversal t, Node arrayPattern, Node rhs, Node parent, Node nodeToDetach) {
String tempVarName = DESTRUCTURING_TEMP_VAR + (destructuringVarCounter++);
Node tempDecl = IR.var(
IR.name(tempVarName),
makeIterator(compiler, rhs.detach()));
tempDecl.useSourceInfoIfMissingFromForTree(arrayPattern);
nodeToDetach.getParent().addChildBefore(tempDecl, nodeToDetach);
boolean needsRuntime = false;
for (Node child = arrayPattern.getFirstChild(), next; child != null; child = next) {
next = child.getNext();
if (child.isEmpty()) {
// Just call the next() method to advance the iterator, but throw away the value.
Node nextCall = IR.exprResult(IR.call(IR.getprop(IR.name(tempVarName), IR.string("next"))));
nextCall.useSourceInfoIfMissingFromForTree(child);
nodeToDetach.getParent().addChildBefore(nextCall, nodeToDetach);
continue;
}
Node newLHS;
Node newRHS;
if (child.isDefaultValue()) {
// [x = defaultValue] = rhs;
// becomes
// var temp0 = $jscomp.makeIterator(rhs);
// var temp1 = temp.next().value
// x = (temp1 === undefined) ? defaultValue : temp1;
String nextVarName = DESTRUCTURING_TEMP_VAR + (destructuringVarCounter++);
Node var = IR.var(
IR.name(nextVarName),
IR.getprop(
IR.call(IR.getprop(IR.name(tempVarName), IR.string("next"))),
IR.string("value")));
var.useSourceInfoIfMissingFromForTree(child);
nodeToDetach.getParent().addChildBefore(var, nodeToDetach);
newLHS = child.getFirstChild().detach();
newRHS = defaultValueHook(IR.name(nextVarName), child.getLastChild().detach());
} else if (child.isRest()) {
// [...x] = rhs;
// becomes
// var temp = $jscomp.makeIterator(rhs);
// x = $jscomp.arrayFromIterator(temp);
newLHS = child.getFirstChild().detach();
newRHS =
IR.call(
NodeUtil.newQName(compiler, "$jscomp.arrayFromIterator"),
IR.name(tempVarName));
needsRuntime = true;
} else {
// LHS is just a name (or a nested pattern).
// var [x] = rhs;
// becomes
// var temp = $jscomp.makeIterator(rhs);
// var x = temp.next().value;
newLHS = child.detach();
newRHS = IR.getprop(
IR.call(IR.getprop(IR.name(tempVarName), IR.string("next"))),
IR.string("value"));
}
Node newNode;
if (parent.isAssign()) {
Node assignment = IR.assign(newLHS, newRHS);
newNode = IR.exprResult(assignment);
} else {
newNode = IR.declaration(newLHS, newRHS, parent.getToken());
}
newNode.useSourceInfoIfMissingFromForTree(arrayPattern);
nodeToDetach.getParent().addChildBefore(newNode, nodeToDetach);
// Explicitly visit the LHS of the new node since it may be a nested
// destructuring pattern.
visit(t, newLHS, newLHS.getParent());
}
nodeToDetach.detach();
if (needsRuntime) {
compiler.ensureLibraryInjected("es6/util/arrayfromiterator", false);
}
t.reportCodeChange();
}
/**
* Convert the assignment '[x, y] = rhs' that is used as an expression and not an expr result to:
* (() => let temp0 = rhs; var temp1 = $jscomp.makeIterator(temp0); var x = temp0.next().value;
* var y = temp0.next().value; return temp0; }) And the assignment '{x: a, y: b} = rhs' used as an
* expression and not an expr result to: (() => let temp0 = rhs; var temp1 = temp0; var a =
* temp0.x; var b = temp0.y; return temp0; })
*/
private void wrapAssignmentInCallToArrow(NodeTraversal t, Node assignment) {
String tempVarName = DESTRUCTURING_TEMP_VAR + (destructuringVarCounter++);
Node rhs = assignment.getLastChild().detach();
Node newAssignment = IR.let(IR.name(tempVarName), rhs);
Node replacementExpr = IR.assign(assignment.getFirstChild().detach(), IR.name(tempVarName));
Node exprResult = IR.exprResult(replacementExpr);
Node returnNode = IR.returnNode(IR.name(tempVarName));
Node block = IR.block(newAssignment, exprResult, returnNode);
Node call = IR.call(IR.arrowFunction(IR.name(""), IR.paramList(), block));
call.useSourceInfoIfMissingFromForTree(assignment);
call.putBooleanProp(Node.FREE_CALL, true);
assignment.getParent().replaceChild(assignment, call);
NodeUtil.markNewScopesChanged(call, compiler);
replacePattern(
t,
replacementExpr.getFirstChild(),
replacementExpr.getLastChild(),
replacementExpr,
exprResult);
}
private void visitDestructuringPatternInEnhancedFor(Node pattern) {
checkArgument(pattern.isDestructuringPattern());
String tempVarName = DESTRUCTURING_TEMP_VAR + (destructuringVarCounter++);
if (NodeUtil.isEnhancedFor(pattern.getParent())) {
Node forNode = pattern.getParent();
Node block = forNode.getLastChild();
Node decl = IR.var(IR.name(tempVarName));
decl.useSourceInfoIfMissingFromForTree(pattern);
forNode.replaceChild(pattern, decl);
Node exprResult = IR.exprResult(IR.assign(pattern, IR.name(tempVarName)));
exprResult.useSourceInfoIfMissingFromForTree(pattern);
block.addChildToFront(exprResult);
} else {
Node destructuringLhs = pattern.getParent();
checkState(destructuringLhs.isDestructuringLhs());
Node declarationNode = destructuringLhs.getParent();
Node forNode = declarationNode.getParent();
checkState(NodeUtil.isEnhancedFor(forNode));
Node block = forNode.getLastChild();
declarationNode.replaceChild(
destructuringLhs, IR.name(tempVarName).useSourceInfoFrom(pattern));
Token declarationType = declarationNode.getToken();
Node decl = IR.declaration(pattern.detach(), IR.name(tempVarName), declarationType);
decl.useSourceInfoIfMissingFromForTree(pattern);
block.addChildToFront(decl);
}
}
private void visitDestructuringPatternInCatch(Node pattern) {
String tempVarName = DESTRUCTURING_TEMP_VAR + (destructuringVarCounter++);
Node catchBlock = pattern.getNext();
pattern.replaceWith(IR.name(tempVarName));
catchBlock.addChildToFront(IR.declaration(pattern, IR.name(tempVarName), Token.LET));
}
/**
* Helper for transpiling DEFAULT_VALUE trees.
*/
private static Node defaultValueHook(Node getprop, Node defaultValue) {
return IR.hook(IR.sheq(getprop, IR.name("undefined")), defaultValue, getprop.cloneTree());
}
}
|
apache-2.0
|
oMMuCo/HPTT-FT-UGM-Official-Website
|
protected/controllers/ZonecityController.php
|
10950
|
<?php
/**
* ZonecityController
* @var $this ZonecityController
* @var $model OmmuZoneCity
* @var $form CActiveForm
* version: 1.1.0
* Reference start
*
* TOC :
* Index
* Suggest
* Manage
* Add
* Edit
* RunAction
* Delete
* Publish
*
* LoadModel
* performAjaxValidation
*
* @author Putra Sudaryanto <[email protected]>
* @copyright Copyright (c) 2015 Ommu Platform (ommu.co)
* @link https://github.com/oMMu/Ommu-Core
* @contect (+62)856-299-4114
*
*----------------------------------------------------------------------------------------------------------
*/
class ZonecityController extends Controller
{
/**
* @var string the default layout for the views. Defaults to '//layouts/column2', meaning
* using two-column layout. See 'protected/views/layouts/column2.php'.
*/
//public $layout='//layouts/column2';
public $defaultAction = 'index';
/**
* Initialize admin page theme
*/
public function init()
{
if(!Yii::app()->user->isGuest) {
if(Yii::app()->user->level == 1) {
$arrThemes = Utility::getCurrentTemplate('admin');
Yii::app()->theme = $arrThemes['folder'];
$this->layout = $arrThemes['layout'];
} else {
$this->redirect(Yii::app()->createUrl('site/login'));
}
} else {
$this->redirect(Yii::app()->createUrl('site/login'));
}
}
/**
* @return array action filters
*/
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
//'postOnly + delete', // we only allow deletion via POST request
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* @return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','suggest'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array(),
'users'=>array('@'),
'expression'=>'isset(Yii::app()->user->level)',
//'expression'=>'isset(Yii::app()->user->level) && (Yii::app()->user->level != 1)',
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('manage','add','edit','runaction','delete','publish'),
'users'=>array('@'),
'expression'=>'isset(Yii::app()->user->level) && (Yii::app()->user->level == 1)',
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array(),
'users'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
/**
* Lists all models.
*/
public function actionIndex()
{
$this->redirect(array('manage'));
}
/**
* Lists all models.
*/
public function actionSuggest($id=null)
{
if($id == null) {
if(isset($_GET['term'])) {
$criteria = new CDbCriteria;
$criteria->condition = 'city LIKE :city';
$criteria->select = "city_id, city";
$criteria->order = "city_id ASC";
$criteria->params = array(':city' => '%' . strtolower($_GET['term']) . '%');
$model = OmmuZoneCity::model()->findAll($criteria);
if($model) {
foreach($model as $items) {
$result[] = array('id' => $items->city_id, 'value' => $items->city);
}
}
}
echo CJSON::encode($result);
Yii::app()->end();
} else {
$model = OmmuZoneCity::getCity($id);
$message['data'] = '<option value="">'.Yii::t('phrase', 'Select one').'</option>';
foreach($model as $key => $val) {
$message['data'] .= '<option value="'.$key.'">'.$val.'</option>';
}
echo CJSON::encode($message);
}
}
/**
* Manages all models.
*/
public function actionManage()
{
$model=new OmmuZoneCity('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['OmmuZoneCity'])) {
$model->attributes=$_GET['OmmuZoneCity'];
}
$columnTemp = array();
if(isset($_GET['GridColumn'])) {
foreach($_GET['GridColumn'] as $key => $val) {
if($_GET['GridColumn'][$key] == 1) {
$columnTemp[] = $key;
}
}
}
$columns = $model->getGridColumn($columnTemp);
$this->pageTitle = 'Ommu Zone Cities Manage';
$this->pageDescription = '';
$this->pageMeta = '';
$this->render('/zone_city/admin_manage',array(
'model'=>$model,
'columns' => $columns,
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionAdd()
{
$model=new OmmuZoneCity;
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);
if(isset($_POST['OmmuZoneCity'])) {
$model->attributes=$_POST['OmmuZoneCity'];
$jsonError = CActiveForm::validate($model);
if(strlen($jsonError) > 2) {
echo $jsonError;
} else {
if(isset($_GET['enablesave']) && $_GET['enablesave'] == 1) {
if($model->save()) {
echo CJSON::encode(array(
'type' => 5,
'get' => Yii::app()->controller->createUrl('manage'),
'id' => 'partial-ommu-zone-city',
'msg' => '<div class="errorSummary success"><strong>OmmuZoneCity success created.</strong></div>',
));
} else {
print_r($model->getErrors());
}
}
}
Yii::app()->end();
} else {
$this->dialogDetail = true;
$this->dialogGroundUrl = Yii::app()->controller->createUrl('manage');
$this->dialogWidth = 600;
$this->pageTitle = 'Create Ommu Zone Cities';
$this->pageDescription = '';
$this->pageMeta = '';
$this->render('/zone_city/admin_add',array(
'model'=>$model,
));
}
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id the ID of the model to be updated
*/
public function actionEdit($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);
if(isset($_POST['OmmuZoneCity'])) {
$model->attributes=$_POST['OmmuZoneCity'];
$jsonError = CActiveForm::validate($model);
if(strlen($jsonError) > 2) {
echo $jsonError;
} else {
if(isset($_GET['enablesave']) && $_GET['enablesave'] == 1) {
if($model->save()) {
echo CJSON::encode(array(
'type' => 5,
'get' => Yii::app()->controller->createUrl('manage'),
'id' => 'partial-ommu-zone-city',
'msg' => '<div class="errorSummary success"><strong>OmmuZoneCity success updated.</strong></div>',
));
} else {
print_r($model->getErrors());
}
}
}
Yii::app()->end();
} else {
$this->dialogDetail = true;
$this->dialogGroundUrl = Yii::app()->controller->createUrl('manage');
$this->dialogWidth = 600;
$this->pageTitle = 'Update Ommu Zone Cities';
$this->pageDescription = '';
$this->pageMeta = '';
$this->render('/zone_city/admin_edit',array(
'model'=>$model,
));
}
}
/**
* Displays a particular model.
* @param integer $id the ID of the model to be displayed
*/
public function actionRunAction() {
$id = $_POST['trash_id'];
$criteria = null;
$actions = $_GET['action'];
if(count($id) > 0) {
$criteria = new CDbCriteria;
$criteria->addInCondition('id', $id);
if($actions == 'publish') {
OmmuZoneCity::model()->updateAll(array(
'publish' => 1,
),$criteria);
} elseif($actions == 'unpublish') {
OmmuZoneCity::model()->updateAll(array(
'publish' => 0,
),$criteria);
} elseif($actions == 'trash') {
OmmuZoneCity::model()->updateAll(array(
'publish' => 2,
),$criteria);
} elseif($actions == 'delete') {
OmmuZoneCity::model()->deleteAll($criteria);
}
}
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax'])) {
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('manage'));
}
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* @param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
$model=$this->loadModel($id);
if(Yii::app()->request->isPostRequest) {
// we only allow deletion via POST request
if(isset($id)) {
if($model->delete()) {
echo CJSON::encode(array(
'type' => 5,
'get' => Yii::app()->controller->createUrl('manage'),
'id' => 'partial-ommu-zone-city',
'msg' => '<div class="errorSummary success"><strong>OmmuZoneCity success deleted.</strong></div>',
));
}
}
} else {
$this->dialogDetail = true;
$this->dialogGroundUrl = Yii::app()->controller->createUrl('manage');
$this->dialogWidth = 350;
$this->pageTitle = 'OmmuZoneCity Delete.';
$this->pageDescription = '';
$this->pageMeta = '';
$this->render('/zone_city/admin_delete');
}
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* @param integer $id the ID of the model to be deleted
*/
public function actionPublish($id)
{
$model=$this->loadModel($id);
if($model->publish == 1) {
$title = Yii::t('phrase', 'Unpublish');
$replace = 0;
} else {
$title = Yii::t('phrase', 'Publish');
$replace = 1;
}
if(Yii::app()->request->isPostRequest) {
// we only allow deletion via POST request
if(isset($id)) {
//change value active or publish
$model->publish = $replace;
if($model->update()) {
echo CJSON::encode(array(
'type' => 5,
'get' => Yii::app()->controller->createUrl('manage'),
'id' => 'partial-ommu-zone-city',
'msg' => '<div class="errorSummary success"><strong>OmmuZoneCity success published.</strong></div>',
));
}
}
} else {
$this->dialogDetail = true;
$this->dialogGroundUrl = Yii::app()->controller->createUrl('manage');
$this->dialogWidth = 350;
$this->pageTitle = $title;
$this->pageDescription = '';
$this->pageMeta = '';
$this->render('/zone_city/admin_publish',array(
'title'=>$title,
'model'=>$model,
));
}
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* @param integer the ID of the model to be loaded
*/
public function loadModel($id)
{
$model = OmmuZoneCity::model()->findByPk($id);
if($model===null)
throw new CHttpException(404, Yii::t('phrase', 'The requested page does not exist.'));
return $model;
}
/**
* Performs the AJAX validation.
* @param CModel the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='ommu-zone-city-form') {
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
|
apache-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.