code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
#ifndef _TCUX11_HPP
#define _TCUX11_HPP
/*-------------------------------------------------------------------------
* drawElements Quality Program Tester Core
* ----------------------------------------
*
* Copyright 2014 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.
*
*//*!
* \file
* \brief X11 utilities.
*//*--------------------------------------------------------------------*/
#include "tcuDefs.hpp"
#include "gluRenderConfig.hpp"
#include "gluPlatform.hpp"
#include "deMutex.hpp"
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/keysym.h>
#include <X11/Xatom.h>
namespace tcu
{
namespace x11
{
enum
{
DEFAULT_WINDOW_WIDTH = 400,
DEFAULT_WINDOW_HEIGHT = 300
};
class EventState
{
public:
EventState (void);
virtual ~EventState (void);
void setQuitFlag (bool quit);
bool getQuitFlag (void);
protected:
de::Mutex m_mutex;
bool m_quit;
private:
EventState (const EventState&);
EventState& operator= (const EventState&);
};
class DisplayBase
{
public:
DisplayBase (EventState& platform);
virtual ~DisplayBase (void);
virtual void processEvents (void) = 0;
protected:
EventState& m_eventState;
private:
DisplayBase (const DisplayBase&);
DisplayBase& operator= (const DisplayBase&);
};
class WindowBase
{
public:
WindowBase (void);
virtual ~WindowBase (void);
virtual void setVisibility (bool visible) = 0;
virtual void processEvents (void) = 0;
virtual DisplayBase& getDisplay (void) = 0;
virtual void getDimensions (int* width, int* height) const = 0;
virtual void setDimensions (int width, int height) = 0;
protected:
bool m_visible;
private:
WindowBase (const WindowBase&);
WindowBase& operator= (const WindowBase&);
};
class XlibDisplay : public DisplayBase
{
public:
XlibDisplay (EventState& platform, const char* name);
virtual ~XlibDisplay (void);
::Display* getXDisplay (void) { return m_display; }
Atom getDeleteAtom (void) { return m_deleteAtom; }
::Visual* getVisual (VisualID visualID);
bool getVisualInfo (VisualID visualID, XVisualInfo& dst);
void processEvents (void);
void processEvent (XEvent& event);
protected:
::Display* m_display;
Atom m_deleteAtom;
private:
XlibDisplay (const XlibDisplay&);
XlibDisplay& operator= (const XlibDisplay&);
};
class XlibWindow : public WindowBase
{
public:
XlibWindow (XlibDisplay& display, int width, int height,
::Visual* visual);
~XlibWindow (void);
void setVisibility (bool visible);
void processEvents (void);
DisplayBase& getDisplay (void) { return (DisplayBase&)m_display; }
::Window& getXID (void) { return m_window; }
void getDimensions (int* width, int* height) const;
void setDimensions (int width, int height);
protected:
XlibDisplay& m_display;
::Colormap m_colormap;
::Window m_window;
private:
XlibWindow (const XlibWindow&);
XlibWindow& operator= (const XlibWindow&);
};
} // x11
} // tcu
#endif // _TCUX11_HPP
| Java |
/**
@author Admino Technologies Oy
Copyright 2013 Admino Technologies Oy. All rights reserved.
See LICENCE for conditions of distribution and use.
@file
@brief */
#pragma once
#include "CloudRenderingPluginApi.h"
#include "CloudRenderingPluginFwd.h"
#include "IModule.h"
class CLOUDRENDERING_API CloudRenderingPlugin : public IModule
{
Q_OBJECT
public:
CloudRenderingPlugin();
~CloudRenderingPlugin();
/// IModule override.
void Initialize();
/// IModule override.
void Uninitialize();
public slots:
WebRTCRendererPtr Renderer() const;
WebRTCClientPtr Client() const;
bool IsRenderer() const;
bool IsClient() const;
private:
QString LC;
WebRTCRendererPtr renderer_;
WebRTCClientPtr client_;
};
| Java |
/*
* 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.
*/
#include "data/constructs/column.h"
#include <string>
#include "data/constructs/inputvalidation.h"
namespace cclient {
namespace data {
void Column::setColFamily(const char *r, uint32_t size) {
columnFamily = std::string(r, size);
}
void Column::setColQualifier(const char *r, uint32_t size) {
columnQualifier = std::string(r, size);
}
void Column::setColVisibility(const char *r, uint32_t size) {
columnVisibility = std::string(r, size);
}
Column::~Column() {}
bool Column::operator<(const Column &rhs) const {
int compare =
compareBytes(columnFamily.data(), 0, columnFamily.size(),
rhs.columnFamily.data(), 0, rhs.columnFamily.size());
if (compare < 0)
return true;
else if (compare > 0)
return false;
;
compare =
compareBytes(columnQualifier.data(), 0, columnQualifier.size(),
rhs.columnQualifier.data(), 0, rhs.columnQualifier.size());
if (compare < 0)
return true;
else if (compare > 0)
return false;
compare =
compareBytes(columnVisibility.data(), 0, columnVisibility.size(),
rhs.columnVisibility.data(), 0, rhs.columnVisibility.size());
if (compare < 0) return true;
return false;
}
bool Column::operator==(const Column &rhs) const {
int compare =
compareBytes(columnFamily.data(), 0, columnFamily.size(),
rhs.columnFamily.data(), 0, rhs.columnFamily.size());
if (compare != 0) return false;
compare =
compareBytes(columnQualifier.data(), 0, columnQualifier.size(),
rhs.columnQualifier.data(), 0, rhs.columnQualifier.size());
if (compare != 0) return false;
compare =
compareBytes(columnVisibility.data(), 0, columnVisibility.size(),
rhs.columnVisibility.data(), 0, rhs.columnVisibility.size());
if (compare != 0)
return false;
else
return true;
}
uint64_t Column::write(cclient::data::streams::OutputStream *outStream) {
if (columnFamily.empty()) {
outStream->writeBoolean(false);
} else {
outStream->writeBoolean(true);
outStream->writeBytes(columnFamily.data(), columnFamily.size());
}
if (columnQualifier.empty()) {
outStream->writeBoolean(false);
} else {
outStream->writeBoolean(true);
outStream->writeBytes(columnQualifier.data(), columnQualifier.size());
}
if (columnVisibility.empty()) {
return outStream->writeBoolean(false);
} else {
outStream->writeBoolean(true);
return outStream->writeBytes(columnVisibility.data(),
columnVisibility.size());
}
}
} // namespace data
} // namespace cclient
| Java |
package me.knox.zmz.mvp.model;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import java.util.List;
import javax.inject.Inject;
import me.knox.zmz.App;
import me.knox.zmz.entity.News;
import me.knox.zmz.mvp.contract.NewsListContract;
import me.knox.zmz.network.JsonResponse;
/**
* Created by KNOX.
*/
public class NewsListModel implements NewsListContract.Model {
@Inject public NewsListModel() {
// empty constructor for injection
}
@Override public Flowable<JsonResponse<List<News>>> getNewsList() {
return App.getInstance().getApi().getNews().observeOn(AndroidSchedulers.mainThread(), true);
}
}
| Java |
/*
* Copyright 2022 Imply Data, 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.
*/
import { ESLintUtils } from '@typescript-eslint/utils';
import { readonlyImplicitFields } from './readonly-implicit-fields';
const ruleTester = new ESLintUtils.RuleTester({
parser: '@typescript-eslint/parser',
});
ruleTester.run('readonly-implicit-fields', readonlyImplicitFields, {
valid: [
// Various valid cases inside of Immutable Classes
`class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
public declare readonly foo: string;
private readonly baz: number;
public readonly qux: () => void;
public getBaz = () => this.baz;
public changeBaz = (baz: number) => this;
public doStuff(): string { return 'stuff'; }
}`,
`class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
declare readonly foo: string;
public declare readonly foo: string;
private declare readonly foo: string;
}`,
`class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
declare readonly getFoo: () => string;
public declare readonly getFoo: () => string;
private declare readonly getFoo: () => string;
}`,
`class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
declare readonly changeFoo: (foo: string) => MyClass;
public declare readonly changeFoo: (foo: string) => MyClass;
private declare readonly changeFoo: (foo: string) => MyClass;
}`,
// Invalid cases but not inside of BaseImmutable inheritors
`class MyClass extends NotImmutable {
declare foo: string;
}`,
`class MyClass extends NotImmutable {
public declare foo: string;
}`,
`class MyClass extends NotImmutable {
private declare foo: string;
}`,
],
invalid: [
{
code: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
public declare foo: string;
}`,
errors: [{ messageId: 'useReadonlyForProperty', line: 3, column: 11 }],
output: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
public declare readonly foo: string;
}`,
},
{
code: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
declare foo: string;
}`,
errors: [{ messageId: 'useReadonlyForProperty', line: 3, column: 11 }],
output: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
declare readonly foo: string;
}`,
},
{
code: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
private declare foo: string;
}`,
errors: [{ messageId: 'useReadonlyForProperty', line: 3, column: 11 }],
output: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
private declare readonly foo: string;
}`,
},
{
code: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
public declare getFoo: () => string;
}`,
errors: [{ messageId: 'useReadonlyForAccessor', line: 3, column: 11 }],
output: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
public declare readonly getFoo: () => string;
}`,
},
{
code: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
declare getFoo: () => string;
}`,
errors: [{ messageId: 'useReadonlyForAccessor', line: 3, column: 11 }],
output: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
declare readonly getFoo: () => string;
}`,
},
{
code: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
private declare getFoo: () => string;
}`,
errors: [{ messageId: 'useReadonlyForAccessor', line: 3, column: 11 }],
output: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
private declare readonly getFoo: () => string;
}`,
},
// Weird spacing
{
code: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
public
declare foo : string;
}`,
errors: [{ messageId: 'useReadonlyForProperty', line: 4, column: 13 }],
output: `
class MyClass extends BaseImmutable<MyClassValue, MyClassJS> {
public
declare readonly foo : string;
}`,
},
],
});
| Java |
// Copyright 2017 The Nomulus Authors. 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.
package google.registry.model.tld;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.equalTo;
import static com.google.common.base.Predicates.not;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.common.collect.Maps.toMap;
import static google.registry.config.RegistryConfig.getSingletonCacheRefreshDuration;
import static google.registry.model.common.EntityGroupRoot.getCrossTldKey;
import static google.registry.persistence.transaction.TransactionManagerFactory.tm;
import static google.registry.util.CollectionUtils.nullToEmptyImmutableCopy;
import static google.registry.util.DateTimeUtils.END_OF_TIME;
import static google.registry.util.DateTimeUtils.START_OF_TIME;
import static google.registry.util.PreconditionsUtils.checkArgumentNotNull;
import static org.joda.money.CurrencyUnit.USD;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;
import com.google.common.collect.Range;
import com.google.common.net.InternetDomainName;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.annotation.Embed;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Mapify;
import com.googlecode.objectify.annotation.OnSave;
import com.googlecode.objectify.annotation.Parent;
import google.registry.model.Buildable;
import google.registry.model.CreateAutoTimestamp;
import google.registry.model.ImmutableObject;
import google.registry.model.UnsafeSerializable;
import google.registry.model.annotations.InCrossTld;
import google.registry.model.annotations.ReportedOn;
import google.registry.model.common.EntityGroupRoot;
import google.registry.model.common.TimedTransitionProperty;
import google.registry.model.common.TimedTransitionProperty.TimedTransition;
import google.registry.model.domain.fee.BaseFee.FeeType;
import google.registry.model.domain.fee.Fee;
import google.registry.model.replay.DatastoreAndSqlEntity;
import google.registry.model.tld.label.PremiumList;
import google.registry.model.tld.label.ReservedList;
import google.registry.persistence.VKey;
import google.registry.persistence.converter.JodaMoneyType;
import google.registry.util.Idn;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
import javax.persistence.Column;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.PostLoad;
import javax.persistence.Transient;
import org.hibernate.annotations.Columns;
import org.hibernate.annotations.Type;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.joda.time.DateTime;
import org.joda.time.Duration;
/** Persisted per-TLD configuration data. */
@ReportedOn
@Entity
@javax.persistence.Entity(name = "Tld")
@InCrossTld
public class Registry extends ImmutableObject
implements Buildable, DatastoreAndSqlEntity, UnsafeSerializable {
@Parent @Transient Key<EntityGroupRoot> parent = getCrossTldKey();
/**
* The canonical string representation of the TLD associated with this {@link Registry}, which is
* the standard ASCII for regular TLDs and punycoded ASCII for IDN TLDs.
*/
@Id
@javax.persistence.Id
@Column(name = "tld_name", nullable = false)
String tldStrId;
/**
* A duplicate of {@link #tldStrId}, to simplify BigQuery reporting since the id field becomes
* {@code __key__.name} rather than being exported as a named field.
*/
@Transient String tldStr;
/** Sets the Datastore specific field, tldStr, when the entity is loaded from Cloud SQL */
@PostLoad
void postLoad() {
tldStr = tldStrId;
}
/** The suffix that identifies roids as belonging to this specific tld, e.g. -HOW for .how. */
String roidSuffix;
/** Default values for all the relevant TLD parameters. */
public static final TldState DEFAULT_TLD_STATE = TldState.PREDELEGATION;
public static final boolean DEFAULT_ESCROW_ENABLED = false;
public static final boolean DEFAULT_DNS_PAUSED = false;
public static final Duration DEFAULT_ADD_GRACE_PERIOD = Duration.standardDays(5);
public static final Duration DEFAULT_AUTO_RENEW_GRACE_PERIOD = Duration.standardDays(45);
public static final Duration DEFAULT_REDEMPTION_GRACE_PERIOD = Duration.standardDays(30);
public static final Duration DEFAULT_RENEW_GRACE_PERIOD = Duration.standardDays(5);
public static final Duration DEFAULT_TRANSFER_GRACE_PERIOD = Duration.standardDays(5);
public static final Duration DEFAULT_AUTOMATIC_TRANSFER_LENGTH = Duration.standardDays(5);
public static final Duration DEFAULT_PENDING_DELETE_LENGTH = Duration.standardDays(5);
public static final Duration DEFAULT_ANCHOR_TENANT_ADD_GRACE_PERIOD = Duration.standardDays(30);
public static final CurrencyUnit DEFAULT_CURRENCY = USD;
public static final Money DEFAULT_CREATE_BILLING_COST = Money.of(USD, 8);
public static final Money DEFAULT_EAP_BILLING_COST = Money.of(USD, 0);
public static final Money DEFAULT_RENEW_BILLING_COST = Money.of(USD, 8);
public static final Money DEFAULT_RESTORE_BILLING_COST = Money.of(USD, 100);
public static final Money DEFAULT_SERVER_STATUS_CHANGE_BILLING_COST = Money.of(USD, 20);
public static final Money DEFAULT_REGISTRY_LOCK_OR_UNLOCK_BILLING_COST = Money.of(USD, 0);
/** The type of TLD, which determines things like backups and escrow policy. */
public enum TldType {
/** A real, official TLD. */
REAL,
/** A test TLD, for the prober. */
TEST
}
/**
* The states a TLD can be in at any given point in time. The ordering below is the required
* sequence of states (ignoring {@link #PDT} which is a pseudo-state).
*/
public enum TldState {
/** The state of not yet being delegated to this registry in the root zone by IANA. */
PREDELEGATION,
/**
* The state in which only trademark holders can submit a "create" request. It is identical to
* {@link #GENERAL_AVAILABILITY} in all other respects.
*/
START_DATE_SUNRISE,
/**
* A state in which no domain operations are permitted. Generally used between sunrise and
* general availability. This state is special in that it has no ordering constraints and can
* appear after any phase.
*/
QUIET_PERIOD,
/**
* The steady state of a TLD in which all domain names are available via first-come,
* first-serve.
*/
GENERAL_AVAILABILITY,
/** A "fake" state for use in predelegation testing. Acts like {@link #GENERAL_AVAILABILITY}. */
PDT
}
/**
* A transition to a TLD state at a specific time, for use in a TimedTransitionProperty. Public
* because App Engine's security manager requires this for instantiation via reflection.
*/
@Embed
public static class TldStateTransition extends TimedTransition<TldState> {
/** The TLD state. */
private TldState tldState;
@Override
public TldState getValue() {
return tldState;
}
@Override
protected void setValue(TldState tldState) {
this.tldState = tldState;
}
}
/**
* A transition to a given billing cost at a specific time, for use in a TimedTransitionProperty.
*
* <p>Public because App Engine's security manager requires this for instantiation via reflection.
*/
@Embed
public static class BillingCostTransition extends TimedTransition<Money> {
/** The billing cost value. */
private Money billingCost;
@Override
public Money getValue() {
return billingCost;
}
@Override
protected void setValue(Money billingCost) {
this.billingCost = billingCost;
}
}
/** Returns the registry for a given TLD, throwing if none exists. */
public static Registry get(String tld) {
Registry registry = CACHE.getUnchecked(tld).orElse(null);
if (registry == null) {
throw new RegistryNotFoundException(tld);
}
return registry;
}
/** Returns the registry entities for the given TLD strings, throwing if any don't exist. */
static ImmutableSet<Registry> getAll(Set<String> tlds) {
try {
ImmutableMap<String, Optional<Registry>> registries = CACHE.getAll(tlds);
ImmutableSet<String> missingRegistries =
registries.entrySet().stream()
.filter(e -> !e.getValue().isPresent())
.map(Map.Entry::getKey)
.collect(toImmutableSet());
if (missingRegistries.isEmpty()) {
return registries.values().stream().map(Optional::get).collect(toImmutableSet());
} else {
throw new RegistryNotFoundException(missingRegistries);
}
} catch (ExecutionException e) {
throw new RuntimeException("Unexpected error retrieving TLDs " + tlds, e);
}
}
/**
* Invalidates the cache entry.
*
* <p>This is called automatically when the registry is saved. One should also call it when a
* registry is deleted.
*/
@OnSave
public void invalidateInCache() {
CACHE.invalidate(tldStr);
}
/** A cache that loads the {@link Registry} for a given tld. */
private static final LoadingCache<String, Optional<Registry>> CACHE =
CacheBuilder.newBuilder()
.expireAfterWrite(
java.time.Duration.ofMillis(getSingletonCacheRefreshDuration().getMillis()))
.build(
new CacheLoader<String, Optional<Registry>>() {
@Override
public Optional<Registry> load(final String tld) {
// Enter a transaction-less context briefly; we don't want to enroll every TLD in
// a transaction that might be wrapping this call.
return tm().doTransactionless(() -> tm().loadByKeyIfPresent(createVKey(tld)));
}
@Override
public Map<String, Optional<Registry>> loadAll(Iterable<? extends String> tlds) {
ImmutableMap<String, VKey<Registry>> keysMap =
toMap(ImmutableSet.copyOf(tlds), Registry::createVKey);
Map<VKey<? extends Registry>, Registry> entities =
tm().doTransactionless(() -> tm().loadByKeys(keysMap.values()));
return Maps.transformEntries(
keysMap, (k, v) -> Optional.ofNullable(entities.getOrDefault(v, null)));
}
});
public static VKey<Registry> createVKey(String tld) {
return VKey.create(Registry.class, tld, Key.create(getCrossTldKey(), Registry.class, tld));
}
public static VKey<Registry> createVKey(Key<Registry> key) {
return createVKey(key.getName());
}
/**
* The name of the pricing engine that this TLD uses.
*
* <p>This must be a valid key for the map of pricing engines injected by {@code @Inject
* Map<String, PricingEngine>}.
*
* <p>Note that it used to be the canonical class name, hence the name of this field, but this
* restriction has since been relaxed and it may now be any unique string.
*/
String pricingEngineClassName;
/**
* The set of name(s) of the {@code DnsWriter} implementations that this TLD uses.
*
* <p>There must be at least one entry in this set.
*
* <p>All entries of this list must be valid keys for the map of {@code DnsWriter}s injected by
* {@code @Inject Map<String, DnsWriter>}
*/
@Column(nullable = false)
Set<String> dnsWriters;
/**
* The number of locks we allow at once for {@link google.registry.dns.PublishDnsUpdatesAction}.
*
* <p>This should always be a positive integer- use 1 for TLD-wide locks. All {@link Registry}
* objects have this value default to 1.
*
* <p>WARNING: changing this parameter changes the lock name for subsequent DNS updates, and thus
* invalidates the locking scheme for enqueued DNS publish updates. If the {@link
* google.registry.dns.writer.DnsWriter} you use is not parallel-write tolerant, you must follow
* this procedure to change this value:
*
* <ol>
* <li>Pause the DNS queue via {@link google.registry.tools.UpdateTldCommand}
* <li>Change this number
* <li>Let the Registry caches expire (currently 5 minutes) and drain the DNS publish queue
* <li>Unpause the DNS queue
* </ol>
*
* <p>Failure to do so can result in parallel writes to the {@link
* google.registry.dns.writer.DnsWriter}, which may be dangerous depending on your implementation.
*/
@Column(nullable = false)
int numDnsPublishLocks;
/** Updates an unset numDnsPublishLocks (0) to the standard default of 1. */
void setDefaultNumDnsPublishLocks() {
if (numDnsPublishLocks == 0) {
numDnsPublishLocks = 1;
}
}
/**
* The unicode-aware representation of the TLD associated with this {@link Registry}.
*
* <p>This will be equal to {@link #tldStr} for ASCII TLDs, but will be non-ASCII for IDN TLDs. We
* store this in a field so that it will be retained upon import into BigQuery.
*/
@Column(nullable = false)
String tldUnicode;
/**
* Id of the folder in drive used to public (export) information for this TLD.
*
* <p>This is optional; if not configured, then information won't be exported for this TLD.
*/
@Nullable String driveFolderId;
/** The type of the TLD, whether it's real or for testing. */
@Column(nullable = false)
@Enumerated(EnumType.STRING)
TldType tldType = TldType.REAL;
/**
* Whether to enable invoicing for this TLD.
*
* <p>Note that this boolean is the sole determiner on whether invoices should be generated for a
* TLD. This applies to {@link TldType#TEST} TLDs as well.
*/
@Column(nullable = false)
boolean invoicingEnabled = false;
/**
* A property that transitions to different TldStates at different times. Stored as a list of
* TldStateTransition embedded objects using the @Mapify annotation.
*/
@Column(nullable = false)
@Mapify(TimedTransitionProperty.TimeMapper.class)
TimedTransitionProperty<TldState, TldStateTransition> tldStateTransitions =
TimedTransitionProperty.forMapify(DEFAULT_TLD_STATE, TldStateTransition.class);
/** An automatically managed creation timestamp. */
@Column(nullable = false)
CreateAutoTimestamp creationTime = CreateAutoTimestamp.create(null);
/** The set of reserved list names that are applicable to this registry. */
@Column(name = "reserved_list_names")
Set<String> reservedListNames;
/**
* Retrieves an ImmutableSet of all ReservedLists associated with this TLD.
*
* <p>This set contains only the names of the list and not a reference to the lists. Updates to a
* reserved list in Cloud SQL are saved as a new ReservedList entity. When using the ReservedList
* for a registry, the database should be queried for the entity with this name that has the
* largest revision ID.
*/
public ImmutableSet<String> getReservedListNames() {
return nullToEmptyImmutableCopy(reservedListNames);
}
/**
* The name of the {@link PremiumList} for this TLD, if there is one.
*
* <p>This is only the name of the list and not a reference to the list. Updates to the premium
* list in Cloud SQL are saved as a new PremiumList entity. When using the PremiumList for a
* registry, the database should be queried for the entity with this name that has the largest
* revision ID.
*/
@Column(name = "premium_list_name", nullable = true)
String premiumListName;
/** Should RDE upload a nightly escrow deposit for this TLD? */
@Column(nullable = false)
boolean escrowEnabled = DEFAULT_ESCROW_ENABLED;
/** Whether the pull queue that writes to authoritative DNS is paused for this TLD. */
@Column(nullable = false)
boolean dnsPaused = DEFAULT_DNS_PAUSED;
/**
* The length of the add grace period for this TLD.
*
* <p>Domain deletes are free and effective immediately so long as they take place within this
* amount of time following creation.
*/
@Column(nullable = false)
Duration addGracePeriodLength = DEFAULT_ADD_GRACE_PERIOD;
/** The length of the anchor tenant add grace period for this TLD. */
@Column(nullable = false)
Duration anchorTenantAddGracePeriodLength = DEFAULT_ANCHOR_TENANT_ADD_GRACE_PERIOD;
/** The length of the auto renew grace period for this TLD. */
@Column(nullable = false)
Duration autoRenewGracePeriodLength = DEFAULT_AUTO_RENEW_GRACE_PERIOD;
/** The length of the redemption grace period for this TLD. */
@Column(nullable = false)
Duration redemptionGracePeriodLength = DEFAULT_REDEMPTION_GRACE_PERIOD;
/** The length of the renew grace period for this TLD. */
@Column(nullable = false)
Duration renewGracePeriodLength = DEFAULT_RENEW_GRACE_PERIOD;
/** The length of the transfer grace period for this TLD. */
@Column(nullable = false)
Duration transferGracePeriodLength = DEFAULT_TRANSFER_GRACE_PERIOD;
/** The length of time before a transfer is automatically approved for this TLD. */
@Column(nullable = false)
Duration automaticTransferLength = DEFAULT_AUTOMATIC_TRANSFER_LENGTH;
/** The length of time a domain spends in the non-redeemable pending delete phase for this TLD. */
@Column(nullable = false)
Duration pendingDeleteLength = DEFAULT_PENDING_DELETE_LENGTH;
/** The currency unit for all costs associated with this TLD. */
@Column(nullable = false)
CurrencyUnit currency = DEFAULT_CURRENCY;
/** The per-year billing cost for registering a new domain name. */
@Type(type = JodaMoneyType.TYPE_NAME)
@Columns(
columns = {
@Column(name = "create_billing_cost_amount"),
@Column(name = "create_billing_cost_currency")
})
Money createBillingCost = DEFAULT_CREATE_BILLING_COST;
/** The one-time billing cost for restoring a domain name from the redemption grace period. */
@Type(type = JodaMoneyType.TYPE_NAME)
@Columns(
columns = {
@Column(name = "restore_billing_cost_amount"),
@Column(name = "restore_billing_cost_currency")
})
Money restoreBillingCost = DEFAULT_RESTORE_BILLING_COST;
/** The one-time billing cost for changing the server status (i.e. lock). */
@Type(type = JodaMoneyType.TYPE_NAME)
@Columns(
columns = {
@Column(name = "server_status_change_billing_cost_amount"),
@Column(name = "server_status_change_billing_cost_currency")
})
Money serverStatusChangeBillingCost = DEFAULT_SERVER_STATUS_CHANGE_BILLING_COST;
/** The one-time billing cost for a registry lock/unlock action initiated by a registrar. */
@Type(type = JodaMoneyType.TYPE_NAME)
@Columns(
columns = {
@Column(name = "registry_lock_or_unlock_cost_amount"),
@Column(name = "registry_lock_or_unlock_cost_currency")
})
Money registryLockOrUnlockBillingCost = DEFAULT_REGISTRY_LOCK_OR_UNLOCK_BILLING_COST;
/**
* A property that transitions to different renew billing costs at different times. Stored as a
* list of BillingCostTransition embedded objects using the @Mapify annotation.
*
* <p>A given value of this property represents the per-year billing cost for renewing a domain
* name. This cost is also used to compute costs for transfers, since each transfer includes a
* renewal to ensure transfers have a cost.
*/
@Column(nullable = false)
@Mapify(TimedTransitionProperty.TimeMapper.class)
TimedTransitionProperty<Money, BillingCostTransition> renewBillingCostTransitions =
TimedTransitionProperty.forMapify(DEFAULT_RENEW_BILLING_COST, BillingCostTransition.class);
/** A property that tracks the EAP fee schedule (if any) for the TLD. */
@Column(nullable = false)
@Mapify(TimedTransitionProperty.TimeMapper.class)
TimedTransitionProperty<Money, BillingCostTransition> eapFeeSchedule =
TimedTransitionProperty.forMapify(DEFAULT_EAP_BILLING_COST, BillingCostTransition.class);
/** Marksdb LORDN service username (password is stored in Keyring) */
String lordnUsername;
/** The end of the claims period (at or after this time, claims no longer applies). */
@Column(nullable = false)
DateTime claimsPeriodEnd = END_OF_TIME;
/** An allow list of clients allowed to be used on domains on this TLD (ignored if empty). */
@Nullable Set<String> allowedRegistrantContactIds;
/** An allow list of hosts allowed to be used on domains on this TLD (ignored if empty). */
@Nullable Set<String> allowedFullyQualifiedHostNames;
public String getTldStr() {
return tldStr;
}
public String getRoidSuffix() {
return roidSuffix;
}
/** Retrieve the actual domain name representing the TLD for which this registry operates. */
public InternetDomainName getTld() {
return InternetDomainName.from(tldStr);
}
/** Retrieve the TLD type (real or test). */
public TldType getTldType() {
return tldType;
}
/**
* Retrieve the TLD state at the given time. Defaults to {@link TldState#PREDELEGATION}.
*
* <p>Note that {@link TldState#PDT} TLDs pretend to be in {@link TldState#GENERAL_AVAILABILITY}.
*/
public TldState getTldState(DateTime now) {
TldState state = tldStateTransitions.getValueAtTime(now);
return TldState.PDT.equals(state) ? TldState.GENERAL_AVAILABILITY : state;
}
/** Retrieve whether this TLD is in predelegation testing. */
public boolean isPdt(DateTime now) {
return TldState.PDT.equals(tldStateTransitions.getValueAtTime(now));
}
public DateTime getCreationTime() {
return creationTime.getTimestamp();
}
public boolean getEscrowEnabled() {
return escrowEnabled;
}
public boolean getDnsPaused() {
return dnsPaused;
}
public String getDriveFolderId() {
return driveFolderId;
}
public Duration getAddGracePeriodLength() {
return addGracePeriodLength;
}
public Duration getAutoRenewGracePeriodLength() {
return autoRenewGracePeriodLength;
}
public Duration getRedemptionGracePeriodLength() {
return redemptionGracePeriodLength;
}
public Duration getRenewGracePeriodLength() {
return renewGracePeriodLength;
}
public Duration getTransferGracePeriodLength() {
return transferGracePeriodLength;
}
public Duration getAutomaticTransferLength() {
return automaticTransferLength;
}
public Duration getPendingDeleteLength() {
return pendingDeleteLength;
}
public Duration getAnchorTenantAddGracePeriodLength() {
return anchorTenantAddGracePeriodLength;
}
public Optional<String> getPremiumListName() {
return Optional.ofNullable(premiumListName);
}
public CurrencyUnit getCurrency() {
return currency;
}
/**
* Use <code>PricingEngineProxy.getDomainCreateCost</code> instead of this to find the cost for a
* domain create.
*/
@VisibleForTesting
public Money getStandardCreateCost() {
return createBillingCost;
}
/**
* Returns the add-on cost of a domain restore (the flat registry-wide fee charged in addition to
* one year of renewal for that name).
*/
public Money getStandardRestoreCost() {
return restoreBillingCost;
}
/**
* Use <code>PricingEngineProxy.getDomainRenewCost</code> instead of this to find the cost for a
* domain renewal, and all derived costs (i.e. autorenews, transfers, and the per-domain part of a
* restore cost).
*/
public Money getStandardRenewCost(DateTime now) {
return renewBillingCostTransitions.getValueAtTime(now);
}
/** Returns the cost of a server status change (i.e. lock). */
public Money getServerStatusChangeCost() {
return serverStatusChangeBillingCost;
}
/** Returns the cost of a registry lock/unlock. */
public Money getRegistryLockOrUnlockBillingCost() {
return registryLockOrUnlockBillingCost;
}
public ImmutableSortedMap<DateTime, TldState> getTldStateTransitions() {
return tldStateTransitions.toValueMap();
}
public ImmutableSortedMap<DateTime, Money> getRenewBillingCostTransitions() {
return renewBillingCostTransitions.toValueMap();
}
/** Returns the EAP fee for the registry at the given time. */
public Fee getEapFeeFor(DateTime now) {
ImmutableSortedMap<DateTime, Money> valueMap = getEapFeeScheduleAsMap();
DateTime periodStart = valueMap.floorKey(now);
DateTime periodEnd = valueMap.ceilingKey(now);
// NOTE: assuming END_OF_TIME would never be reached...
Range<DateTime> validPeriod =
Range.closedOpen(
periodStart != null ? periodStart : START_OF_TIME,
periodEnd != null ? periodEnd : END_OF_TIME);
return Fee.create(
eapFeeSchedule.getValueAtTime(now).getAmount(),
FeeType.EAP,
// An EAP fee does not count as premium -- it's a separate one-time fee, independent of
// which the domain is separately considered standard vs premium depending on renewal price.
false,
validPeriod,
validPeriod.upperEndpoint());
}
@VisibleForTesting
public ImmutableSortedMap<DateTime, Money> getEapFeeScheduleAsMap() {
return eapFeeSchedule.toValueMap();
}
public String getLordnUsername() {
return lordnUsername;
}
public DateTime getClaimsPeriodEnd() {
return claimsPeriodEnd;
}
public String getPremiumPricingEngineClassName() {
return pricingEngineClassName;
}
public ImmutableSet<String> getDnsWriters() {
return ImmutableSet.copyOf(dnsWriters);
}
/** Returns the number of simultaneous DNS publish operations we allow at once. */
public int getNumDnsPublishLocks() {
return numDnsPublishLocks;
}
public ImmutableSet<String> getAllowedRegistrantContactIds() {
return nullToEmptyImmutableCopy(allowedRegistrantContactIds);
}
public ImmutableSet<String> getAllowedFullyQualifiedHostNames() {
return nullToEmptyImmutableCopy(allowedFullyQualifiedHostNames);
}
@Override
public Builder asBuilder() {
return new Builder(clone(this));
}
/** A builder for constructing {@link Registry} objects, since they are immutable. */
public static class Builder extends Buildable.Builder<Registry> {
public Builder() {}
private Builder(Registry instance) {
super(instance);
}
public Builder setTldType(TldType tldType) {
getInstance().tldType = tldType;
return this;
}
public Builder setInvoicingEnabled(boolean invoicingEnabled) {
getInstance().invoicingEnabled = invoicingEnabled;
return this;
}
/** Sets the TLD state to transition to the specified states at the specified times. */
public Builder setTldStateTransitions(ImmutableSortedMap<DateTime, TldState> tldStatesMap) {
checkNotNull(tldStatesMap, "TLD states map cannot be null");
// Filter out any entries with QUIET_PERIOD as the value before checking for ordering, since
// that phase is allowed to appear anywhere.
checkArgument(
Ordering.natural()
.isStrictlyOrdered(
Iterables.filter(tldStatesMap.values(), not(equalTo(TldState.QUIET_PERIOD)))),
"The TLD states are chronologically out of order");
getInstance().tldStateTransitions =
TimedTransitionProperty.fromValueMap(tldStatesMap, TldStateTransition.class);
return this;
}
public Builder setTldStr(String tldStr) {
checkArgument(tldStr != null, "TLD must not be null");
getInstance().tldStr = tldStr;
return this;
}
public Builder setEscrowEnabled(boolean enabled) {
getInstance().escrowEnabled = enabled;
return this;
}
public Builder setDnsPaused(boolean paused) {
getInstance().dnsPaused = paused;
return this;
}
public Builder setDriveFolderId(String driveFolderId) {
getInstance().driveFolderId = driveFolderId;
return this;
}
public Builder setPremiumPricingEngine(String pricingEngineClass) {
getInstance().pricingEngineClassName = checkArgumentNotNull(pricingEngineClass);
return this;
}
public Builder setDnsWriters(ImmutableSet<String> dnsWriters) {
getInstance().dnsWriters = dnsWriters;
return this;
}
public Builder setNumDnsPublishLocks(int numDnsPublishLocks) {
checkArgument(
numDnsPublishLocks > 0,
"numDnsPublishLocks must be positive when set explicitly (use 1 for TLD-wide locks)");
getInstance().numDnsPublishLocks = numDnsPublishLocks;
return this;
}
public Builder setAddGracePeriodLength(Duration addGracePeriodLength) {
checkArgument(
addGracePeriodLength.isLongerThan(Duration.ZERO),
"addGracePeriodLength must be non-zero");
getInstance().addGracePeriodLength = addGracePeriodLength;
return this;
}
/** Warning! Changing this will affect the billing time of autorenew events in the past. */
public Builder setAutoRenewGracePeriodLength(Duration autoRenewGracePeriodLength) {
checkArgument(
autoRenewGracePeriodLength.isLongerThan(Duration.ZERO),
"autoRenewGracePeriodLength must be non-zero");
getInstance().autoRenewGracePeriodLength = autoRenewGracePeriodLength;
return this;
}
public Builder setRedemptionGracePeriodLength(Duration redemptionGracePeriodLength) {
checkArgument(
redemptionGracePeriodLength.isLongerThan(Duration.ZERO),
"redemptionGracePeriodLength must be non-zero");
getInstance().redemptionGracePeriodLength = redemptionGracePeriodLength;
return this;
}
public Builder setRenewGracePeriodLength(Duration renewGracePeriodLength) {
checkArgument(
renewGracePeriodLength.isLongerThan(Duration.ZERO),
"renewGracePeriodLength must be non-zero");
getInstance().renewGracePeriodLength = renewGracePeriodLength;
return this;
}
public Builder setTransferGracePeriodLength(Duration transferGracePeriodLength) {
checkArgument(
transferGracePeriodLength.isLongerThan(Duration.ZERO),
"transferGracePeriodLength must be non-zero");
getInstance().transferGracePeriodLength = transferGracePeriodLength;
return this;
}
public Builder setAutomaticTransferLength(Duration automaticTransferLength) {
checkArgument(
automaticTransferLength.isLongerThan(Duration.ZERO),
"automaticTransferLength must be non-zero");
getInstance().automaticTransferLength = automaticTransferLength;
return this;
}
public Builder setPendingDeleteLength(Duration pendingDeleteLength) {
checkArgument(
pendingDeleteLength.isLongerThan(Duration.ZERO), "pendingDeleteLength must be non-zero");
getInstance().pendingDeleteLength = pendingDeleteLength;
return this;
}
public Builder setCurrency(CurrencyUnit currency) {
checkArgument(currency != null, "currency must be non-null");
getInstance().currency = currency;
return this;
}
public Builder setCreateBillingCost(Money amount) {
checkArgument(amount.isPositiveOrZero(), "createBillingCost cannot be negative");
getInstance().createBillingCost = amount;
return this;
}
public Builder setReservedListsByName(Set<String> reservedListNames) {
checkArgument(reservedListNames != null, "reservedListNames must not be null");
ImmutableSet.Builder<ReservedList> builder = new ImmutableSet.Builder<>();
for (String reservedListName : reservedListNames) {
// Check for existence of the reserved list and throw an exception if it doesn't exist.
Optional<ReservedList> reservedList = ReservedList.get(reservedListName);
checkArgument(
reservedList.isPresent(),
"Could not find reserved list %s to add to the tld",
reservedListName);
builder.add(reservedList.get());
}
return setReservedLists(builder.build());
}
public Builder setReservedLists(ReservedList... reservedLists) {
return setReservedLists(ImmutableSet.copyOf(reservedLists));
}
public Builder setReservedLists(Set<ReservedList> reservedLists) {
checkArgumentNotNull(reservedLists, "reservedLists must not be null");
ImmutableSet.Builder<String> nameBuilder = new ImmutableSet.Builder<>();
for (ReservedList reservedList : reservedLists) {
nameBuilder.add(reservedList.getName());
}
getInstance().reservedListNames = nameBuilder.build();
return this;
}
public Builder setPremiumList(@Nullable PremiumList premiumList) {
getInstance().premiumListName = (premiumList == null) ? null : premiumList.getName();
return this;
}
public Builder setRestoreBillingCost(Money amount) {
checkArgument(amount.isPositiveOrZero(), "restoreBillingCost cannot be negative");
getInstance().restoreBillingCost = amount;
return this;
}
/**
* Sets the renew billing cost to transition to the specified values at the specified times.
*
* <p>Renew billing costs transitions should only be added at least 5 days (the length of an
* automatic transfer) in advance, to avoid discrepancies between the cost stored with the
* billing event (created when the transfer is requested) and the cost at the time when the
* transfer actually occurs (5 days later).
*/
public Builder setRenewBillingCostTransitions(
ImmutableSortedMap<DateTime, Money> renewCostsMap) {
checkArgumentNotNull(renewCostsMap, "Renew billing costs map cannot be null");
checkArgument(
renewCostsMap.values().stream().allMatch(Money::isPositiveOrZero),
"Renew billing cost cannot be negative");
getInstance().renewBillingCostTransitions =
TimedTransitionProperty.fromValueMap(renewCostsMap, BillingCostTransition.class);
return this;
}
/** Sets the EAP fee schedule for the TLD. */
public Builder setEapFeeSchedule(ImmutableSortedMap<DateTime, Money> eapFeeSchedule) {
checkArgumentNotNull(eapFeeSchedule, "EAP schedule map cannot be null");
checkArgument(
eapFeeSchedule.values().stream().allMatch(Money::isPositiveOrZero),
"EAP fee cannot be negative");
getInstance().eapFeeSchedule =
TimedTransitionProperty.fromValueMap(eapFeeSchedule, BillingCostTransition.class);
return this;
}
private static final Pattern ROID_SUFFIX_PATTERN = Pattern.compile("^[A-Z0-9_]{1,8}$");
public Builder setRoidSuffix(String roidSuffix) {
checkArgument(
ROID_SUFFIX_PATTERN.matcher(roidSuffix).matches(),
"ROID suffix must be in format %s",
ROID_SUFFIX_PATTERN.pattern());
getInstance().roidSuffix = roidSuffix;
return this;
}
public Builder setServerStatusChangeBillingCost(Money amount) {
checkArgument(
amount.isPositiveOrZero(), "Server status change billing cost cannot be negative");
getInstance().serverStatusChangeBillingCost = amount;
return this;
}
public Builder setRegistryLockOrUnlockBillingCost(Money amount) {
checkArgument(amount.isPositiveOrZero(), "Registry lock/unlock cost cannot be negative");
getInstance().registryLockOrUnlockBillingCost = amount;
return this;
}
public Builder setLordnUsername(String username) {
getInstance().lordnUsername = username;
return this;
}
public Builder setClaimsPeriodEnd(DateTime claimsPeriodEnd) {
getInstance().claimsPeriodEnd = checkArgumentNotNull(claimsPeriodEnd);
return this;
}
public Builder setAllowedRegistrantContactIds(
ImmutableSet<String> allowedRegistrantContactIds) {
getInstance().allowedRegistrantContactIds = allowedRegistrantContactIds;
return this;
}
public Builder setAllowedFullyQualifiedHostNames(
ImmutableSet<String> allowedFullyQualifiedHostNames) {
getInstance().allowedFullyQualifiedHostNames = allowedFullyQualifiedHostNames;
return this;
}
@Override
public Registry build() {
final Registry instance = getInstance();
// Pick up the name of the associated TLD from the instance object.
String tldName = instance.tldStr;
checkArgument(tldName != null, "No registry TLD specified");
// Check for canonical form by converting to an InternetDomainName and then back.
checkArgument(
InternetDomainName.isValid(tldName)
&& tldName.equals(InternetDomainName.from(tldName).toString()),
"Cannot create registry for TLD that is not a valid, canonical domain name");
// Check the validity of all TimedTransitionProperties to ensure that they have values for
// START_OF_TIME. The setters above have already checked this for new values, but also check
// here to catch cases where we loaded an invalid TimedTransitionProperty from Datastore and
// cloned it into a new builder, to block re-building a Registry in an invalid state.
instance.tldStateTransitions.checkValidity();
instance.renewBillingCostTransitions.checkValidity();
instance.eapFeeSchedule.checkValidity();
// All costs must be in the expected currency.
// TODO(b/21854155): When we move PremiumList into Datastore, verify its currency too.
checkArgument(
instance.getStandardCreateCost().getCurrencyUnit().equals(instance.currency),
"Create cost must be in the registry's currency");
checkArgument(
instance.getStandardRestoreCost().getCurrencyUnit().equals(instance.currency),
"Restore cost must be in the registry's currency");
checkArgument(
instance.getServerStatusChangeCost().getCurrencyUnit().equals(instance.currency),
"Server status change cost must be in the registry's currency");
checkArgument(
instance.getRegistryLockOrUnlockBillingCost().getCurrencyUnit().equals(instance.currency),
"Registry lock/unlock cost must be in the registry's currency");
Predicate<Money> currencyCheck =
(Money money) -> money.getCurrencyUnit().equals(instance.currency);
checkArgument(
instance.getRenewBillingCostTransitions().values().stream().allMatch(currencyCheck),
"Renew cost must be in the registry's currency");
checkArgument(
instance.eapFeeSchedule.toValueMap().values().stream().allMatch(currencyCheck),
"All EAP fees must be in the registry's currency");
checkArgumentNotNull(
instance.pricingEngineClassName, "All registries must have a configured pricing engine");
checkArgument(
instance.dnsWriters != null && !instance.dnsWriters.isEmpty(),
"At least one DNS writer must be specified."
+ " VoidDnsWriter can be used if DNS writing isn't desired");
// If not set explicitly, numDnsPublishLocks defaults to 1.
instance.setDefaultNumDnsPublishLocks();
checkArgument(
instance.numDnsPublishLocks > 0,
"Number of DNS publish locks must be positive. Use 1 for TLD-wide locks.");
instance.tldStrId = tldName;
instance.tldUnicode = Idn.toUnicode(tldName);
return super.build();
}
}
/** Exception to throw when no Registry entity is found for given TLD string(s). */
public static class RegistryNotFoundException extends RuntimeException {
RegistryNotFoundException(ImmutableSet<String> tlds) {
super("No registry object(s) found for " + Joiner.on(", ").join(tlds));
}
RegistryNotFoundException(String tld) {
this(ImmutableSet.of(tld));
}
}
}
| Java |
import java.util.Scanner;
/**
* @author Oleg Cherednik
* @since 27.10.2017
*/
public class Solution {
static int[] leftRotation(int[] a, int d) {
for (int i = 0, j = a.length - 1; i < j; i++, j--)
swap(a, i, j);
d %= a.length;
if (d > 0) {
d = a.length - d;
for (int i = 0, j = d - 1; i < j; i++, j--)
swap(a, i, j);
for (int i = d, j = a.length - 1; i < j; i++, j--)
swap(a, i, j);
}
return a;
}
private static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int d = in.nextInt();
int[] a = new int[n];
for (int a_i = 0; a_i < n; a_i++) {
a[a_i] = in.nextInt();
}
int[] result = leftRotation(a, d);
for (int i = 0; i < result.length; i++) {
System.out.print(result[i] + (i != result.length - 1 ? " " : ""));
}
System.out.println("");
in.close();
}
}
| Java |
package com.pmis.manage.dao;
import org.springframework.stereotype.Component;
import com.pmis.common.dao.CommonDao;
@Component
public class UserInfoDao extends CommonDao{
}
| Java |
/**
* Licensed to Odiago, Inc. under one or more contributor license
* agreements. See the NOTICE.txt file distributed with this work for
* additional information regarding copyright ownership. Odiago, Inc.
* 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.odiago.flumebase.lang;
import java.util.Collections;
import java.util.List;
/**
* Abstract base class that defines a callable function. Subclasses
* of this exist for scalar, aggregate, and table functions.
*/
public abstract class Function {
/**
* @return the Type of the object returned by the function.
*/
public abstract Type getReturnType();
/**
* @return an ordered list containing the types expected for all mandatory arguments.
*/
public abstract List<Type> getArgumentTypes();
/**
* @return an ordered list containing types expected for variable argument lists.
* If a function takes a variable-length argument list, the varargs must be arranged
* in groups matching the size of the list returned by this method. e.g., to accept
* an arbitrary number of strings, this should return a singleton list of type STRING.
* If pairs of strings and ints are required, this should return a list [STRING, INT].
*/
public List<Type> getVarArgTypes() {
return Collections.emptyList();
}
/**
* Determines whether arguments are promoted to their specified types by
* the runtime. If this returns true, actual arguments are promoted to
* new values that match the types specified in getArgumentTypes().
* If false, the expressions are simply type-checked to ensure that there
* is a valid promotion, but are passed in as-is. The default value of
* this method is true.
*/
public boolean autoPromoteArguments() {
return true;
}
}
| Java |
/**
* Copyright 2016 Netflix, 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 io.reactivex.internal.operators.maybe;
import io.reactivex.*;
import io.reactivex.disposables.Disposable;
import io.reactivex.internal.disposables.DisposableHelper;
/**
* Turns an onSuccess into an onComplete, onError and onComplete is relayed as is.
*
* @param <T> the value type
*/
public final class MaybeIgnoreElement<T> extends AbstractMaybeWithUpstream<T, T> {
public MaybeIgnoreElement(MaybeSource<T> source) {
super(source);
}
@Override
protected void subscribeActual(MaybeObserver<? super T> observer) {
source.subscribe(new IgnoreMaybeObserver<T>(observer));
}
static final class IgnoreMaybeObserver<T> implements MaybeObserver<T>, Disposable {
final MaybeObserver<? super T> actual;
Disposable d;
IgnoreMaybeObserver(MaybeObserver<? super T> actual) {
this.actual = actual;
}
@Override
public void onSubscribe(Disposable d) {
if (DisposableHelper.validate(this.d, d)) {
this.d = d;
actual.onSubscribe(this);
}
}
@Override
public void onSuccess(T value) {
d = DisposableHelper.DISPOSED;
actual.onComplete();
}
@Override
public void onError(Throwable e) {
d = DisposableHelper.DISPOSED;
actual.onError(e);
}
@Override
public void onComplete() {
d = DisposableHelper.DISPOSED;
actual.onComplete();
}
@Override
public boolean isDisposed() {
return d.isDisposed();
}
@Override
public void dispose() {
d.dispose();
d = DisposableHelper.DISPOSED;
}
}
}
| Java |
// Copyright 2020 The Knative 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 service
import (
"testing"
"gotest.tools/v3/assert"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
k8sfake "k8s.io/client-go/kubernetes/fake"
"knative.dev/kperf/pkg"
"knative.dev/kperf/pkg/testutil"
servingv1client "knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1"
servingv1fake "knative.dev/serving/pkg/client/clientset/versioned/typed/serving/v1/fake"
)
func TestCleanServicesFunc(t *testing.T) {
tests := []struct {
name string
cleanArgs pkg.CleanArgs
}{
{
name: "should clean services in namespace",
cleanArgs: pkg.CleanArgs{
Namespace: "test-kperf-1",
},
},
{
name: "should clean services in namespace range",
cleanArgs: pkg.CleanArgs{
NamespacePrefix: "test-kperf",
NamespaceRange: "1,2",
},
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
ns := &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: "test-kperf-1",
},
}
client := k8sfake.NewSimpleClientset(ns)
fakeServing := &servingv1fake.FakeServingV1{Fake: &client.Fake}
servingClient := func() (servingv1client.ServingV1Interface, error) {
return fakeServing, nil
}
p := &pkg.PerfParams{
ClientSet: client,
NewServingClient: servingClient,
}
err := CleanServices(p, tc.cleanArgs)
assert.NilError(t, err)
})
}
}
func TestNewServiceCleanCommand(t *testing.T) {
t.Run("incompleted or wrong args for service clean", func(t *testing.T) {
client := k8sfake.NewSimpleClientset()
fakeServing := &servingv1fake.FakeServingV1{Fake: &client.Fake}
servingClient := func() (servingv1client.ServingV1Interface, error) {
return fakeServing, nil
}
p := &pkg.PerfParams{
ClientSet: client,
NewServingClient: servingClient,
}
cmd := NewServiceCleanCommand(p)
_, err := testutil.ExecuteCommand(cmd)
assert.ErrorContains(t, err, "both namespace and namespace-prefix are empty")
_, err = testutil.ExecuteCommand(cmd, "--namespace-prefix", "test-kperf-1", "--namespace-range", "2,1")
assert.ErrorContains(t, err, "failed to parse namespace range 2,1")
_, err = testutil.ExecuteCommand(cmd, "--namespace-prefix", "test-kperf", "--namespace-range", "x,y")
assert.ErrorContains(t, err, "strconv.Atoi: parsing \"x\": invalid syntax")
_, err = testutil.ExecuteCommand(cmd, "--namespace-prefix", "test-kperf", "--namespace-range", "1,y")
assert.ErrorContains(t, err, "strconv.Atoi: parsing \"y\": invalid syntax")
_, err = testutil.ExecuteCommand(cmd, "--namespace-prefix", "test-kperf", "--namespace-range", "1")
assert.ErrorContains(t, err, "expected range like 1,500, given 1")
_, err = testutil.ExecuteCommand(cmd, "--namespace-prefix", "test-kperf-1", "--namespace-range", "1,2")
assert.ErrorContains(t, err, "no namespace found with prefix test-kperf-1")
})
t.Run("clean service as expected", func(t *testing.T) {
ns := &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: "test-kperf-1",
},
}
client := k8sfake.NewSimpleClientset(ns)
fakeServing := &servingv1fake.FakeServingV1{Fake: &client.Fake}
servingClient := func() (servingv1client.ServingV1Interface, error) {
return fakeServing, nil
}
p := &pkg.PerfParams{
ClientSet: client,
NewServingClient: servingClient,
}
cmd := NewServiceCleanCommand(p)
_, err := testutil.ExecuteCommand(cmd, "--namespace", "test-kperf-1")
assert.NilError(t, err)
_, err = testutil.ExecuteCommand(cmd, "--namespace-prefix", "test-kperf", "--namespace-range", "1,2")
assert.NilError(t, err)
})
t.Run("failed to clean services", func(t *testing.T) {
ns := &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: "test-kperf-2",
},
}
client := k8sfake.NewSimpleClientset(ns)
fakeServing := &servingv1fake.FakeServingV1{Fake: &client.Fake}
servingClient := func() (servingv1client.ServingV1Interface, error) {
return fakeServing, nil
}
p := &pkg.PerfParams{
ClientSet: client,
NewServingClient: servingClient,
}
cmd := NewServiceCleanCommand(p)
_, err := testutil.ExecuteCommand(cmd, "--namespace", "test-kperf-1")
assert.ErrorContains(t, err, "namespaces \"test-kperf-1\" not found")
cmd = NewServiceCleanCommand(p)
_, err = testutil.ExecuteCommand(cmd, "--namespace-prefix", "test-kperf-1", "--namespace-range", "1,2")
assert.ErrorContains(t, err, "no namespace found with prefix test-kperf-1")
})
t.Run("clean generated ksvc with namespace flag", func(t *testing.T) {
ns := &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: "test-kperf-prefix-1",
},
}
client := k8sfake.NewSimpleClientset(ns)
fakeServing := &servingv1fake.FakeServingV1{Fake: &client.Fake}
servingClient := func() (servingv1client.ServingV1Interface, error) {
return fakeServing, nil
}
p := &pkg.PerfParams{
ClientSet: client,
NewServingClient: servingClient,
}
cmd := NewServiceCleanCommand(p)
_, err := testutil.ExecuteCommand(cmd, "--namespace", "test-kperf-prefix-1", "--svc-prefix", "test-ksvc")
assert.NilError(t, err)
})
}
| Java |
/*
* Copyright 2014–2018 SlamData 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 quasar.frontend.logicalplan
import slamdata.Predef._
import quasar.{Data, Func}
import quasar.DataGenerators._
import quasar.fp._
import quasar.std
import matryoshka._
import matryoshka.data.Fix
import org.scalacheck._
import org.specs2.scalaz.{ScalazMatchers, Spec}
import scalaz._, Scalaz._
import scalaz.scalacheck.ScalazProperties.{equal => _, _}
import pathy.Path._
class LogicalPlanSpecs extends Spec with ScalazMatchers {
val lpf = new LogicalPlanR[Fix[LogicalPlan]]
implicit val arbLogicalPlan: Delay[Arbitrary, LogicalPlan] =
new Delay[Arbitrary, LogicalPlan] {
def apply[A](arb: Arbitrary[A]) =
Arbitrary {
Gen.oneOf(readGen[A], addGen(arb), constGen[A], letGen(arb), freeGen[A](Nil))
}
}
// Switch this to parameterize over Funcs as well
def addGen[A: Arbitrary]: Gen[LogicalPlan[A]] = for {
l <- Arbitrary.arbitrary[A]
r <- Arbitrary.arbitrary[A]
} yield Invoke(std.MathLib.Add, Func.Input2(l, r))
def letGen[A: Arbitrary]: Gen[LogicalPlan[A]] = for {
n <- Gen.choose(0, 1000)
(form, body) <- Arbitrary.arbitrary[(A, A)]
} yield let(Symbol("tmp" + n), form, body)
def readGen[A]: Gen[LogicalPlan[A]] = Gen.const(read(rootDir </> file("foo")))
def constGen[A]: Gen[LogicalPlan[A]] = for {
data <- Arbitrary.arbitrary[Data]
} yield constant(data)
def freeGen[A](vars: List[Symbol]): Gen[LogicalPlan[A]] = for {
n <- Gen.choose(0, 1000)
} yield free(Symbol("tmp" + n))
implicit val arbIntLP = arbLogicalPlan(Arbitrary.arbInt)
checkAll(traverse.laws[LogicalPlan])
import quasar.std.StdLib._, relations._, quasar.std.StdLib.set._, structural._, math._
"normalizeTempNames" should {
"rename simple nested lets" in {
lpf.normalizeTempNames(
lpf.let('foo, lpf.read(file("foo")),
lpf.let('bar, lpf.read(file("bar")),
Fix(MakeMapN(
lpf.constant(Data.Str("x")) -> Fix(MapProject(lpf.free('foo), lpf.constant(Data.Str("x")))),
lpf.constant(Data.Str("y")) -> Fix(MapProject(lpf.free('bar), lpf.constant(Data.Str("y"))))))))) must equal(
lpf.let('__tmp0, lpf.read(file("foo")),
lpf.let('__tmp1, lpf.read(file("bar")),
Fix(MakeMapN(
lpf.constant(Data.Str("x")) -> Fix(MapProject(lpf.free('__tmp0), lpf.constant(Data.Str("x")))),
lpf.constant(Data.Str("y")) -> Fix(MapProject(lpf.free('__tmp1), lpf.constant(Data.Str("y")))))))))
}
"rename shadowed name" in {
lpf.normalizeTempNames(
lpf.let('x, lpf.read(file("foo")),
lpf.let('x, Fix(MakeMapN(
lpf.constant(Data.Str("x")) -> Fix(MapProject(lpf.free('x), lpf.constant(Data.Str("x")))))),
lpf.free('x)))) must equal(
lpf.let('__tmp0, lpf.read(file("foo")),
lpf.let('__tmp1, Fix(MakeMapN(
lpf.constant(Data.Str("x")) -> Fix(MapProject(lpf.free('__tmp0), lpf.constant(Data.Str("x")))))),
lpf.free('__tmp1))))
}
}
"normalizeLets" should {
"re-nest" in {
lpf.normalizeLets(
lpf.let('bar,
lpf.let('foo,
lpf.read(file("foo")),
Fix(Filter(lpf.free('foo), Fix(Eq(Fix(MapProject(lpf.free('foo), lpf.constant(Data.Str("x")))), lpf.constant(Data.Str("z"))))))),
Fix(MakeMapN(
lpf.constant(Data.Str("y")) -> Fix(MapProject(lpf.free('bar), lpf.constant(Data.Str("y")))))))) must equal(
lpf.let('foo,
lpf.read(file("foo")),
lpf.let('bar,
Fix(Filter(lpf.free('foo), Fix(Eq(Fix(MapProject(lpf.free('foo), lpf.constant(Data.Str("x")))), lpf.constant(Data.Str("z")))))),
Fix(MakeMapN(
lpf.constant(Data.Str("y")) -> Fix(MapProject(lpf.free('bar), lpf.constant(Data.Str("y")))))))))
}
"re-nest deep" in {
lpf.normalizeLets(
lpf.let('baz,
lpf.let('bar,
lpf.let('foo,
lpf.read(file("foo")),
Fix(Filter(lpf.free('foo), Fix(Eq(Fix(MapProject(lpf.free('foo), lpf.constant(Data.Str("x")))), lpf.constant(Data.Int(0))))))),
Fix(Filter(lpf.free('bar), Fix(Eq(Fix(MapProject(lpf.free('foo), lpf.constant(Data.Str("y")))), lpf.constant(Data.Int(1))))))),
Fix(MakeMapN(
lpf.constant(Data.Str("z")) -> Fix(MapProject(lpf.free('bar), lpf.constant(Data.Str("z")))))))) must equal(
lpf.let('foo,
lpf.read(file("foo")),
lpf.let('bar,
Fix(Filter(lpf.free('foo), Fix(Eq(Fix(MapProject(lpf.free('foo), lpf.constant(Data.Str("x")))), lpf.constant(Data.Int(0)))))),
lpf.let('baz,
Fix(Filter(lpf.free('bar), Fix(Eq(Fix(MapProject(lpf.free('foo), lpf.constant(Data.Str("y")))), lpf.constant(Data.Int(1)))))),
Fix(MakeMapN(
lpf.constant(Data.Str("z")) -> Fix(MapProject(lpf.free('bar), lpf.constant(Data.Str("z"))))))))))
}
"hoist multiple Lets" in {
lpf.normalizeLets(
Fix(Add(
lpf.let('x, lpf.constant(Data.Int(0)), Fix(Add(lpf.free('x), lpf.constant(Data.Int(1))))),
lpf.let('y, lpf.constant(Data.Int(2)), Fix(Add(lpf.free('y), lpf.constant(Data.Int(3)))))))) must equal(
lpf.let('x, lpf.constant(Data.Int(0)),
lpf.let('y, lpf.constant(Data.Int(2)),
Fix(Add(
Fix(Add(lpf.free('x), lpf.constant(Data.Int(1)))),
Fix(Add(lpf.free('y), lpf.constant(Data.Int(3)))))))))
}
"hoist deep Let by one level" in {
lpf.normalizeLets(
Fix(Add(
lpf.constant(Data.Int(0)),
Fix(Add(
lpf.let('x, lpf.constant(Data.Int(1)), Fix(Add(lpf.free('x), lpf.constant(Data.Int(2))))),
lpf.constant(Data.Int(3))))))) must equal(
Fix(Add(
lpf.constant(Data.Int(0)),
lpf.let('x, lpf.constant(Data.Int(1)),
Fix(Add(
Fix(Add(lpf.free('x), lpf.constant(Data.Int(2)))),
lpf.constant(Data.Int(3))))))))
}
}
}
| Java |
package com.intellij.util.xml.impl;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.NullableFactory;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.XmlElementFactory;
import com.intellij.psi.xml.XmlDocument;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.xml.DomElement;
import com.intellij.util.xml.DomFileElement;
import com.intellij.util.xml.DomNameStrategy;
import com.intellij.util.xml.EvaluatedXmlName;
import com.intellij.util.xml.stubs.ElementStub;
import org.jetbrains.annotations.NonNls;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.List;
/**
* @author peter
*/
public class DomRootInvocationHandler extends DomInvocationHandler<AbstractDomChildDescriptionImpl, ElementStub> {
private static final Logger LOG = Logger.getInstance("#com.intellij.util.xml.impl.DomRootInvocationHandler");
private final DomFileElementImpl<?> myParent;
public DomRootInvocationHandler(final Class aClass,
final RootDomParentStrategy strategy,
@Nonnull final DomFileElementImpl fileElement,
@Nonnull final EvaluatedXmlName tagName,
@Nullable ElementStub stub
) {
super(aClass, strategy, tagName, new AbstractDomChildDescriptionImpl(aClass) {
@Nonnull
public List<? extends DomElement> getValues(@Nonnull final DomElement parent) {
throw new UnsupportedOperationException();
}
public int compareTo(final AbstractDomChildDescriptionImpl o) {
throw new UnsupportedOperationException();
}
}, fileElement.getManager(), true, stub);
myParent = fileElement;
}
public void undefineInternal() {
try {
final XmlTag tag = getXmlTag();
if (tag != null) {
deleteTag(tag);
detach();
fireUndefinedEvent();
}
}
catch (Exception e) {
LOG.error(e);
}
}
public boolean equals(final Object obj) {
if (!(obj instanceof DomRootInvocationHandler)) return false;
final DomRootInvocationHandler handler = (DomRootInvocationHandler)obj;
return myParent.equals(handler.myParent);
}
public int hashCode() {
return myParent.hashCode();
}
@Nonnull
public String getXmlElementNamespace() {
return getXmlName().getNamespace(getFile(), getFile());
}
@Override
protected String checkValidity() {
final XmlTag tag = (XmlTag)getXmlElement();
if (tag != null && !tag.isValid()) {
return "invalid root tag";
}
final String s = myParent.checkValidity();
if (s != null) {
return "root: " + s;
}
return null;
}
@Nonnull
public DomFileElementImpl getParent() {
return myParent;
}
public DomElement createPathStableCopy() {
final DomFileElement stableCopy = myParent.createStableCopy();
return getManager().createStableValue(new NullableFactory<DomElement>() {
public DomElement create() {
return stableCopy.isValid() ? stableCopy.getRootElement() : null;
}
});
}
protected XmlTag setEmptyXmlTag() {
final XmlTag[] result = new XmlTag[]{null};
getManager().runChange(new Runnable() {
public void run() {
try {
final String namespace = getXmlElementNamespace();
@NonNls final String nsDecl = StringUtil.isEmpty(namespace) ? "" : " xmlns=\"" + namespace + "\"";
final XmlFile xmlFile = getFile();
final XmlTag tag = XmlElementFactory.getInstance(xmlFile.getProject()).createTagFromText("<" + getXmlElementName() + nsDecl + "/>");
result[0] = ((XmlDocument)xmlFile.getDocument().replace(((XmlFile)tag.getContainingFile()).getDocument())).getRootTag();
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
});
return result[0];
}
@Nonnull
public final DomNameStrategy getNameStrategy() {
final Class<?> rawType = getRawType();
final DomNameStrategy strategy = DomImplUtil.getDomNameStrategy(rawType, isAttribute());
if (strategy != null) {
return strategy;
}
return DomNameStrategy.HYPHEN_STRATEGY;
}
}
| Java |
package org.consumersunion.stories.common.client.util;
public class CachedObjectKeys {
public static final String OPENED_CONTENT = "openedContent";
public static final String OPENED_STORY = "openedStory";
public static final String OPENED_COLLECTION = "openedCollection";
}
| Java |
#ifndef LOG_H
#define LOG_H
/*
* 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.
*/
#include <proton/import_export.h>
#include <proton/type_compat.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @cond INTERNAL
*/
/**
* @file
*
* Control log messages that are not associated with a transport.
* See pn_transport_trace for transport-related logging.
*/
/**
* Callback for customized logging.
*/
typedef void (*pn_logger_t)(const char *message);
/**
* Enable/disable global logging.
*
* By default, logging is enabled by environment variable PN_TRACE_LOG.
* Calling this function overrides the environment setting.
*/
PN_EXTERN void pn_log_enable(bool enabled);
/**
* Set the logger.
*
* By default a logger that prints to stderr is installed.
*
* @param logger is called with each log message if logging is enabled.
* Passing 0 disables logging regardless of pn_log_enable() or environment settings.
*/
PN_EXTERN void pn_log_logger(pn_logger_t logger);
/**
* @endcond
*/
#ifdef __cplusplus
}
#endif
#endif
| Java |
package dkalymbaev.triangle;
class Triangle {
/**
* This class defines points a b and c as peacks of triangle.
*/
public Point a;
public Point b;
public Point c;
/**
* Creating of a new objects.
* @param a is the length of the first side.
* @param b is the length of the second side.
* @param c is the length of the third side.
*/
public Triangle(Point a, Point b, Point c) {
this.a = a;
this.b = b;
this.c = c;
}
public double area() {
double ab = a.distanceTo(b);
double bc = b.distanceTo(c);
double ac = a.distanceTo(c);
double halfperim = ((ab + bc + ac) / 2);
double area = Math.sqrt(halfperim * (halfperim - ab) * (halfperim - bc) * (halfperim - ac));
if (ab > 0 && bc > 0 && ac > 0) {
return area;
} else {
return 0;
}
}
} | Java |
/*
* Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
* Copyright [2016-2019] EMBL-European Bioinformatics Institute
*
* 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.ensembl.healthcheck.util;
import java.util.HashMap;
import java.util.Map;
/**
* A default implementation of the {@link MapRowMapper} intended as an
* extension point to help when creating these call back objects. This version
* will return a HashMap of the given generic types.
*
* @author ayates
* @author dstaines
*/
public abstract class AbstractMapRowMapper<K, T> implements MapRowMapper<K, T>{
public Map<K, T> getMap() {
return new HashMap<K,T>();
}
}
| Java |
/**
* Created by plter on 6/13/16.
*/
(function () {
var files = ["hello.js", "app.js"];
files.forEach(function (file) {
var scriptTag = document.createElement("script");
scriptTag.async = false;
scriptTag.src = file;
document.body.appendChild(scriptTag);
});
}()); | Java |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>文件</title>
<meta name="generator" content="Org mode" />
<meta name="author" content="Wu, Shanliang" />
<style type="text/css">
<!--/*--><![CDATA[/*><!--*/
.title { text-align: center;
margin-bottom: .2em; }
.subtitle { text-align: center;
font-size: medium;
font-weight: bold;
margin-top:0; }
.todo { font-family: monospace; color: red; }
.done { font-family: monospace; color: green; }
.priority { font-family: monospace; color: orange; }
.tag { background-color: #eee; font-family: monospace;
padding: 2px; font-size: 80%; font-weight: normal; }
.timestamp { color: #bebebe; }
.timestamp-kwd { color: #5f9ea0; }
.org-right { margin-left: auto; margin-right: 0px; text-align: right; }
.org-left { margin-left: 0px; margin-right: auto; text-align: left; }
.org-center { margin-left: auto; margin-right: auto; text-align: center; }
.underline { text-decoration: underline; }
#postamble p, #preamble p { font-size: 90%; margin: .2em; }
p.verse { margin-left: 3%; }
pre {
border: 1px solid #ccc;
box-shadow: 3px 3px 3px #eee;
padding: 8pt;
font-family: monospace;
overflow: auto;
margin: 1.2em;
}
pre.src {
position: relative;
overflow: visible;
padding-top: 1.2em;
}
pre.src:before {
display: none;
position: absolute;
background-color: white;
top: -10px;
right: 10px;
padding: 3px;
border: 1px solid black;
}
pre.src:hover:before { display: inline;}
/* Languages per Org manual */
pre.src-asymptote:before { content: 'Asymptote'; }
pre.src-awk:before { content: 'Awk'; }
pre.src-C:before { content: 'C'; }
/* pre.src-C++ doesn't work in CSS */
pre.src-clojure:before { content: 'Clojure'; }
pre.src-css:before { content: 'CSS'; }
pre.src-D:before { content: 'D'; }
pre.src-ditaa:before { content: 'ditaa'; }
pre.src-dot:before { content: 'Graphviz'; }
pre.src-calc:before { content: 'Emacs Calc'; }
pre.src-emacs-lisp:before { content: 'Emacs Lisp'; }
pre.src-fortran:before { content: 'Fortran'; }
pre.src-gnuplot:before { content: 'gnuplot'; }
pre.src-haskell:before { content: 'Haskell'; }
pre.src-hledger:before { content: 'hledger'; }
pre.src-java:before { content: 'Java'; }
pre.src-js:before { content: 'Javascript'; }
pre.src-latex:before { content: 'LaTeX'; }
pre.src-ledger:before { content: 'Ledger'; }
pre.src-lisp:before { content: 'Lisp'; }
pre.src-lilypond:before { content: 'Lilypond'; }
pre.src-lua:before { content: 'Lua'; }
pre.src-matlab:before { content: 'MATLAB'; }
pre.src-mscgen:before { content: 'Mscgen'; }
pre.src-ocaml:before { content: 'Objective Caml'; }
pre.src-octave:before { content: 'Octave'; }
pre.src-org:before { content: 'Org mode'; }
pre.src-oz:before { content: 'OZ'; }
pre.src-plantuml:before { content: 'Plantuml'; }
pre.src-processing:before { content: 'Processing.js'; }
pre.src-python:before { content: 'Python'; }
pre.src-R:before { content: 'R'; }
pre.src-ruby:before { content: 'Ruby'; }
pre.src-sass:before { content: 'Sass'; }
pre.src-scheme:before { content: 'Scheme'; }
pre.src-screen:before { content: 'Gnu Screen'; }
pre.src-sed:before { content: 'Sed'; }
pre.src-sh:before { content: 'shell'; }
pre.src-sql:before { content: 'SQL'; }
pre.src-sqlite:before { content: 'SQLite'; }
/* additional languages in org.el's org-babel-load-languages alist */
pre.src-forth:before { content: 'Forth'; }
pre.src-io:before { content: 'IO'; }
pre.src-J:before { content: 'J'; }
pre.src-makefile:before { content: 'Makefile'; }
pre.src-maxima:before { content: 'Maxima'; }
pre.src-perl:before { content: 'Perl'; }
pre.src-picolisp:before { content: 'Pico Lisp'; }
pre.src-scala:before { content: 'Scala'; }
pre.src-shell:before { content: 'Shell Script'; }
pre.src-ebnf2ps:before { content: 'ebfn2ps'; }
/* additional language identifiers per "defun org-babel-execute"
in ob-*.el */
pre.src-cpp:before { content: 'C++'; }
pre.src-abc:before { content: 'ABC'; }
pre.src-coq:before { content: 'Coq'; }
pre.src-groovy:before { content: 'Groovy'; }
/* additional language identifiers from org-babel-shell-names in
ob-shell.el: ob-shell is the only babel language using a lambda to put
the execution function name together. */
pre.src-bash:before { content: 'bash'; }
pre.src-csh:before { content: 'csh'; }
pre.src-ash:before { content: 'ash'; }
pre.src-dash:before { content: 'dash'; }
pre.src-ksh:before { content: 'ksh'; }
pre.src-mksh:before { content: 'mksh'; }
pre.src-posh:before { content: 'posh'; }
/* Additional Emacs modes also supported by the LaTeX listings package */
pre.src-ada:before { content: 'Ada'; }
pre.src-asm:before { content: 'Assembler'; }
pre.src-caml:before { content: 'Caml'; }
pre.src-delphi:before { content: 'Delphi'; }
pre.src-html:before { content: 'HTML'; }
pre.src-idl:before { content: 'IDL'; }
pre.src-mercury:before { content: 'Mercury'; }
pre.src-metapost:before { content: 'MetaPost'; }
pre.src-modula-2:before { content: 'Modula-2'; }
pre.src-pascal:before { content: 'Pascal'; }
pre.src-ps:before { content: 'PostScript'; }
pre.src-prolog:before { content: 'Prolog'; }
pre.src-simula:before { content: 'Simula'; }
pre.src-tcl:before { content: 'tcl'; }
pre.src-tex:before { content: 'TeX'; }
pre.src-plain-tex:before { content: 'Plain TeX'; }
pre.src-verilog:before { content: 'Verilog'; }
pre.src-vhdl:before { content: 'VHDL'; }
pre.src-xml:before { content: 'XML'; }
pre.src-nxml:before { content: 'XML'; }
/* add a generic configuration mode; LaTeX export needs an additional
(add-to-list 'org-latex-listings-langs '(conf " ")) in .emacs */
pre.src-conf:before { content: 'Configuration File'; }
table { border-collapse:collapse; }
caption.t-above { caption-side: top; }
caption.t-bottom { caption-side: bottom; }
td, th { vertical-align:top; }
th.org-right { text-align: center; }
th.org-left { text-align: center; }
th.org-center { text-align: center; }
td.org-right { text-align: right; }
td.org-left { text-align: left; }
td.org-center { text-align: center; }
dt { font-weight: bold; }
.footpara { display: inline; }
.footdef { margin-bottom: 1em; }
.figure { padding: 1em; }
.figure p { text-align: center; }
.inlinetask {
padding: 10px;
border: 2px solid gray;
margin: 10px;
background: #ffffcc;
}
#org-div-home-and-up
{ text-align: right; font-size: 70%; white-space: nowrap; }
textarea { overflow-x: auto; }
.linenr { font-size: smaller }
.code-highlighted { background-color: #ffff00; }
.org-info-js_info-navigation { border-style: none; }
#org-info-js_console-label
{ font-size: 10px; font-weight: bold; white-space: nowrap; }
.org-info-js_search-highlight
{ background-color: #ffff00; color: #000000; font-weight: bold; }
.org-svg { width: 90%; }
/*]]>*/-->
</style>
<link rel="stylesheet" type="text/css" href="../css/main.css" />
<script type="text/javascript">
/*
@licstart The following is the entire license notice for the
JavaScript code in this tag.
Copyright (C) 2012-2019 Free Software Foundation, Inc.
The JavaScript code in this tag is free software: you can
redistribute it and/or modify it under the terms of the GNU
General Public License (GNU GPL) as published by the Free Software
Foundation, either version 3 of the License, or (at your option)
any later version. The code is distributed WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU GPL for more details.
As additional permission under GNU GPL version 3 section 7, you
may distribute non-source (e.g., minimized or compacted) forms of
that code without the copy of the GNU GPL normally required by
section 4, provided you include this license notice and a URL
through which recipients can access the Corresponding Source.
@licend The above is the entire license notice
for the JavaScript code in this tag.
*/
<!--/*--><![CDATA[/*><!--*/
function CodeHighlightOn(elem, id)
{
var target = document.getElementById(id);
if(null != target) {
elem.cacheClassElem = elem.className;
elem.cacheClassTarget = target.className;
target.className = "code-highlighted";
elem.className = "code-highlighted";
}
}
function CodeHighlightOff(elem, id)
{
var target = document.getElementById(id);
if(elem.cacheClassElem)
elem.className = elem.cacheClassElem;
if(elem.cacheClassTarget)
target.className = elem.cacheClassTarget;
}
/*]]>*///-->
</script>
</head>
<body>
<div id="org-div-home-and-up">
<a accesskey="h" href="operation-objects.html"> UP </a>
|
<a accesskey="H" href="../elisp.html"> HOME </a>
</div><div id="content">
<h1 class="title">文件</h1>
<div id="table-of-contents">
<h2>Table of Contents</h2>
<div id="text-table-of-contents">
<ul>
<li><a href="#org760b7c8">打开文件</a></li>
<li><a href="#org53d8f23">文件读写</a></li>
<li><a href="#org90be9ba">文件信息</a></li>
<li><a href="#orgf9e4cd2">修改文件信息</a></li>
<li><a href="#orgfb973bd">文件名操作</a></li>
<li><a href="#org649f07e">临时文件</a></li>
<li><a href="#org14afedb">读取目录内容</a></li>
<li><a href="#orgfbd11db">文件Handle</a></li>
</ul>
</div>
</div>
<pre class="example">
作为一个编辑器,自然文件是最重要的操作对象之一
这一节要介绍有关文件的一系列命令,比如查找文件,读写文件,文件信息、读取目录、文件名操作等
</pre>
<div id="outline-container-org760b7c8" class="outline-2">
<h2 id="org760b7c8">打开文件</h2>
<div class="outline-text-2" id="text-org760b7c8">
<p>
当打开一个文件时,实际上 emacs 做了很多事情:
</p>
<ul class="org-ul">
<li>把文件名展开成为完整的文件名</li>
<li>判断文件是否存在</li>
<li>判断文件是否可读或者文件大小是否太大</li>
<li>查看文件是否已经打开,是否被锁定</li>
<li>向缓冲区插入文件内容</li>
<li>设置缓冲区的模式</li>
</ul>
<pre class="example">
这还只是简单的一个步骤,实际情况比这要复杂的多,许多异常需要考虑
而且为了所有函数的可扩展性,许多变量、handler 和 hook 被加入到文件操作的函数中,使得每一个环节都可以让用户或者 elisp 开发者可以定制,甚至完全接管所有的文件操作
</pre>
<p>
这里需要区分两个概念:文件和缓冲区。它们是两个不同的对象:
</p>
<ul class="org-ul">
<li>文件:是在计算机上可持久保存的信息</li>
<li>缓冲区: Emacs 中包含文件内容信息的对象,在 emacs 退出后就会消失,只有当保存缓冲区之后缓冲区里的内容才写到文件中去</li>
</ul>
</div>
</div>
<div id="outline-container-org53d8f23" class="outline-2">
<h2 id="org53d8f23">文件读写</h2>
<div class="outline-text-2" id="text-org53d8f23">
<p>
打开一个文件的命令是 <span class="underline">find-file</span> : 这命令使一个缓冲区访问某个文件,并让这个缓冲区成为当前缓冲区
</p>
<ul class="org-ul">
<li><span class="underline">find-file-noselect</span> :所有访问文件的核心函数,它只返回访问文件的缓冲区</li>
<li>find-file 在打开文件过程中会调用 <span class="underline">find-file-hook</span></li>
</ul>
<p>
这两个函数都有一个特点,如果 emacs 里已经有一个缓冲区访问这个文件的话,emacs 不会创建另一个缓冲区来访问文件,而只是简单返回或者转到这个缓冲区
</p>
<pre class="example">
怎样检查有没有缓冲区是否访问某个文件呢?
所有和文件关联的缓冲区里都有一个 buffer-local 变量buffer-file-name。但是不要直接设置这个变量来改变缓冲区关联的文件,而是使用 set-visited-file-name 来修改
同样不要直接从 buffer-list 里搜索buffer-file-name 来查找和某个文件关联的缓冲区,应该使用get-file-buffer 或者 find-buffer-visiting
</pre>
<div class="org-src-container">
<pre class="src src-lisp">(find-file <span style="color: #deb887;">"~/tmp/test.txt"</span>)
(<span style="color: #00bfff; font-weight: bold;">with-current-buffer</span>
(find-file-noselect <span style="color: #deb887;">"~/tmp/test.txt"</span>)
buffer-file-name) <span style="color: #5f9ea0; font-style: italic;">; => "/home/klose/tmp/test.txt"</span>
(find-buffer-visiting <span style="color: #deb887;">"~/tmp/test.txt"</span>) <span style="color: #5f9ea0; font-style: italic;">; => #<buffer test.txt></span>
(get-file-buffer <span style="color: #deb887;">"~/tmp/test.txt"</span>) <span style="color: #5f9ea0; font-style: italic;">; => #<buffer test.txt></span>
</pre>
</div>
<p>
保存一个文件的过程相对简单一些:
</p>
<ol class="org-ol">
<li>首先创建备份文件</li>
<li>处理文件的位模式</li>
<li>将缓冲区写入文件</li>
</ol>
<p>
保存文件的命令是 <span class="underline">save-buffer</span>
</p>
<ul class="org-ul">
<li>相当于其它编辑器里 <b>另存为</b> 的命令是 <span class="underline">write-file</span> ,在这个过程中会调用一些函数或者 hook:
<ul class="org-ul">
<li>write-file-functions 和 write-contents-functions 几乎功能完全相同,都是在写入文件之前运行的函数,如果这些函数中有一个返回了 non-nil 的值, 则会认为文件已经写入了,后面的函数都不会运行,而且也不会使用再调用其它 写入文件的函数
<ul class="org-ul">
<li>这两个变量有一个重要的区别是write-contents-functions 在改变主模式之后会被修改,因为它没有permanent-local 属性,而 write-file-functions 则会仍然保留</li>
</ul></li>
<li>before-save-hook 和 write-file-functions 功能也比较类似,但是这个变量里的函数会逐个执行,不论返回什么值也不会影响后面文件的写入</li>
<li>after-save-hook 是在文件已经写入之后才调用的 hook,它是 save-buffer 最后一个动作</li>
</ul></li>
</ul>
<pre class="example">
但是实际上在 elisp 编程过程中经常遇到的一个问题是读取一个文件中的内容, 读取完之后并不希望这个缓冲区还留下来
如果直接用 kill-buffer 可能会把用户打开的文件关闭。而且 find-file-noselect 做的事情实在超出我们的需要
</pre>
<p>
这时可能需要的是更底层的文件读写函数,它们是 <span class="underline">insert-file-contents</span> 和 <span class="underline">write-region</span> ,调用形式分别是:
</p>
<div class="org-src-container">
<pre class="src src-lisp">(insert-file-contents filename <span style="color: #98f5ff;">&optional</span> visit beg end replace)
(write-region start end filename <span style="color: #98f5ff;">&optional</span> append visit lockname mustbenew)
</pre>
</div>
<p>
<span class="underline">insert-file-contents</span> 可以插入文件中指定部分到当前缓冲区中:
</p>
<ul class="org-ul">
<li>如果指定 visit 则会标记缓冲区的修改状态并关联缓冲区到文件,一般是不用的</li>
<li>replace 是指是否要删除缓冲区里其它内容,这比先删除缓冲区其它内容后插入文件内容要快一些,但是一般也用不上</li>
</ul>
<pre class="example">
insert-file-contents 会处理文件的编码,如果不需要解码文件的话,可以用 insert-file-contents-literally
</pre>
<p>
<span class="underline">write-region</span> 可以把缓冲区中的一部分写入到指定文件中:
</p>
<ul class="org-ul">
<li>如果指定 append 则是添加到文件末尾</li>
<li>visit 参数也会把缓冲区和文件关联</li>
<li>lockname 则是文件锁定的名字</li>
<li>mustbenew 确保文件存在时会要求用户确认操作</li>
</ul>
</div>
</div>
<div id="outline-container-org90be9ba" class="outline-2">
<h2 id="org90be9ba">文件信息</h2>
<div class="outline-text-2" id="text-org90be9ba">
<ul class="org-ul">
<li>文件是否存在可以使用 <span class="underline">file-exists-p</span> 来判断:对于目录和一般文件都可以用这个函数进行判断
<ul class="org-ul">
<li>符号链接只有当 <span class="underline">目标文件</span> 存在时才返回 t</li>
</ul></li>
<li><span class="underline">file-readable-p</span> 、 <span class="underline">file-writable-p</span> , <span class="underline">file-executable-p</span> 分用来测试用户对文件的权限
<ul class="org-ul">
<li>文件的位模式还可以用 <span class="underline">file-modes</span> 函数得到</li>
</ul></li>
</ul>
<div class="org-src-container">
<pre class="src src-lisp">(file-exists-p <span style="color: #deb887;">"~/tmp/test.txt"</span>) <span style="color: #5f9ea0; font-style: italic;">; => t</span>
(file-readable-p <span style="color: #deb887;">"~/tmp/test.txt"</span>) <span style="color: #5f9ea0; font-style: italic;">; => t</span>
(file-writable-p <span style="color: #deb887;">"~/tmp/test.txt"</span>) <span style="color: #5f9ea0; font-style: italic;">; => t</span>
(file-executable-p <span style="color: #deb887;">"~/tmp/test.txt"</span>) <span style="color: #5f9ea0; font-style: italic;">; => nil</span>
(format <span style="color: #deb887;">"%o"</span> (file-modes <span style="color: #deb887;">"~/tmp/test.txt"</span>)) <span style="color: #5f9ea0; font-style: italic;">; => "644"</span>
</pre>
</div>
<p>
文件类型判断:
</p>
<ul class="org-ul">
<li><span class="underline">file-regular-p</span> : 判断一个文件名是否是一个普通文件(不是目录,命名管道、终端或者其它 IO 设备)</li>
<li><span class="underline">file-directory-p</span>: 判断一个文件名是否一个存在的目录</li>
<li><span class="underline">file-symlink-p</span> : 判断一个文件名是否是一个符号链接
<ul class="org-ul">
<li>当文件名是一个符号链接时会返回 <span class="underline">目标文件名</span></li>
<li>文件的真实名字也就是除去相对链接和符号链接后得到的文件名可以用 <span class="underline">file-truename</span> 得到</li>
</ul></li>
</ul>
<pre class="example">
事实上每个和文件关联的 buffer 里也有一个缓冲区局部变量 buffer-file-truename 来记录这个文件名
</pre>
<div class="org-src-container">
<pre class="src src-sh">$ ls -l t.txt
lrwxrwxrwx 1 klose klose 8 2007-07-15 15:51 t.txt -> test.txt
</pre>
</div>
<div class="org-src-container">
<pre class="src src-lisp">(file-regular-p <span style="color: #deb887;">"~/tmp/t.txt"</span>) <span style="color: #5f9ea0; font-style: italic;">; => t</span>
(file-directory-p <span style="color: #deb887;">"~/tmp/t.txt"</span>) <span style="color: #5f9ea0; font-style: italic;">; => nil</span>
(file-symlink-p <span style="color: #deb887;">"~/tmp/t.txt"</span>) <span style="color: #5f9ea0; font-style: italic;">; => "test.txt"</span>
(file-truename <span style="color: #deb887;">"~/tmp/t.txt"</span>) <span style="color: #5f9ea0; font-style: italic;">; => "/home/klose/tmp/test.txt"</span>
</pre>
</div>
<p>
文件更详细的信息可以用 <span class="underline">file-attributes</span> 函数得到。这个函数类似系统的 stat 命令,返回文件几乎所有的信息,包括 <span class="underline">文件类型</span> , <span class="underline">用户</span> 和 <span class="underline">组用户</span> , <span class="underline">访问日期</span> 、 <span class="underline">修改日期</span> 、 <span class="underline">status change 日期</span> 、 <span class="underline">文件大小</span> 、 <span class="underline">文件位模式</span> 、 <span class="underline">inode number</span> 、 <span class="underline">system number</span> …..
</p>
<div class="org-src-container">
<pre class="src src-lisp">(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-stat-type</span> (file <span style="color: #98f5ff;">&optional</span> id-format)
(car (file-attributes file id-format)))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-stat-name-number</span> (file <span style="color: #98f5ff;">&optional</span> id-format)
(cadr (file-attributes file id-format)))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-stat-uid</span> (file <span style="color: #98f5ff;">&optional</span> id-format)
(nth 2 (file-attributes file id-format)))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-stat-gid</span> (file <span style="color: #98f5ff;">&optional</span> id-format)
(nth 3 (file-attributes file id-format)))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-stat-atime</span> (file <span style="color: #98f5ff;">&optional</span> id-format)
(nth 4 (file-attributes file id-format)))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-stat-mtime</span> (file <span style="color: #98f5ff;">&optional</span> id-format)
(nth 5 (file-attributes file id-format)))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-stat-ctime</span> (file <span style="color: #98f5ff;">&optional</span> id-format)
(nth 6 (file-attributes file id-format)))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-stat-size</span> (file <span style="color: #98f5ff;">&optional</span> id-format)
(nth 7 (file-attributes file id-format)))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-stat-modes</span> (file <span style="color: #98f5ff;">&optional</span> id-format)
(nth 8 (file-attributes file id-format)))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-stat-guid-changep</span> (file <span style="color: #98f5ff;">&optional</span> id-format)
(nth 9 (file-attributes file id-format)))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-stat-inode-number</span> (file <span style="color: #98f5ff;">&optional</span> id-format)
(nth 10 (file-attributes file id-format)))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-stat-system-number</span> (file <span style="color: #98f5ff;">&optional</span> id-format)
(nth 11 (file-attributes file id-format)))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-attr-type</span> (attr)
(car attr))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-attr-name-number</span> (attr)
(cadr attr))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-attr-uid</span> (attr)
(nth 2 attr))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-attr-gid</span> (attr)
(nth 3 attr))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-attr-atime</span> (attr)
(nth 4 attr))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-attr-mtime</span> (attr)
(nth 5 attr))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-attr-ctime</span> (attr)
(nth 6 attr))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-attr-size</span> (attr)
(nth 7 attr))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-attr-modes</span> (attr)
(nth 8 attr))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-attr-guid-changep</span> (attr)
(nth 9 attr))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-attr-inode-number</span> (attr)
(nth 10 attr))
(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">file-attr-system-number</span> (attr)
(nth 11 attr))
</pre>
</div>
<pre class="example">
前一组函数是直接由文件名访问文件信息,而后一组函数是由 file-attributes 的返回值来得到文件信息
</pre>
</div>
</div>
<div id="outline-container-orgf9e4cd2" class="outline-2">
<h2 id="orgf9e4cd2">修改文件信息</h2>
<div class="outline-text-2" id="text-orgf9e4cd2">
<ul class="org-ul">
<li>重命名和复制文件可以用 <span class="underline">rename-file</span> 和 <span class="underline">copy-file</span></li>
<li>删除文件使用 <span class="underline">delete-file</span></li>
<li>创建目录使用 <span class="underline">make-directory</span> 函数</li>
<li>不能用 delete-file 删除 目录,只能用 <span class="underline">delete-directory</span> 删除目录,当目录不为空时会产生一个错误</li>
<li>设置文件修改时间使用 <span class="underline">set-file-times</span></li>
<li>设置文件位模式可以用 <span class="underline">set-file-modes</span> 函数:参数必须是一个整数
<ul class="org-ul">
<li>可以用位函数 logand、logior 和 logxor 函数来进行位操作</li>
</ul></li>
</ul>
</div>
</div>
<div id="outline-container-orgfb973bd" class="outline-2">
<h2 id="orgfb973bd">文件名操作</h2>
<div class="outline-text-2" id="text-orgfb973bd">
<p>
路径一般由 <span class="underline">目录</span> 和 <span class="underline">文件名</span> ,而文件名一般由 <span class="underline">主文件名</span> (basename)、 <span class="underline">文件名后缀</span> 和 <span class="underline">版本号</span> 构成。 Emacs 有一系列函数来得到路径中的不同部分:
</p>
<div class="org-src-container">
<pre class="src src-lisp">(file-name-directory <span style="color: #deb887;">"~/tmp/test.txt"</span>) <span style="color: #5f9ea0; font-style: italic;">; => "~/tmp/"</span>
(file-name-nondirectory <span style="color: #deb887;">"~/tmp/test.txt"</span>) <span style="color: #5f9ea0; font-style: italic;">; => "test.txt"</span>
(file-name-sans-extension <span style="color: #deb887;">"~/tmp/test.txt"</span>) <span style="color: #5f9ea0; font-style: italic;">; => "~/tmp/test"</span>
(file-name-extension <span style="color: #deb887;">"~/tmp/test.txt"</span>) <span style="color: #5f9ea0; font-style: italic;">; => "txt"</span>
(file-name-sans-versions <span style="color: #deb887;">"~/tmp/test.txt~"</span>) <span style="color: #5f9ea0; font-style: italic;">; => "~/tmp/test.txt"</span>
(file-name-sans-versions <span style="color: #deb887;">"~/tmp/test.txt.~1~"</span>) <span style="color: #5f9ea0; font-style: italic;">; => "~/tmp/test.txt"</span>
</pre>
</div>
<pre class="example">
虽然 MSWin 的文件名使用的路径分隔符不同,但是这里介绍的函数都能用于 MSWin 形式的文件名,只是返回的文件名都是 Unix 形式了
</pre>
<p>
路径如果是从根目录开始的称为是绝对路径:
</p>
<ul class="org-ul">
<li>测试一个路径是否是绝对路径使用 <span class="underline">file-name-absolute-p</span>
<ul class="org-ul">
<li>如果在 Unix 或 GNU/Linux 系统,以 ~ 开头的路径也是绝对路径</li>
<li>在 MSWin 上,以 "/" 、 "\"、"X:" 开头的路径都是绝对路径</li>
</ul></li>
<li>如果不是绝对路径,可以使用 <span class="underline">expand-file-name</span> 来得到绝对路径</li>
<li>把一个绝对路径转换成相对某个路径的相对路径的可以用 <span class="underline">file-relative-name</span> 函数</li>
</ul>
<div class="org-src-container">
<pre class="src src-lisp">(file-name-absolute-p <span style="color: #deb887;">"~rms/foo"</span>) <span style="color: #5f9ea0; font-style: italic;">; => t</span>
(file-name-absolute-p <span style="color: #deb887;">"/user/rms/foo"</span>) <span style="color: #5f9ea0; font-style: italic;">; => t</span>
(expand-file-name <span style="color: #deb887;">"foo"</span>) <span style="color: #5f9ea0; font-style: italic;">; => "/home/klose/foo"</span>
(expand-file-name <span style="color: #deb887;">"foo"</span> <span style="color: #deb887;">"/usr/spool/"</span>) <span style="color: #5f9ea0; font-style: italic;">; => "/usr/spool/foo"</span>
(file-relative-name <span style="color: #deb887;">"/foo/bar"</span> <span style="color: #deb887;">"/foo/"</span>) <span style="color: #5f9ea0; font-style: italic;">; => "bar"</span>
(file-relative-name <span style="color: #deb887;">"/foo/bar"</span> <span style="color: #deb887;">"/hack/"</span>) <span style="color: #5f9ea0; font-style: italic;">; => "../foo/bar"</span>
</pre>
</div>
<p>
对于目录,如果要将其作为目录,也就是确保它是以路径分隔符结束,可以用 <span class="underline">file-name-as-directory</span>
</p>
<pre class="example">
不要用 (concat dir "/") 来转换,这会有移植问题
</pre>
<p>
和它相对应的函数是 <span class="underline">directory-file-name</span>
</p>
<div class="org-src-container">
<pre class="src src-lisp">(file-name-as-directory <span style="color: #deb887;">"~rms/lewis"</span>) <span style="color: #5f9ea0; font-style: italic;">; => "~rms/lewis/"</span>
(directory-file-name <span style="color: #deb887;">"~lewis/"</span>) <span style="color: #5f9ea0; font-style: italic;">; => "~lewis"</span>
</pre>
</div>
<p>
如果要得到所在系统使用的文件名,可以用 <span class="underline">convert-standard-filename</span>
</p>
<div class="org-src-container">
<pre class="src src-lisp">(convert-standard-filename <span style="color: #deb887;">"c:/windows"</span>) <span style="color: #5f9ea0; font-style: italic;">;=> "c:\\windows"</span>
</pre>
</div>
<pre class="example">
比如 在 MSWin 系统上,可以用这个函数返回用 "\" 分隔的文件名
</pre>
</div>
</div>
<div id="outline-container-org649f07e" class="outline-2">
<h2 id="org649f07e">临时文件</h2>
<div class="outline-text-2" id="text-org649f07e">
<ul class="org-ul">
<li>如果需要产生一个临时文件,可以使用 <span class="underline">make-temp-file</span>
<ul class="org-ul">
<li>这个函数按给定前缀产生一个不和现有文件冲突的文件,并返回它的文件名</li>
<li>如果给定的名字是一个相对文件名,则产生的文件名会用 <span class="underline">temporary-file-directory</span> 进行扩展
<ul class="org-ul">
<li>也可以用这个函数产生一个临时文件夹</li>
</ul></li>
</ul></li>
<li>如果只想产生一个不存在的文件名,可以用 <span class="underline">make-temp-name</span> 函数</li>
</ul>
<div class="org-src-container">
<pre class="src src-lisp">(make-temp-file <span style="color: #deb887;">"foo"</span>) <span style="color: #5f9ea0; font-style: italic;">; => "/tmp/foo5611dxf"</span>
(make-temp-name <span style="color: #deb887;">"foo"</span>) <span style="color: #5f9ea0; font-style: italic;">; => "foo5611q7l"</span>
</pre>
</div>
</div>
</div>
<div id="outline-container-org14afedb" class="outline-2">
<h2 id="org14afedb">读取目录内容</h2>
<div class="outline-text-2" id="text-org14afedb">
<p>
可以用 <span class="underline">directory-files</span> 来得到某个目录中的全部或者符合某个正则表达式的文件名:
</p>
<div class="org-src-container">
<pre class="src src-lisp">(directory-files <span style="color: #deb887;">"~/tmp/dir/"</span>)
<span style="color: #5f9ea0; font-style: italic;">;; </span><span style="color: #5f9ea0; font-style: italic;">=></span>
<span style="color: #5f9ea0; font-style: italic;">;; </span><span style="color: #5f9ea0; font-style: italic;">("#foo.el#" "." ".#foo.el" ".." "foo.el" "t.pl" "t2.pl")</span>
(directory-files <span style="color: #deb887;">"~/tmp/dir/"</span> t)
<span style="color: #5f9ea0; font-style: italic;">;; </span><span style="color: #5f9ea0; font-style: italic;">=></span>
<span style="color: #5f9ea0; font-style: italic;">;; </span><span style="color: #5f9ea0; font-style: italic;">("/home/ywb/tmp/dir/#foo.el#"</span>
<span style="color: #5f9ea0; font-style: italic;">;; </span><span style="color: #5f9ea0; font-style: italic;">"/home/ywb/tmp/dir/."</span>
<span style="color: #5f9ea0; font-style: italic;">;; </span><span style="color: #5f9ea0; font-style: italic;">"/home/ywb/tmp/dir/.#foo.el"</span>
<span style="color: #5f9ea0; font-style: italic;">;; </span><span style="color: #5f9ea0; font-style: italic;">"/home/ywb/tmp/dir/.."</span>
<span style="color: #5f9ea0; font-style: italic;">;; </span><span style="color: #5f9ea0; font-style: italic;">"/home/ywb/tmp/dir/foo.el"</span>
<span style="color: #5f9ea0; font-style: italic;">;; </span><span style="color: #5f9ea0; font-style: italic;">"/home/ywb/tmp/dir/t.pl"</span>
<span style="color: #5f9ea0; font-style: italic;">;; </span><span style="color: #5f9ea0; font-style: italic;">"/home/ywb/tmp/dir/t2.pl")</span>
(directory-files <span style="color: #deb887;">"~/tmp/dir/"</span> nil <span style="color: #deb887;">"\\.pl$"</span>) <span style="color: #5f9ea0; font-style: italic;">; => ("t.pl" "t2.pl")</span>
</pre>
</div>
<ul class="org-ul">
<li><span class="underline">directory-files-and-attributes</span> 和 directory-files 相似,但是返回的列表 中包含了 file-attributes 得到的信息</li>
<li><span class="underline">file-name-all-versions</span> 用于得到某个文件在目录中的所有版本</li>
<li><span class="underline">file-expand-wildcards</span> 可以用通配符来得到目录中的文件列表</li>
</ul>
</div>
</div>
<div id="outline-container-orgfbd11db" class="outline-2">
<h2 id="orgfbd11db">文件Handle</h2>
<div class="outline-text-2" id="text-orgfbd11db">
<pre class="example">
如果不把文件局限在存储在本地机器上的信息,而且有一套基本的文件操作,比如判断文件是否存在、打开文件、保存文件、得到目录内容之类,那远程的文件和本地文件的差别也仅在于文件名表示方法不同而已
在 Emacs 里,底层的文件操作函数都可以托管给 elisp 中的函数,这样只要用 elisp 实现了某种类型文件的基本操作,就能像编辑本地文件一样编辑其它类型文件了
</pre>
<p>
决定何种类型的文件名使用什么方式来操作是在 <span class="underline">file-name-handler-alist</span> 变量定义的。它是由形如 <span class="underline">(REGEXP . HANDLER)</span> 的列表。如果文件名匹配这个 REGEXP 则使用 HANDLER 来进行相应的文件操作。这里所说的文件操作,具体的来说有这些函数:
</p>
<div class="org-src-container">
<pre class="src src-lisp">`<span style="color: #ffd700;">access-file</span>', `<span style="color: #ffd700;">add-name-to-file</span>', `<span style="color: #ffd700;">byte-compiler-base-file-name</span>',
`<span style="color: #ffd700;">copy-file</span>', `<span style="color: #ffd700;">delete-directory</span>', `<span style="color: #ffd700;">delete-file</span>',
`<span style="color: #ffd700;">diff-latest-backup-file</span>', `<span style="color: #ffd700;">directory-file-name</span>', `<span style="color: #ffd700;">directory-files</span>',
`<span style="color: #ffd700;">directory-files-and-attributes</span>', `<span style="color: #ffd700;">dired-call-process</span>',
`<span style="color: #ffd700;">dired-compress-file</span>', `<span style="color: #ffd700;">dired-uncache</span>',
`<span style="color: #ffd700;">expand-file-name</span>', `<span style="color: #ffd700;">file-accessible-directory-p</span>', `<span style="color: #ffd700;">file-attributes</span>',
`<span style="color: #ffd700;">file-directory-p</span>', `<span style="color: #ffd700;">file-executable-p</span>', `<span style="color: #ffd700;">file-exists-p</span>',
`<span style="color: #ffd700;">file-local-copy</span>', `<span style="color: #ffd700;">file-remote-p</span>', `<span style="color: #ffd700;">file-modes</span>',
`<span style="color: #ffd700;">file-name-all-completions</span>', `<span style="color: #ffd700;">file-name-as-directory</span>',
`<span style="color: #ffd700;">file-name-completion</span>', `<span style="color: #ffd700;">file-name-directory</span>', `<span style="color: #ffd700;">file-name-nondirectory</span>',
`<span style="color: #ffd700;">file-name-sans-versions</span>', `<span style="color: #ffd700;">file-newer-than-file-p</span>',
`<span style="color: #ffd700;">file-ownership-preserved-p</span>', `<span style="color: #ffd700;">file-readable-p</span>', `<span style="color: #ffd700;">file-regular-p</span>',
`<span style="color: #ffd700;">file-symlink-p</span>', `<span style="color: #ffd700;">file-truename</span>', `<span style="color: #ffd700;">file-writable-p</span>',
`<span style="color: #ffd700;">find-backup-file-name</span>', `<span style="color: #ffd700;">find-file-noselect</span>',
`<span style="color: #ffd700;">get-file-buffer</span>', `<span style="color: #ffd700;">insert-directory</span>', `<span style="color: #ffd700;">insert-file-contents</span>',
`<span style="color: #ffd700;">load</span>', `<span style="color: #ffd700;">make-auto-save-file-name</span>', `<span style="color: #ffd700;">make-directory</span>',
`<span style="color: #ffd700;">make-directory-internal</span>', `<span style="color: #ffd700;">make-symbolic-link</span>',
`<span style="color: #ffd700;">rename-file</span>', `<span style="color: #ffd700;">set-file-modes</span>', `<span style="color: #ffd700;">set-file-times</span>',
`<span style="color: #ffd700;">set-visited-file-modtime</span>', `<span style="color: #ffd700;">shell-command</span>', `<span style="color: #ffd700;">substitute-in-file-name</span>',
`<span style="color: #ffd700;">unhandled-file-name-directory</span>', `<span style="color: #ffd700;">vc-registered</span>',
`<span style="color: #ffd700;">verify-visited-file-modtime</span>',
`<span style="color: #ffd700;">write-region</span>'
</pre>
</div>
<p>
在 HANDLE 里,可以只接管部分的文件操作,其它仍交给 emacs 原来的函数来完成
</p>
<pre class="example">
举一个简单的例子。比如最新版本的 emacs 把 *scratch* 的 auto-save-mode 打开了
如果你不想这个缓冲区的自动保存的文件名散布得到处都是,可以想办法让这个缓冲区的自动保存文件放到指定的目录中
刚好 make-auto-save-file-name 是在上面这个列表里的,但是不幸的是在函数定义里 make-auto-save-file-name 里不对不关联文件的缓冲区使用 handler
继续往下看,发现生成保存文件名是使用了 expand-file-name 函数
</pre>
<p>
一个解决方法就是:
</p>
<div class="org-src-container">
<pre class="src src-lisp">(<span style="color: #00bfff; font-weight: bold;">defun</span> <span style="color: #daa520; font-weight: bold;">my-scratch-auto-save-file-name</span> (operation <span style="color: #98f5ff;">&rest</span> args)
(<span style="color: #00bfff; font-weight: bold;">if</span> (and (eq operation 'expand-file-name)
(string= (car args) <span style="color: #deb887;">"#*scratch*#"</span>))
(expand-file-name (concat <span style="color: #deb887;">"~/.emacs.d/backup/"</span> (car args)))
(<span style="color: #00bfff; font-weight: bold;">let</span> ((inhibit-file-name-handlers
(cons 'my-scratch-auto-save-file-name
(and (eq inhibit-file-name-operation operation)
inhibit-file-name-handlers)))
(inhibit-file-name-operation operation))
(apply operation args))))
</pre>
</div>
<p>
<a href="text.html">Next:文本</a>
</p>
<p>
<a href="window.html">Previous:窗口</a>
</p>
<p>
<a href="operation-objects.html">TOP:操作对象</a>
</p>
</div>
</div>
</div>
<div id="postamble" class="status">
<br/>
<div class='ds-thread'></div>
<script>
var duoshuoQuery = {short_name:'klose911'};
(function() {
var dsThread = document.getElementsByClassName('ds-thread')[0];
dsThread.setAttribute('data-thread-key', document.title);
dsThread.setAttribute('data-title', document.title);
dsThread.setAttribute('data-url', window.location.href);
var ds = document.createElement('script');
ds.type = 'text/javascript';ds.async = true;
ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
ds.charset = 'UTF-8';
(document.getElementsByTagName('head')[0]
|| document.getElementsByTagName('body')[0]).appendChild(ds);
})();
</script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-90850421-1', 'auto');
ga('send', 'pageview');
</script>
</div>
</body>
</html>
| Java |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width" />
<link rel="shortcut icon" type="image/x-icon" href="../../../../../../../favicon.ico" />
<title>com.google.android.gms.games.multiplayer | Android Developers</title>
<!-- STYLESHEETS -->
<link rel="stylesheet"
href="http://fonts.googleapis.com/css?family=Roboto+Condensed">
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:light,regular,medium,thin,italic,mediumitalic,bold"
title="roboto">
<link href="../../../../../../../assets/css/default.css?v=2" rel="stylesheet" type="text/css">
<!-- FULLSCREEN STYLESHEET -->
<link href="../../../../../../../assets/css/fullscreen.css" rel="stylesheet" class="fullscreen"
type="text/css">
<!-- JAVASCRIPT -->
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script src="../../../../../../../assets/js/android_3p-bundle.js" type="text/javascript"></script>
<script type="text/javascript">
var toRoot = "../../../../../../../";
var metaTags = [];
var devsite = false;
</script>
<script src="../../../../../../../assets/js/docs.js?v=2" type="text/javascript"></script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-5831155-1', 'android.com');
ga('create', 'UA-49880327-2', 'android.com', {'name': 'universal'}); // New tracker);
ga('send', 'pageview');
ga('universal.send', 'pageview'); // Send page view for new tracker.
</script>
</head>
<body class="gc-documentation
develop">
<div id="doc-api-level" class="" style="display:none"></div>
<a name="top"></a>
<a name="top"></a>
<!-- Header -->
<div id="header-wrapper">
<div id="header">
<div class="wrap" id="header-wrap">
<div class="col-3 logo">
<a href="../../../../../../../index.html">
<img src="../../../../../../../assets/images/dac_logo.png"
srcset="../../../../../../../assets/images/dac_logo@2x.png 2x"
width="123" height="25" alt="Android Developers" />
</a>
<div class="btn-quicknav" id="btn-quicknav">
<a href="#" class="arrow-inactive">Quicknav</a>
<a href="#" class="arrow-active">Quicknav</a>
</div>
</div>
<ul class="nav-x col-9">
<li class="design">
<a href="../../../../../../../design/index.html"
zh-tw-lang="設計"
zh-cn-lang="设计"
ru-lang="Проектирование"
ko-lang="디자인"
ja-lang="設計"
es-lang="Diseñar"
>Design</a></li>
<li class="develop"><a href="../../../../../../../develop/index.html"
zh-tw-lang="開發"
zh-cn-lang="开发"
ru-lang="Разработка"
ko-lang="개발"
ja-lang="開発"
es-lang="Desarrollar"
>Develop</a></li>
<li class="distribute last"><a href="../../../../../../../distribute/googleplay/index.html"
zh-tw-lang="發佈"
zh-cn-lang="分发"
ru-lang="Распространение"
ko-lang="배포"
ja-lang="配布"
es-lang="Distribuir"
>Distribute</a></li>
</ul>
<div class="menu-container">
<div class="moremenu">
<div id="more-btn"></div>
</div>
<div class="morehover" id="moremenu">
<div class="top"></div>
<div class="mid">
<div class="header">Links</div>
<ul>
<li><a href="https://play.google.com/apps/publish/" target="_googleplay">Google Play Developer Console</a></li>
<li><a href="http://android-developers.blogspot.com/">Android Developers Blog</a></li>
<li><a href="../../../../../../../about/index.html">About Android</a></li>
</ul>
<div class="header">Android Sites</div>
<ul>
<li><a href="http://www.android.com">Android.com</a></li>
<li class="active"><a>Android Developers</a></li>
<li><a href="http://source.android.com">Android Open Source Project</a></li>
</ul>
<br class="clearfix" />
</div><!-- end 'mid' -->
<div class="bottom"></div>
</div><!-- end 'moremenu' -->
<div class="search" id="search-container">
<div class="search-inner">
<div id="search-btn"></div>
<div class="left"></div>
<form onsubmit="return submit_search()">
<input id="search_autocomplete" type="text" value="" autocomplete="off" name="q"
onfocus="search_focus_changed(this, true)" onblur="search_focus_changed(this, false)"
onkeydown="return search_changed(event, true, '../../../../../../../')"
onkeyup="return search_changed(event, false, '../../../../../../../')" />
</form>
<div class="right"></div>
<a class="close hide">close</a>
<div class="left"></div>
<div class="right"></div>
</div><!-- end search-inner -->
</div><!-- end search-container -->
<div class="search_filtered_wrapper reference">
<div class="suggest-card reference no-display">
<ul class="search_filtered">
</ul>
</div>
</div>
<div class="search_filtered_wrapper docs">
<div class="suggest-card dummy no-display"> </div>
<div class="suggest-card develop no-display">
<ul class="search_filtered">
</ul>
<div class="child-card guides no-display">
</div>
<div class="child-card training no-display">
</div>
<div class="child-card samples no-display">
</div>
</div>
<div class="suggest-card design no-display">
<ul class="search_filtered">
</ul>
</div>
<div class="suggest-card distribute no-display">
<ul class="search_filtered">
</ul>
</div>
</div>
</div><!-- end menu-container (search and menu widget) -->
<!-- Expanded quicknav -->
<div id="quicknav" class="col-13">
<ul>
<li class="about">
<ul>
<li><a href="../../../../../../../about/index.html">About</a></li>
<li><a href="../../../../../../../wear/index.html">Wear</a></li>
<li><a href="../../../../../../../tv/index.html">TV</a></li>
<li><a href="../../../../../../../auto/index.html">Auto</a></li>
</ul>
</li>
<li class="design">
<ul>
<li><a href="../../../../../../../design/index.html">Get Started</a></li>
<li><a href="../../../../../../../design/devices.html">Devices</a></li>
<li><a href="../../../../../../../design/style/index.html">Style</a></li>
<li><a href="../../../../../../../design/patterns/index.html">Patterns</a></li>
<li><a href="../../../../../../../design/building-blocks/index.html">Building Blocks</a></li>
<li><a href="../../../../../../../design/downloads/index.html">Downloads</a></li>
<li><a href="../../../../../../../design/videos/index.html">Videos</a></li>
</ul>
</li>
<li class="develop">
<ul>
<li><a href="../../../../../../../training/index.html"
zh-tw-lang="訓練課程"
zh-cn-lang="培训"
ru-lang="Курсы"
ko-lang="교육"
ja-lang="トレーニング"
es-lang="Capacitación"
>Training</a></li>
<li><a href="../../../../../../../guide/index.html"
zh-tw-lang="API 指南"
zh-cn-lang="API 指南"
ru-lang="Руководства по API"
ko-lang="API 가이드"
ja-lang="API ガイド"
es-lang="Guías de la API"
>API Guides</a></li>
<li><a href="../../../../../../../reference/packages.html"
zh-tw-lang="參考資源"
zh-cn-lang="参考"
ru-lang="Справочник"
ko-lang="참조문서"
ja-lang="リファレンス"
es-lang="Referencia"
>Reference</a></li>
<li><a href="../../../../../../../sdk/index.html"
zh-tw-lang="相關工具"
zh-cn-lang="工具"
ru-lang="Инструменты"
ko-lang="도구"
ja-lang="ツール"
es-lang="Herramientas"
>Tools</a>
</li>
<li><a href="../../../../../../../google/index.html">Google Services</a>
</li>
</ul>
</li>
<li class="distribute last">
<ul>
<li><a href="../../../../../../../distribute/googleplay/index.html">Google Play</a></li>
<li><a href="../../../../../../../distribute/essentials/index.html">Essentials</a></li>
<li><a href="../../../../../../../distribute/users/index.html">Get Users</a></li>
<li><a href="../../../../../../../distribute/engage/index.html">Engage & Retain</a></li>
<li><a href="../../../../../../../distribute/monetize/index.html">Monetize</a></li>
<li><a href="../../../../../../../distribute/tools/index.html">Tools & Reference</a></li>
<li><a href="../../../../../../../distribute/stories/index.html">Developer Stories</a></li>
</ul>
</li>
</ul>
</div><!-- /Expanded quicknav -->
</div><!-- end header-wrap.wrap -->
</div><!-- end header -->
<!-- Secondary x-nav -->
<div id="nav-x">
<div class="wrap">
<ul class="nav-x col-9 develop" style="width:100%">
<li class="training"><a href="../../../../../../../training/index.html"
zh-tw-lang="訓練課程"
zh-cn-lang="培训"
ru-lang="Курсы"
ko-lang="교육"
ja-lang="トレーニング"
es-lang="Capacitación"
>Training</a></li>
<li class="guide"><a href="../../../../../../../guide/index.html"
zh-tw-lang="API 指南"
zh-cn-lang="API 指南"
ru-lang="Руководства по API"
ko-lang="API 가이드"
ja-lang="API ガイド"
es-lang="Guías de la API"
>API Guides</a></li>
<li class="reference"><a href="../../../../../../../reference/packages.html"
zh-tw-lang="參考資源"
zh-cn-lang="参考"
ru-lang="Справочник"
ko-lang="참조문서"
ja-lang="リファレンス"
es-lang="Referencia"
>Reference</a></li>
<li class="tools"><a href="../../../../../../../sdk/index.html"
zh-tw-lang="相關工具"
zh-cn-lang="工具"
ru-lang="Инструменты"
ko-lang="도구"
ja-lang="ツール"
es-lang="Herramientas"
>Tools</a></li>
<li class="google"><a href="../../../../../../../google/index.html"
>Google Services</a>
</li>
</ul>
</div>
</div>
<!-- /Sendondary x-nav DEVELOP -->
<div id="searchResults" class="wrap" style="display:none;">
<h2 id="searchTitle">Results</h2>
<div id="leftSearchControl" class="search-control">Loading...</div>
</div>
</div> <!--end header-wrapper -->
<div id="sticky-header">
<div>
<a class="logo" href="#top"></a>
<a class="top" href="#top"></a>
<ul class="breadcrumb">
<li class="current">com.google.android.gms.games.multiplayer</li>
</ul>
</div>
</div>
<div class="wrap clearfix" id="body-content">
<div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<div id="devdoc-nav">
<div id="api-nav-header">
<div id="api-level-toggle">
<label for="apiLevelCheckbox" class="disabled"
title="Select your target API level to dim unavailable APIs">API level: </label>
<div class="select-wrapper">
<select id="apiLevelSelector">
<!-- option elements added by buildApiLevelSelector() -->
</select>
</div>
</div><!-- end toggle -->
<div id="api-nav-title">Android APIs</div>
</div><!-- end nav header -->
<script>
var SINCE_DATA = [ ];
buildApiLevelSelector();
</script>
<div id="swapper">
<div id="nav-panels">
<div id="resize-packages-nav">
<div id="packages-nav" class="scroll-pane">
<ul>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/package-summary.html">com.google.android.gms</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/actions/package-summary.html">com.google.android.gms.actions</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/package-summary.html">com.google.android.gms.ads</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/doubleclick/package-summary.html">com.google.android.gms.ads.doubleclick</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/identifier/package-summary.html">com.google.android.gms.ads.identifier</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/mediation/package-summary.html">com.google.android.gms.ads.mediation</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/mediation/admob/package-summary.html">com.google.android.gms.ads.mediation.admob</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/mediation/customevent/package-summary.html">com.google.android.gms.ads.mediation.customevent</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/purchase/package-summary.html">com.google.android.gms.ads.purchase</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/ads/search/package-summary.html">com.google.android.gms.ads.search</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/analytics/package-summary.html">com.google.android.gms.analytics</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/analytics/ecommerce/package-summary.html">com.google.android.gms.analytics.ecommerce</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/appindexing/package-summary.html">com.google.android.gms.appindexing</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/appstate/package-summary.html">com.google.android.gms.appstate</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/auth/package-summary.html">com.google.android.gms.auth</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/auth/api/package-summary.html">com.google.android.gms.auth.api</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/cast/package-summary.html">com.google.android.gms.cast</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/common/package-summary.html">com.google.android.gms.common</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/common/annotation/package-summary.html">com.google.android.gms.common.annotation</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/common/api/package-summary.html">com.google.android.gms.common.api</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/common/data/package-summary.html">com.google.android.gms.common.data</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/common/images/package-summary.html">com.google.android.gms.common.images</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/drive/package-summary.html">com.google.android.gms.drive</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/drive/events/package-summary.html">com.google.android.gms.drive.events</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/drive/metadata/package-summary.html">com.google.android.gms.drive.metadata</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/drive/query/package-summary.html">com.google.android.gms.drive.query</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/drive/widget/package-summary.html">com.google.android.gms.drive.widget</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/fitness/package-summary.html">com.google.android.gms.fitness</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/fitness/data/package-summary.html">com.google.android.gms.fitness.data</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/fitness/request/package-summary.html">com.google.android.gms.fitness.request</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/fitness/result/package-summary.html">com.google.android.gms.fitness.result</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/fitness/service/package-summary.html">com.google.android.gms.fitness.service</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/package-summary.html">com.google.android.gms.games</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/achievement/package-summary.html">com.google.android.gms.games.achievement</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/event/package-summary.html">com.google.android.gms.games.event</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/leaderboard/package-summary.html">com.google.android.gms.games.leaderboard</a></li>
<li class="selected api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/package-summary.html">com.google.android.gms.games.multiplayer</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/realtime/package-summary.html">com.google.android.gms.games.multiplayer.realtime</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/turnbased/package-summary.html">com.google.android.gms.games.multiplayer.turnbased</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/quest/package-summary.html">com.google.android.gms.games.quest</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/request/package-summary.html">com.google.android.gms.games.request</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/games/snapshot/package-summary.html">com.google.android.gms.games.snapshot</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/gcm/package-summary.html">com.google.android.gms.gcm</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/identity/intents/package-summary.html">com.google.android.gms.identity.intents</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/identity/intents/model/package-summary.html">com.google.android.gms.identity.intents.model</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/location/package-summary.html">com.google.android.gms.location</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/maps/package-summary.html">com.google.android.gms.maps</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/maps/model/package-summary.html">com.google.android.gms.maps.model</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/panorama/package-summary.html">com.google.android.gms.panorama</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/plus/package-summary.html">com.google.android.gms.plus</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/plus/model/moments/package-summary.html">com.google.android.gms.plus.model.moments</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/plus/model/people/package-summary.html">com.google.android.gms.plus.model.people</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/security/package-summary.html">com.google.android.gms.security</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/tagmanager/package-summary.html">com.google.android.gms.tagmanager</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/wallet/package-summary.html">com.google.android.gms.wallet</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/wallet/fragment/package-summary.html">com.google.android.gms.wallet.fragment</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/wearable/package-summary.html">com.google.android.gms.wearable</a></li>
</ul><br/>
</div> <!-- end packages-nav -->
</div> <!-- end resize-packages -->
<div id="classes-nav" class="scroll-pane">
<ul>
<li><h2>Interfaces</h2>
<ul>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/Invitation.html">Invitation</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/Invitations.html">Invitations</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/Invitations.LoadInvitationsResult.html">Invitations.LoadInvitationsResult</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/Multiplayer.html">Multiplayer</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/OnInvitationReceivedListener.html">OnInvitationReceivedListener</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/Participant.html">Participant</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/Participatable.html">Participatable</a></li>
</ul>
</li>
<li><h2>Classes</h2>
<ul>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/InvitationBuffer.html">InvitationBuffer</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/InvitationEntity.html">InvitationEntity</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/ParticipantBuffer.html">ParticipantBuffer</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/ParticipantEntity.html">ParticipantEntity</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/ParticipantResult.html">ParticipantResult</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/ParticipantUtils.html">ParticipantUtils</a></li>
</ul>
</li>
</ul><br/>
</div><!-- end classes -->
</div><!-- end nav-panels -->
<div id="nav-tree" style="display:none" class="scroll-pane">
<div id="tree-list"></div>
</div><!-- end nav-tree -->
</div><!-- end swapper -->
<div id="nav-swap">
<a class="fullscreen">fullscreen</a>
<a href='#' onclick='swapNav();return false;'><span id='tree-link'>Use Tree Navigation</span><span id='panel-link' style='display:none'>Use Panel Navigation</span></a>
</div>
</div> <!-- end devdoc-nav -->
</div> <!-- end side-nav -->
<script type="text/javascript">
// init fullscreen based on user pref
var fullscreen = readCookie("fullscreen");
if (fullscreen != 0) {
if (fullscreen == "false") {
toggleFullscreen(false);
} else {
toggleFullscreen(true);
}
}
// init nav version for mobile
if (isMobile) {
swapNav(); // tree view should be used on mobile
$('#nav-swap').hide();
} else {
chooseDefaultNav();
if ($("#nav-tree").is(':visible')) {
init_default_navtree("../../../../../../../");
}
}
// scroll the selected page into view
$(document).ready(function() {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
});
</script>
<div class="col-12" id="doc-col">
<div id="api-info-block">
<div class="api-level">
</div>
</div>
<div id="jd-header">
package
<h1>com.google.android.gms.games.multiplayer</h1>
</div><!-- end header -->
<div id="naMessage"></div>
<div id="jd-content" class="api apilevel-">
<div class="jd-descr">
Contains data classes for multiplayer functionality.
</div>
<h2>Interfaces</h2>
<div class="jd-sumtable">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/Invitation.html">Invitation</a></td>
<td class="jd-descrcol" width="100%">Data interface for an invitation object. </td>
</tr>
<tr class=" api apilevel-" >
<td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/Invitations.html">Invitations</a></td>
<td class="jd-descrcol" width="100%">Entry point for invitations functionality. </td>
</tr>
<tr class="alt-color api apilevel-" >
<td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/Invitations.LoadInvitationsResult.html">Invitations.LoadInvitationsResult</a></td>
<td class="jd-descrcol" width="100%">Result delivered when invitations have been loaded. </td>
</tr>
<tr class=" api apilevel-" >
<td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/Multiplayer.html">Multiplayer</a></td>
<td class="jd-descrcol" width="100%">Common constants/methods for multiplayer functionality. </td>
</tr>
<tr class="alt-color api apilevel-" >
<td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/OnInvitationReceivedListener.html">OnInvitationReceivedListener</a></td>
<td class="jd-descrcol" width="100%">Listener to invoke when a new invitation is received. </td>
</tr>
<tr class=" api apilevel-" >
<td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/Participant.html">Participant</a></td>
<td class="jd-descrcol" width="100%">Data interface for multiplayer participants. </td>
</tr>
<tr class="alt-color api apilevel-" >
<td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/Participatable.html">Participatable</a></td>
<td class="jd-descrcol" width="100%">Interface defining methods for an object which can have participants. </td>
</tr>
</table>
</div>
<h2>Classes</h2>
<div class="jd-sumtable">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/InvitationBuffer.html">InvitationBuffer</a></td>
<td class="jd-descrcol" width="100%"><code><a href="../../../../../../../reference/com/google/android/gms/common/data/DataBuffer.html">DataBuffer</a></code> implementation containing Invitation data. </td>
</tr>
<tr class=" api apilevel-" >
<td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/InvitationEntity.html">InvitationEntity</a></td>
<td class="jd-descrcol" width="100%">Data object representing the data for a multiplayer invitation. </td>
</tr>
<tr class="alt-color api apilevel-" >
<td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/ParticipantBuffer.html">ParticipantBuffer</a></td>
<td class="jd-descrcol" width="100%"><code><a href="../../../../../../../reference/com/google/android/gms/common/data/DataBuffer.html">DataBuffer</a></code> implementation containing match participant data. </td>
</tr>
<tr class=" api apilevel-" >
<td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/ParticipantEntity.html">ParticipantEntity</a></td>
<td class="jd-descrcol" width="100%">Data object representing a Participant in a match. </td>
</tr>
<tr class="alt-color api apilevel-" >
<td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/ParticipantResult.html">ParticipantResult</a></td>
<td class="jd-descrcol" width="100%">Data class used to report a participant's result in a match. </td>
</tr>
<tr class=" api apilevel-" >
<td class="jd-linkcol"><a href="../../../../../../../reference/com/google/android/gms/games/multiplayer/ParticipantUtils.html">ParticipantUtils</a></td>
<td class="jd-descrcol" width="100%">Utilities for working with multiplayer participants. </td>
</tr>
</table>
</div>
<div id="footer" class="wrap" >
<div id="copyright">
Except as noted, this content is licensed under <a
href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2.0</a>.
For details and restrictions, see the <a href="../../../../../../../license.html">
Content License</a>.
</div>
<div id="build_info">
Android GmsCore 1501030 r —
<script src="../../../../../../../timestamp.js" type="text/javascript"></script>
<script>document.write(BUILD_TIMESTAMP)</script>
</div>
<div id="footerlinks">
<p>
<a href="../../../../../../../about/index.html">About Android</a> |
<a href="../../../../../../../legal.html">Legal</a> |
<a href="../../../../../../../support.html">Support</a>
</p>
</div>
</div> <!-- end footer -->
</div><!-- end jd-content -->
</div><!-- doc-content -->
</div> <!-- end body-content -->
</body>
</html>
| Java |
#!/bin/bash
#
./srmgor_2conn 2>&1 | tee runlog${1}.txt
| Java |
package mesosphere.marathon.integration
import mesosphere.marathon.api.v2.json.GroupUpdate
import mesosphere.marathon.integration.setup.{ IntegrationFunSuite, IntegrationHealthCheck, SingleMarathonIntegrationTest, WaitTestSupport }
import mesosphere.marathon.state.{ AppDefinition, PathId, UpgradeStrategy }
import org.apache.http.HttpStatus
import org.scalatest._
import spray.http.DateTime
import scala.concurrent.duration._
class GroupDeployIntegrationTest
extends IntegrationFunSuite
with SingleMarathonIntegrationTest
with Matchers
with BeforeAndAfter
with GivenWhenThen {
//clean up state before running the test case
before(cleanUp())
test("create empty group successfully") {
Given("A group which does not exist in marathon")
val group = GroupUpdate.empty("test".toRootTestPath)
When("The group gets created")
val result = marathon.createGroup(group)
Then("The group is created. A success event for this group is send.")
result.code should be(201) //created
val event = waitForChange(result)
}
test("update empty group successfully") {
Given("An existing group")
val name = "test2".toRootTestPath
val group = GroupUpdate.empty(name)
val dependencies = Set("/test".toTestPath)
waitForChange(marathon.createGroup(group))
When("The group gets updated")
waitForChange(marathon.updateGroup(name, group.copy(dependencies = Some(dependencies))))
Then("The group is updated")
val result = marathon.group("test2".toRootTestPath)
result.code should be(200)
result.value.dependencies should be(dependencies)
}
test("deleting an existing group gives a 200 http response") {
Given("An existing group")
val group = GroupUpdate.empty("test3".toRootTestPath)
waitForChange(marathon.createGroup(group))
When("The group gets deleted")
val result = marathon.deleteGroup(group.id.get)
waitForChange(result)
Then("The group is deleted")
result.code should be(200)
// only expect the test base group itself
marathon.listGroupsInBaseGroup.value.filter { group => group.id != testBasePath } should be('empty)
}
test("delete a non existing group should give a 404 http response") {
When("A non existing group is deleted")
val result = marathon.deleteGroup("does_not_exist".toRootTestPath)
Then("We get a 404 http response code")
result.code should be(404)
}
test("create a group with applications to start") {
Given("A group with one application")
val app = appProxy("/test/app".toRootTestPath, "v1", 2, withHealth = false)
val group = GroupUpdate("/test".toRootTestPath, Set(app))
When("The group is created")
waitForChange(marathon.createGroup(group))
Then("A success event is send and the application has been started")
val tasks = waitForTasks(app.id, app.instances)
tasks should have size 2
}
test("update a group with applications to restart") {
Given("A group with one application started")
val id = "test".toRootTestPath
val appId = id / "app"
val app1V1 = appProxy(appId, "v1", 2, withHealth = false)
waitForChange(marathon.createGroup(GroupUpdate(id, Set(app1V1))))
waitForTasks(app1V1.id, app1V1.instances)
When("The group is updated, with a changed application")
val app1V2 = appProxy(appId, "v2", 2, withHealth = false)
waitForChange(marathon.updateGroup(id, GroupUpdate(id, Set(app1V2))))
Then("A success event is send and the application has been started")
waitForTasks(app1V2.id, app1V2.instances)
}
test("update a group with the same application so no restart is triggered") {
Given("A group with one application started")
val id = "test".toRootTestPath
val appId = id / "app"
val app1V1 = appProxy(appId, "v1", 2, withHealth = false)
waitForChange(marathon.createGroup(GroupUpdate(id, Set(app1V1))))
waitForTasks(app1V1.id, app1V1.instances)
val tasks = marathon.tasks(appId)
When("The group is updated, with the same application")
waitForChange(marathon.updateGroup(id, GroupUpdate(id, Set(app1V1))))
Then("There is no deployment and all tasks still live")
marathon.listDeploymentsForBaseGroup().value should be ('empty)
marathon.tasks(appId).value.toSet should be(tasks.value.toSet)
}
test("create a group with application with health checks") {
Given("A group with one application")
val id = "proxy".toRootTestPath
val appId = id / "app"
val proxy = appProxy(appId, "v1", 1)
val group = GroupUpdate(id, Set(proxy))
When("The group is created")
val create = marathon.createGroup(group)
Then("A success event is send and the application has been started")
waitForChange(create)
}
test("upgrade a group with application with health checks") {
Given("A group with one application")
val id = "test".toRootTestPath
val appId = id / "app"
val proxy = appProxy(appId, "v1", 1)
val group = GroupUpdate(id, Set(proxy))
waitForChange(marathon.createGroup(group))
val check = appProxyCheck(proxy.id, "v1", state = true)
When("The group is updated")
check.afterDelay(1.second, state = false)
check.afterDelay(3.seconds, state = true)
val update = marathon.updateGroup(id, group.copy(apps = Some(Set(appProxy(appId, "v2", 1)))))
Then("A success event is send and the application has been started")
waitForChange(update)
}
test("rollback from an upgrade of group") {
Given("A group with one application")
val gid = "proxy".toRootTestPath
val appId = gid / "app"
val proxy = appProxy(appId, "v1", 2)
val group = GroupUpdate(gid, Set(proxy))
val create = marathon.createGroup(group)
waitForChange(create)
waitForTasks(proxy.id, proxy.instances)
val v1Checks = appProxyCheck(appId, "v1", state = true)
When("The group is updated")
waitForChange(marathon.updateGroup(gid, group.copy(apps = Some(Set(appProxy(appId, "v2", 2))))))
Then("The new version is deployed")
val v2Checks = appProxyCheck(appId, "v2", state = true)
WaitTestSupport.validFor("all v2 apps are available", 10.seconds) { v2Checks.pingSince(2.seconds) }
When("A rollback to the first version is initiated")
waitForChange(marathon.rollbackGroup(gid, create.value.version), 120.seconds)
Then("The rollback will be performed and the old version is available")
v1Checks.healthy
WaitTestSupport.validFor("all v1 apps are available", 10.seconds) { v1Checks.pingSince(2.seconds) }
}
test("during Deployment the defined minimum health capacity is never undershot") {
Given("A group with one application")
val id = "test".toRootTestPath
val appId = id / "app"
val proxy = appProxy(appId, "v1", 2).copy(upgradeStrategy = UpgradeStrategy(1))
val group = GroupUpdate(id, Set(proxy))
val create = marathon.createGroup(group)
waitForChange(create)
waitForTasks(appId, proxy.instances)
val v1Check = appProxyCheck(appId, "v1", state = true)
When("The new application is not healthy")
val v2Check = appProxyCheck(appId, "v2", state = false) //will always fail
val update = marathon.updateGroup(id, group.copy(apps = Some(Set(appProxy(appId, "v2", 2)))))
Then("All v1 applications are kept alive")
v1Check.healthy
WaitTestSupport.validFor("all v1 apps are always available", 15.seconds) { v1Check.pingSince(3.seconds) }
When("The new application becomes healthy")
v2Check.state = true //make v2 healthy, so the app can be cleaned
waitForChange(update)
}
test("An upgrade in progress can not be interrupted without force") {
Given("A group with one application with an upgrade in progress")
val id = "forcetest".toRootTestPath
val appId = id / "app"
val proxy = appProxy(appId, "v1", 2)
val group = GroupUpdate(id, Set(proxy))
val create = marathon.createGroup(group)
waitForChange(create)
appProxyCheck(appId, "v2", state = false) //will always fail
marathon.updateGroup(id, group.copy(apps = Some(Set(appProxy(appId, "v2", 2)))))
When("Another upgrade is triggered, while the old one is not completed")
val result = marathon.updateGroup(id, group.copy(apps = Some(Set(appProxy(appId, "v3", 2)))))
Then("An error is indicated")
result.code should be (HttpStatus.SC_CONFLICT)
waitForEvent("group_change_failed")
When("Another upgrade is triggered with force, while the old one is not completed")
val force = marathon.updateGroup(id, group.copy(apps = Some(Set(appProxy(appId, "v4", 2)))), force = true)
Then("The update is performed")
waitForChange(force)
}
test("A group with a running deployment can not be deleted without force") {
Given("A group with one application with an upgrade in progress")
val id = "forcetest".toRootTestPath
val appId = id / "app"
val proxy = appProxy(appId, "v1", 2)
appProxyCheck(appId, "v1", state = false) //will always fail
val group = GroupUpdate(id, Set(proxy))
val create = marathon.createGroup(group)
When("Delete the group, while the deployment is in progress")
val deleteResult = marathon.deleteGroup(id)
Then("An error is indicated")
deleteResult.code should be (HttpStatus.SC_CONFLICT)
waitForEvent("group_change_failed")
When("Delete is triggered with force, while the deployment is not completed")
val force = marathon.deleteGroup(id, force = true)
Then("The delete is performed")
waitForChange(force)
}
test("Groups with Applications with circular dependencies can not get deployed") {
Given("A group with 3 circular dependent applications")
val db = appProxy("/test/db".toTestPath, "v1", 1, dependencies = Set("/test/frontend1".toTestPath))
val service = appProxy("/test/service".toTestPath, "v1", 1, dependencies = Set(db.id))
val frontend = appProxy("/test/frontend1".toTestPath, "v1", 1, dependencies = Set(service.id))
val group = GroupUpdate("test".toTestPath, Set(db, service, frontend))
When("The group gets posted")
val result = marathon.createGroup(group)
Then("An unsuccessful response has been posted, with an error indicating cyclic dependencies")
val errors = (result.entityJson \ "details" \\ "errors").flatMap(_.as[Seq[String]])
errors.find(_.contains("cyclic dependencies")) shouldBe defined
}
test("Applications with dependencies get deployed in the correct order") {
Given("A group with 3 dependent applications")
val db = appProxy("/test/db".toTestPath, "v1", 1)
val service = appProxy("/test/service".toTestPath, "v1", 1, dependencies = Set(db.id))
val frontend = appProxy("/test/frontend1".toTestPath, "v1", 1, dependencies = Set(service.id))
val group = GroupUpdate("/test".toTestPath, Set(db, service, frontend))
When("The group gets deployed")
var ping = Map.empty[PathId, DateTime]
def storeFirst(health: IntegrationHealthCheck) {
if (!ping.contains(health.appId)) ping += health.appId -> DateTime.now
}
val dbHealth = appProxyCheck(db.id, "v1", state = true).withHealthAction(storeFirst)
val serviceHealth = appProxyCheck(service.id, "v1", state = true).withHealthAction(storeFirst)
val frontendHealth = appProxyCheck(frontend.id, "v1", state = true).withHealthAction(storeFirst)
waitForChange(marathon.createGroup(group))
Then("The correct order is maintained")
ping should have size 3
ping(db.id) should be < ping(service.id)
ping(service.id) should be < ping(frontend.id)
}
test("Groups with dependencies get deployed in the correct order") {
Given("A group with 3 dependent applications")
val db = appProxy("/test/db/db1".toTestPath, "v1", 1)
val service = appProxy("/test/service/service1".toTestPath, "v1", 1)
val frontend = appProxy("/test/frontend/frontend1".toTestPath, "v1", 1)
val group = GroupUpdate(
"/test".toTestPath,
Set.empty[AppDefinition],
Set(
GroupUpdate(PathId("db"), apps = Set(db)),
GroupUpdate(PathId("service"), apps = Set(service)).copy(dependencies = Some(Set("/test/db".toTestPath))),
GroupUpdate(PathId("frontend"), apps = Set(frontend)).copy(dependencies = Some(Set("/test/service".toTestPath)))
)
)
When("The group gets deployed")
var ping = Map.empty[PathId, DateTime]
def storeFirst(health: IntegrationHealthCheck) {
if (!ping.contains(health.appId)) ping += health.appId -> DateTime.now
}
val dbHealth = appProxyCheck(db.id, "v1", state = true).withHealthAction(storeFirst)
val serviceHealth = appProxyCheck(service.id, "v1", state = true).withHealthAction(storeFirst)
val frontendHealth = appProxyCheck(frontend.id, "v1", state = true).withHealthAction(storeFirst)
waitForChange(marathon.createGroup(group))
Then("The correct order is maintained")
ping should have size 3
ping(db.id) should be < ping(service.id)
ping(service.id) should be < ping(frontend.id)
}
ignore("Groups with dependant Applications get upgraded in the correct order with maintained upgrade strategy") {
var ping = Map.empty[String, DateTime]
def key(health: IntegrationHealthCheck) = s"${health.appId}_${health.versionId}"
def storeFirst(health: IntegrationHealthCheck) {
if (!ping.contains(key(health))) ping += key(health) -> DateTime.now
}
def create(version: String, initialState: Boolean) = {
val db = appProxy("/test/db".toTestPath, version, 1)
val service = appProxy("/test/service".toTestPath, version, 1, dependencies = Set(db.id))
val frontend = appProxy("/test/frontend1".toTestPath, version, 1, dependencies = Set(service.id))
(
GroupUpdate("/test".toTestPath, Set(db, service, frontend)),
appProxyCheck(db.id, version, state = initialState).withHealthAction(storeFirst),
appProxyCheck(service.id, version, state = initialState).withHealthAction(storeFirst),
appProxyCheck(frontend.id, version, state = initialState).withHealthAction(storeFirst))
}
Given("A group with 3 dependent applications")
val (groupV1, dbV1, serviceV1, frontendV1) = create("v1", true)
waitForChange(marathon.createGroup(groupV1))
When("The group gets updated, where frontend2 is not healthy")
val (groupV2, dbV2, serviceV2, frontendV2) = create("v2", false)
val upgrade = marathon.updateGroup(groupV2.id.get, groupV2)
waitForHealthCheck(dbV2)
Then("The correct order is maintained")
ping should have size 4
ping(key(dbV1)) should be < ping(key(serviceV1))
ping(key(serviceV1)) should be < ping(key(frontendV1))
WaitTestSupport.validFor("all v1 apps are available as well as db v2", 15.seconds) {
dbV1.pingSince(2.seconds) &&
serviceV1.pingSince(2.seconds) &&
frontendV1.pingSince(2.seconds) &&
dbV2.pingSince(2.seconds)
}
When("The v2 db becomes healthy")
dbV2.state = true
waitForHealthCheck(serviceV2)
Then("The correct order is maintained")
ping should have size 5
ping(key(serviceV1)) should be < ping(key(frontendV1))
ping(key(dbV2)) should be < ping(key(serviceV2))
WaitTestSupport.validFor("service and frontend v1 are available as well as db and service v2", 15.seconds) {
serviceV1.pingSince(2.seconds) &&
frontendV1.pingSince(2.seconds) &&
dbV2.pingSince(2.seconds) &&
serviceV2.pingSince(2.seconds)
}
When("The v2 service becomes healthy")
serviceV2.state = true
waitForHealthCheck(frontendV2)
Then("The correct order is maintained")
ping should have size 6
ping(key(dbV2)) should be < ping(key(serviceV2))
ping(key(serviceV2)) should be < ping(key(frontendV2))
WaitTestSupport.validFor("frontend v1 is available as well as all v2", 15.seconds) {
frontendV1.pingSince(2.seconds) &&
dbV2.pingSince(2.seconds) &&
serviceV2.pingSince(2.seconds) &&
frontendV2.pingSince(2.seconds)
}
When("The v2 frontend becomes healthy")
frontendV2.state = true
Then("The deployment can be finished. All v1 apps are destroyed and all v2 apps are healthy.")
waitForChange(upgrade)
List(dbV1, serviceV1, frontendV1).foreach(_.pinged = false)
WaitTestSupport.validFor("all v2 apps are alive", 15.seconds) {
!dbV1.pinged && !serviceV1.pinged && !frontendV1.pinged &&
dbV2.pingSince(2.seconds) && serviceV2.pingSince(2.seconds) && frontendV2.pingSince(2.seconds)
}
}
}
| Java |
package com.linbo.algs.examples.queues;
import java.util.Iterator;
import com.linbo.algs.util.StdRandom;
/**
* Created by @linbojin on 13/1/17.
* Ref: http://coursera.cs.princeton.edu/algs4/assignments/queues.html
* RandomizedQueue: a double-ended queue or deque (pronounced "deck") is a
* generalization of a stack and a queue that supports adding and removing
* items from either the front or the back of the data structure.
*/
public class RandomizedQueue<Item> implements Iterable<Item> {
// Memory: 16 + 8 + 4 + 4 + 4 + 4 + 24 + N * 4 * 2
// = 64 + 8N
private Item[] q; // queue elements
private int size; // number of elements on queue
private int first; // index of first element of queue
private int last; // index of next available slot
// construct an empty randomized queue
public RandomizedQueue() {
q = (Item[]) new Object[2];
size = 0;
first = 0;
last = 0;
}
// is the queue empty?
public boolean isEmpty() {
return size == 0;
}
// return the number of items on the queue
public int size() {
return size;
}
// resize the underlying array
private void resize(int capacity) {
assert capacity >= size;
Item[] temp = (Item[]) new Object[capacity];
for (int i = 0; i < size; i++) {
temp[i] = q[(first + i) % q.length];
}
q = temp;
first = 0;
last = size;
}
// add the item
public void enqueue(Item item) {
if (item == null) {
throw new java.lang.NullPointerException("Input item can not be null!");
}
// double size of array if necessary and recopy to front of array
if (size == q.length) resize(2 * q.length); // double size of array if necessary
q[last++] = item; // add item
if (last == q.length) last = 0; // wrap-around
size++;
}
// remove and return a random item
public Item dequeue() {
if (isEmpty()) {
throw new java.util.NoSuchElementException("Queue is empty!");
}
int index = StdRandom.uniform(size) + first;
int i = index % q.length;
Item item = q[i];
last = (last + q.length - 1) % q.length;
if (i != last) {
q[i] = q[last];
}
q[last] = null;
size--;
// shrink size of array if necessary
if (size > 0 && size == q.length / 4) resize(q.length / 2);
return item;
}
// return (but do not remove) a random item
public Item sample() {
if (isEmpty()) {
throw new java.util.NoSuchElementException("Queue is empty!");
}
int index = StdRandom.uniform(size) + first;
return q[index % q.length];
}
// an independent iterator over items in random order
public Iterator<Item> iterator() {
return new ArrayIterator();
}
// an iterator, doesn't implement remove() since it's optional
private class ArrayIterator implements Iterator<Item> {
private int i = 0;
private int[] inxArr;
public ArrayIterator() {
inxArr = StdRandom.permutation(size);
}
public boolean hasNext() {
return i < size;
}
public void remove() {
throw new UnsupportedOperationException();
}
public Item next() {
if (!hasNext()) throw new java.util.NoSuchElementException();
Item item = q[(inxArr[i] + first) % q.length];
i++;
return item;
}
}
// unit testing (optional)
public static void main(String[] args) {
RandomizedQueue<Integer> rq = new RandomizedQueue<Integer>();
System.out.println(rq.isEmpty());
rq.enqueue(1);
rq.enqueue(2);
rq.enqueue(3);
rq.enqueue(4);
rq.enqueue(5);
for (int i : rq) {
System.out.print(i);
System.out.print(" ");
}
System.out.println("\n*******");
System.out.println(rq.sample());
System.out.println(rq.size()); // 5
System.out.println("*******");
System.out.println(rq.isEmpty());
System.out.println(rq.dequeue());
System.out.println(rq.dequeue());
System.out.println(rq.sample());
System.out.println(rq.size()); // 3
System.out.println("*******");
System.out.println(rq.dequeue());
System.out.println(rq.dequeue());
System.out.println(rq.size()); // 1
System.out.println("*******");
System.out.println(rq.sample());
System.out.println(rq.dequeue());
System.out.println(rq.size()); // 0
System.out.println("*******");
RandomizedQueue<Integer> rqOne = new RandomizedQueue<Integer>();
System.out.println(rq.size());
rq.enqueue(4);
System.out.println(rq.size());
rq.enqueue(5);
System.out.println(rq.dequeue());
}
}
| Java |
/*
* 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.xerces.impl.scd;
import java.util.ArrayList;
import java.util.List;
import org.apache.xerces.util.NamespaceSupport;
import org.apache.xerces.xni.NamespaceContext;
import org.apache.xerces.xni.QName;
import org.apache.xerces.util.XML11Char;
//import org.apache.xml.serializer.utils.XML11Char;
/**
* This class handles the parsing of relative/incomplete SCDs/SCPs
* @author Ishan Jayawardena udeshike@gmail.com
* @version $Id$
*/
class SCDParser {
private List steps;
private static final int CHARTYPE_AT = 1; // @
private static final int CHARTYPE_TILDE = 2; // ~
private static final int CHARTYPE_PERIOD = 3; // .
private static final int CHARTYPE_STAR = 4; // *
private static final int CHARTYPE_ZERO = 5; // 0
private static final int CHARTYPE_1_THROUGH_9 = 6; // [1-9]
private static final int CHARTYPE_NC_NAMESTART = 7; // XML11Char.NCNameStart
private static final int CHARTYPE_NC_NAME = 8; // XML11Char.NCName
private static final int CHARTYPE_OPEN_BRACKET = 9; // [
private static final int CHARTYPE_CLOSE_BRACKET = 10;// ]
private static final int CHARTYPE_OPEN_PAREN = 11; // (
private static final int CHARTYPE_CLOSE_PAREN = 12; // )
private static final int CHARTYPE_COLON = 13; // :
private static final int CHARTYPE_SLASH = 14; // /
private static final int CHARTYPE_NOMORE = 0;
private static final short LIST_SIZE = 15;
public SCDParser() {
steps = new ArrayList(LIST_SIZE);
}
private static int getCharType(int c) throws SCDException {
switch (c) {
case '@':
return CHARTYPE_AT;
case '~':
return CHARTYPE_TILDE;
case '.':
return CHARTYPE_PERIOD;
case '*':
return CHARTYPE_STAR;
case ':':
return CHARTYPE_COLON;
case '/':
return CHARTYPE_SLASH;
case '(':
return CHARTYPE_OPEN_PAREN;
case ')':
return CHARTYPE_CLOSE_PAREN;
case '[':
return CHARTYPE_OPEN_BRACKET;
case ']':
return CHARTYPE_CLOSE_BRACKET;
case '0':
return CHARTYPE_ZERO;
}
if (c == CHARTYPE_NOMORE) {
return CHARTYPE_NOMORE;
}
if (c >= '1' && c <= '9') {
return CHARTYPE_1_THROUGH_9;
}
if (XML11Char.isXML11NCNameStart(c)) {
return CHARTYPE_NC_NAMESTART;
}
if (XML11Char.isXML11NCName(c)) {
return CHARTYPE_NC_NAME;
}
throw new SCDException("Error in SCP: Unsupported character "
+ (char) c + " (" + c + ")");
}
public static char charAt(String s, int position) {
if (position >= s.length()) {
return (char) -1; // TODO: throw and exception instead?
//throw new SCDException("Error in SCP: No more characters in the SCP string");
}
return s.charAt(position);
}
private static QName readQName(String step, int[] finalPosition, int currentPosition, NamespaceContext nsContext)
throws SCDException {
return readNameTest(step, finalPosition, currentPosition, nsContext);
}
/**
* TODO: this is the wild card name test
*/
public static final QName WILDCARD = new QName(null, "*", "*", null);
/**
* TODO: this is the name test zero
*/
public static final QName ZERO = new QName(null, "0", "0", null);
/*
* Similar to readQName() method. But this method additionally tests for another two types
* of name tests. i.e the wildcard name test and the zero name test.
*/
private static QName readNameTest(String step, int[] finalPosition, int currentPosition, NamespaceContext nsContext)
throws SCDException {
int initialPosition = currentPosition;
int start = currentPosition;
String prefix = ""; // for the default namespace
String localPart = null;
if (charAt(step, currentPosition) == '*') {
finalPosition[0] = currentPosition + 1;
return WILDCARD;
} else if (charAt(step, currentPosition) == '0') {
finalPosition[0] = currentPosition + 1;
return ZERO;
// prefix, localPart, rawname, uri;
} else if (XML11Char.isXML11NCNameStart(charAt(step, currentPosition))) {
while (XML11Char.isXML11NCName(charAt(step, ++currentPosition))) {}
prefix = step.substring(initialPosition, currentPosition);
if (charAt(step, currentPosition) == ':') {
if (XML11Char
.isXML11NCNameStart(charAt(step, ++currentPosition))) {
initialPosition = currentPosition;
while (XML11Char.isXML11NCName(charAt(step,
currentPosition++))) {
}
localPart = step.substring(initialPosition,
currentPosition - 1);
}
if (localPart == null) {
localPart = prefix;
prefix = "";
}
finalPosition[0] = currentPosition - 1;
} else {
finalPosition[0] = currentPosition;
localPart = prefix;
prefix = "";
}
String rawname = step.substring(start, finalPosition[0]);
if (nsContext != null) {
// it a field
String uri = nsContext.getURI(prefix.intern());
if ("".equals(prefix)) { // default namespace.
return new QName(prefix, localPart, rawname, uri);
} else if (uri != null) {
// just use uri != null test here!
return new QName(prefix, localPart, rawname, uri);
}
throw new SCDException("Error in SCP: The prefix \"" + prefix
+ "\" is undeclared in this context");
}
throw new SCDException("Error in SCP: Namespace context is null");
}
throw new SCDException("Error in SCP: Invalid nametest starting character \'"
+ charAt(step, currentPosition) + "\'");
} // readNameTest()
private static int scanNCName(String data, int currentPosition) {
if (XML11Char.isXML11NCNameStart(charAt(data, currentPosition))) {
while (XML11Char.isXML11NCName(charAt(data, ++currentPosition))) {
}
}
return currentPosition;
}
/* scans a XML namespace Scheme Data section
* [2] EscapedNamespaceName ::= EscapedData*
* [6] SchemeData ::= EscapedData*
* [7] EscapedData ::= NormalChar | '^(' | '^)' | '^^' | '(' SchemeData ')'
* [8] NormalChar ::= UnicodeChar - [()^]
* [9] UnicodeChar ::= [#x0-#x10FFFF]
*/
private static int scanXmlnsSchemeData(String data, int currentPosition) throws SCDException {
int c = 0;
int balanceParen = 0;
do {
c = charAt(data, currentPosition);
if (c >= 0x0 && c <= 0x10FFFF) { // unicode char
if (c != '^') { // normal char
++currentPosition;
if (c == '(') {
++balanceParen;
} else if (c == ')') { // can`t be empty '(' xmlnsSchemeData ')'
--balanceParen;
if (balanceParen == -1) {
// this is the end
return currentPosition - 1;
}
if (charAt(data, currentPosition - 2) == '(') {
throw new SCDException(
"Error in SCD: empty xmlns scheme data between '(' and ')'");
}
}
} else { // check if '^' is used as an escape char
if (charAt(data, currentPosition + 1) == '('
|| charAt(data, currentPosition + 1) == ')'
|| charAt(data, currentPosition + 1) == '^') {
currentPosition = currentPosition + 2;
} else {
throw new SCDException("Error in SCD: \'^\' character is used as a non escape character at position "
+ ++currentPosition);
}
}
} else {
throw new SCDException("Error in SCD: the character \'" + c + "\' at position "
+ ++currentPosition + " is invalid for xmlns scheme data");
}
} while (currentPosition < data.length());
String s = "";
if (balanceParen != -1) { // checks unbalanced l parens only.
s = "Unbalanced parentheses exist within xmlns scheme data section";
}
throw new SCDException("Error in SCD: Attempt to read an invalid xmlns Scheme data. " + s);
}
private static int skipWhiteSpaces(String data, int currentPosition) {
while (XML11Char.isXML11Space(charAt(data, currentPosition))) {
++currentPosition; // this is important
}
return currentPosition;
}
// Scans a predicate from the input string step
private static int readPredicate(String step, int[] finalPosition,
int currentPosition) throws SCDException {
// we've already seen a '['
int end = step.indexOf(']', currentPosition);
if (end >= 0) {
try {
int i = Integer.parseInt(step.substring(currentPosition, end)); // toString?
if (i > 0) {
finalPosition[0] = end + 1;
return i;
}
throw new SCDException("Error in SCP: Invalid predicate value "
+ i);
} catch (NumberFormatException e) {
e.printStackTrace();
throw new SCDException(
"Error in SCP: A NumberFormatException occurred while reading the predicate");
}
}
throw new SCDException(
"Error in SCP: Attempt to read an invalid predicate starting from position "
+ ++currentPosition);
} // readPredicate()
/**
* Processes the scp input string and seperates it into Steps
* @param scp the input string that contains an SCDParser
* @return a list of Steps contained in the SCDParser
*/
public List parseSCP(String scp, NamespaceContext nsContext, boolean isRelative)
throws SCDException {
steps.clear();
Step step;
if (scp.length() == 1 && scp.charAt(0) == '/') { // read a schema
// schema step.
//System.out.println("<SCHEMA STEP>");
steps.add(new Step(Axis.NO_AXIS, null, 0));
return steps;
}
// check if this is an incomplete SCP
if (isRelative) {
if ("./".equals(scp.substring(0, 2))) {
scp = scp.substring(1);
} else if (scp.charAt(0) != '/') {
scp = '/' + scp;
} else {
throw new SCDException("Error in incomplete SCP: Invalid starting character");
}
}
int stepStart = 0;
int[] currentPosition = new int[] { 0 };
while (currentPosition[0] < scp.length()) {
if (charAt(scp, currentPosition[0]) == '/') {
if (charAt(scp, currentPosition[0] + 1) == '/') {
if (currentPosition[0] + 1 != scp.length() - 1) {
steps.add(new Step(Axis.SPECIAL_COMPONENT, WILDCARD, 0));
stepStart = currentPosition[0] + 2;
} else {
stepStart = currentPosition[0] + 1;
}
} else {
if (currentPosition[0] != scp.length() - 1) {
stepStart = currentPosition[0] + 1;
} else {
stepStart = currentPosition[0];
}
}
step = processStep(scp, currentPosition, stepStart, nsContext);
steps.add(step);
} else { // error: invalid scp. should start with a slash
throw new SCDException("Error in SCP: Invalid character \'"
+ charAt(scp, currentPosition[0]) + " \' at position"
+ currentPosition[0]);
}
}
return steps;
}
private static Step processStep(String step, int[] newPosition, int currentPosition, NamespaceContext nsContext)
throws SCDException {
short axis = -1;
QName nameTest = null;
int predicate = 0;
switch (getCharType(charAt(step, currentPosition))) { // 0
case CHARTYPE_AT: // '@'
axis = Axis.SCHEMA_ATTRIBUTE;
nameTest = readNameTest(step, newPosition, currentPosition + 1,
nsContext); // 1 handles *, 0, and QNames.
break;
case CHARTYPE_TILDE: // '~'
axis = Axis.TYPE;
nameTest = readNameTest(step, newPosition, currentPosition + 1,
nsContext); // 1
break;
case CHARTYPE_PERIOD: // '.'
axis = Axis.CURRENT_COMPONENT;
nameTest = WILDCARD;
newPosition[0] = currentPosition + 1;
break;
case CHARTYPE_ZERO: // '0'
axis = Axis.SCHEMA_ELEMENT; // Element without a name. This will
// never match anything.
nameTest = ZERO;
newPosition[0] = currentPosition + 1;
break;
case CHARTYPE_STAR: // '*'
axis = Axis.SCHEMA_ELEMENT;
nameTest = WILDCARD;
newPosition[0] = currentPosition + 1;
break;
case CHARTYPE_NC_NAMESTART: // isXML11NCNameStart()
QName name = readQName(step, newPosition, currentPosition,
nsContext); // 0 handles a and a:b
int newPos = newPosition[0];
if (newPosition[0] == step.length()) {
axis = Axis.SCHEMA_ELEMENT;
nameTest = name;
} else if (charAt(step, newPos) == ':'
&& charAt(step, newPos + 1) == ':') {
// TODO: what to do with extension axes?
// Could be a hashtable look up; fail if extension axis
axis = Axis.qnameToAxis(name.rawname);
if (axis == Axis.EXTENSION_AXIS) {
throw new SCDException(
"Error in SCP: Extension axis {"+name.rawname+"} not supported!");
}
nameTest = readNameTest(step, newPosition, newPos + 2,
nsContext);
} else if (charAt(step, newPos) == '(') {
throw new SCDException(
"Error in SCP: Extension accessor not supported!");
} else if (charAt(step, newPos) == '/') { // /abc:def/...
axis = Axis.SCHEMA_ELEMENT;
nameTest = name;
return new Step(axis, nameTest, predicate);
} else { // /abc:def[6]
axis = Axis.SCHEMA_ELEMENT;
nameTest = name;
}
break;
default:
throw new SCDException("Error in SCP: Invalid character \'"
+ charAt(step, currentPosition) + "\' at position "
+ currentPosition);
}
if (newPosition[0] < step.length()) {
if (charAt(step, newPosition[0]) == '[') {
predicate = readPredicate(step, newPosition, newPosition[0] + 1); // Also consumes right-bracket
} else if (charAt(step, newPosition[0]) == '/') { // /a::a/a...
return new Step(axis, nameTest, predicate);
} else {
throw new SCDException("Error in SCP: Unexpected character \'"
+ charAt(step, newPosition[0]) + "\' at position "
+ newPosition[0]);
}
// TODO: handle what if not?
}
if (charAt(step, newPosition[0]) == '/') {// /abc:def[6]/...
return new Step(axis, nameTest, predicate);
}
if (newPosition[0] < step.length()) {
throw new SCDException("Error in SCP: Unexpected character \'"
+ step.charAt(newPosition[0]) + "\' at the end");
}
return new Step(axis, nameTest, predicate);
} // processStep()
/**
* Creates a list of Step objects from the input relative SCD string by
* parsing it
* @param relativeSCD
* @param isIncompleteSCD if the relative SCD in the first parameter an incomplete SCD
* @return the list of Step objects
*/
public List parseRelativeSCD(String relativeSCD, boolean isIncompleteSCD) throws SCDException {
// xmlns(p=http://example.com/schema/po)xscd(/type::p:USAddress)
int[] currentPosition = new int[] { 0 };
NamespaceContext nsContext = new NamespaceSupport();
//System.out.println("Relative SCD## " + relativeSCD);
while (currentPosition[0] < relativeSCD.length()) {
if ("xmlns".equals(relativeSCD.substring(currentPosition[0], currentPosition[0] + 5))) { // TODO catch string out of bound exception
currentPosition[0] = readxmlns(relativeSCD, nsContext, currentPosition[0] + 5);
} else if ("xscd".equals(relativeSCD.substring(currentPosition[0], currentPosition[0] + 4))) { // (/type::p:USAddress) part
// process xscd() part
String data = relativeSCD.substring(currentPosition[0] + 4, relativeSCD.length());
if (charAt(data, 0) == '('
&& charAt(data, data.length() - 1) == ')') {
return parseSCP(data.substring(1, data.length() - 1), nsContext, isIncompleteSCD);
}
throw new SCDException("Error in SCD: xscd() part is invalid at position "
+ ++currentPosition[0]);
} else {
throw new SCDException("Error in SCD: Expected \'xmlns\' or \'xscd\' at position "
+ ++currentPosition[0]);
}
}
throw new SCDException("Error in SCD: Error at position "
+ ++currentPosition[0]);
} // createSteps()
private static int readxmlns(String data, NamespaceContext nsContext,
int currentPosition) throws SCDException {
if (charAt(data, currentPosition++) == '(') {
// readNCName
int pos = currentPosition;
currentPosition = scanNCName(data, currentPosition);
if (currentPosition == pos) {
throw new SCDException(
"Error in SCD: Missing namespace name at position "
+ ++currentPosition);
}
String name = data.substring(pos, currentPosition);
// skip S
currentPosition = skipWhiteSpaces(data, currentPosition);
// read '='
if (charAt(data, currentPosition) != '=') {
throw new SCDException("Error in SCD: Expected a \'=\' character at position "
+ ++currentPosition);
}
// skip S
currentPosition = skipWhiteSpaces(data, ++currentPosition);
// read uri
pos = currentPosition;
currentPosition = scanXmlnsSchemeData(data, currentPosition);
if (currentPosition == pos) {
throw new SCDException("Error in SCD: Missing namespace value at position "
+ ++currentPosition);
}
String uri = data.substring(pos, currentPosition);
if (charAt(data, currentPosition) == ')') {
nsContext.declarePrefix(name.intern(), uri.intern());
return ++currentPosition;
}
throw new SCDException("Error in SCD: Invalid xmlns pointer part at position "
+ ++currentPosition);
}
throw new SCDException("Error in SCD: Invalid xmlns pointer part at position "
+ ++currentPosition);
} // readxmlns()
}
| Java |
/*
Copyright 2011 LinkedIn Corporation
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.linkedin.sample;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.LinkedInApi;
import org.scribe.model.*;
import org.scribe.oauth.OAuthService;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
private static final String PROTECTED_RESOURCE_URL = "http://api.linkedin.com/v1/people/~/connections:(y,last-name)";
private static String API_KEY = "77mahxt83mbma8";
private static String API_SECRET = "vpSWVa01dWq4dFfO";
public static void main(String[] args) {
/*
we need a OAuthService to handle authentication and the subsequent calls.
Since we are going to use the REST APIs we need to generate a request token as the first step in the call.
Once we get an access toke we can continue to use that until the API key changes or auth is revoked.
Therefore, to make this sample easier to re-use we serialize the AuthHandler (which stores the access token) to
disk and then reuse it.
When you first run this code please insure that you fill in the API_KEY and API_SECRET above with your own
credentials and if there is a service.dat file in the code please delete it.
*/
//The Access Token is used in all Data calls to the APIs - it basically says our application has been given access
//to the approved information in LinkedIn
//Token accessToken = null;
//Using the Scribe library we enter the information needed to begin the chain of Oauth2 calls.
OAuthService service = new ServiceBuilder()
.provider(LinkedInApi.class)
.apiKey(API_KEY)
.apiSecret(API_SECRET)
.build();
/*************************************
* This first piece of code handles all the pieces needed to be granted access to make a data call
*/
Scanner in = new Scanner(System.in);
System.out.println("=== LinkedIn's OAuth Workflow ===");
System.out.println();
// Obtain the Request Token
System.out.println("Fetching the Request Token...");
Token requestToken = service.getRequestToken();
System.out.println("Got the Request Token!");
System.out.println();
System.out.println("Now go and authorize Scribe here:");
System.out.println(service.getAuthorizationUrl(requestToken));
System.out.println("And paste the verifier here");
System.out.print(">>");
Verifier verifier = new Verifier(in.nextLine());
System.out.println();
// Trade the Request Token and Verfier for the Access Token
System.out.println("Trading the Request Token for an Access Token...");
Token accessToken = service.getAccessToken(requestToken, verifier);
System.out.println("Got the Access Token!");
System.out.println("(if your curious it looks like this: " + accessToken + " )");
System.out.println();
// Now let's go and ask for a protected resource!
System.out.println("Now we're going to access a protected resource...");
OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
service.signRequest(accessToken, request);
Response response = request.send();
System.out.println("Got it! Lets see what we found...");
System.out.println();
System.out.println(response.getBody());
System.out.println();
System.out.println("Thats it man! Go and build something awesome with Scribe! :)");
}
/*try{
File file = new File("service.txt");
if(file.exists()){
//if the file exists we assume it has the AuthHandler in it - which in turn contains the Access Token
ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(file));
AuthHandler authHandler = (AuthHandler) inputStream.readObject();
accessToken = authHandler.getAccessToken();
} else {
System.out.println("There is no stored Access token we need to make one");
//In the constructor the AuthHandler goes through the chain of calls to create an Access Token
AuthHandler authHandler = new AuthHandler(service);
System.out.println("test");
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("service.txt"));
outputStream.writeObject( authHandler);
outputStream.close();
accessToken = authHandler.getAccessToken();
}
}catch (Exception e){
System.out.println("Threw an exception when serializing: " + e.getClass() + " :: " + e.getMessage());
}
*//*
* We are all done getting access - time to get busy getting data
*************************************//*
*//**************************
*
* Querying the LinkedIn API
*
**************************//*
System.out.println();
System.out.println("********A basic user profile call********");
//The ~ means yourself - so this should return the basic default information for your profile in XML format
//https://developer.linkedin.com/documents/profile-api
String url = "http://api.linkedin.com/v1/people/~";
OAuthRequest request = new OAuthRequest(Verb.GET, url);
service.signRequest(accessToken, request);
Response response = request.send();
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********Get the profile in JSON********");
//This basic call profile in JSON format
//You can read more about JSON here http://json.org
url = "http://api.linkedin.com/v1/people/~";
request = new OAuthRequest(Verb.GET, url);
request.addHeader("x-li-format", "json");
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********Get the profile in JSON using query parameter********");
//This basic call profile in JSON format. Please note the call above is the preferred method.
//You can read more about JSON here http://json.org
url = "http://api.linkedin.com/v1/people/~";
request = new OAuthRequest(Verb.GET, url);
request.addQuerystringParameter("format", "json");
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********Get my connections - going into a resource********");
//This basic call gets all your connections each one will be in a person tag with some profile information
//https://developer.linkedin.com/documents/connections-api
url = "http://api.linkedin.com/v1/people/~/connections";
request = new OAuthRequest(Verb.GET, url);
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********Get only 10 connections - using parameters********");
//This basic call gets only 10 connections - each one will be in a person tag with some profile information
//https://developer.linkedin.com/documents/connections-api
//more basic about query strings in a URL here http://en.wikipedia.org/wiki/Query_string
url = "http://api.linkedin.com/v1/people/~/connections";
request = new OAuthRequest(Verb.GET, url);
request.addQuerystringParameter("count", "10");
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********GET network updates that are CONN and SHAR********");
//This basic call get connection updates from your connections
//https://developer.linkedin.com/documents/get-network-updates-and-statistics-api
//specifics on updates https://developer.linkedin.com/documents/network-update-types
url = "http://api.linkedin.com/v1/people/~/network/updates";
request = new OAuthRequest(Verb.GET, url);
request.addQuerystringParameter("type","SHAR");
request.addQuerystringParameter("type","CONN");
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********People Search using facets and Encoding input parameters i.e. UTF8********");
//This basic call get connection updates from your connections
//https://developer.linkedin.com/documents/people-search-api#Facets
//Why doesn't this look like
//people-search?title=developer&location=fr&industry=4
//url = "http://api.linkedin.com/v1/people-search?title=D%C3%A9veloppeur&facets=location,industry&facet=location,fr,0";
url = "http://api.linkedin.com/v1/people-search:(people:(first-name,last-name,headline),facets:(code,buckets))";
request = new OAuthRequest(Verb.GET, url);
request.addQuerystringParameter("title", "Développeur");
request.addQuerystringParameter("facet", "industry,4");
request.addQuerystringParameter("facets", "location,industry");
System.out.println(request.getUrl());
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getBody());
System.out.println();System.out.println();
/////////////////field selectors
System.out.println("********A basic user profile call with field selectors********");
//The ~ means yourself - so this should return the basic default information for your profile in XML format
//https://developer.linkedin.com/documents/field-selectors
url = "http://api.linkedin.com/v1/people/~:(first-name,last-name,positions)";
request = new OAuthRequest(Verb.GET, url);
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getHeaders().toString());
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********A basic user profile call with field selectors going into a subresource********");
//The ~ means yourself - so this should return the basic default information for your profile in XML format
//https://developer.linkedin.com/documents/field-selectors
url = "http://api.linkedin.com/v1/people/~:(first-name,last-name,positions:(company:(name)))";
request = new OAuthRequest(Verb.GET, url);
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getHeaders().toString());
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********A basic user profile call into a subresource return data in JSON********");
//The ~ means yourself - so this should return the basic default information for your profile
//https://developer.linkedin.com/documents/field-selectors
url = "https://api.linkedin.com/v1/people/~/connections:(first-name,last-name,headline)?format=json";
request = new OAuthRequest(Verb.GET, url);
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getHeaders().toString());
System.out.println(response.getBody());
System.out.println();System.out.println();
System.out.println("********A more complicated example using postings into groups********");
//https://developer.linkedin.com/documents/field-selectors
//https://developer.linkedin.com/documents/groups-api
url = "http://api.linkedin.com/v1/groups/3297124/posts:(id,category,creator:(id,first-name,last-name),title,summary,creation-timestamp,site-group-post-url,comments,likes)";
request = new OAuthRequest(Verb.GET, url);
service.signRequest(accessToken, request);
response = request.send();
System.out.println(response.getHeaders().toString());
System.out.println(response.getBody());
System.out.println();System.out.println();*/
/**************************
*
* Wrting to the LinkedIn API
*
**************************/
/*
* Commented out so we don't write into your LinkedIn/Twitter feed while you are just testing out
* some code. Uncomment if you'd like to see writes in action.
*
*
System.out.println("********Write to the share - using XML********");
//This basic shares some basic information on the users activity stream
//https://developer.linkedin.com/documents/share-api
url = "http://api.linkedin.com/v1/people/~/shares";
request = new OAuthRequest(Verb.POST, url);
request.addHeader("Content-Type", "text/xml");
//Make an XML document
Document doc = DocumentHelper.createDocument();
Element share = doc.addElement("share");
share.addElement("comment").addText("Guess who is testing the LinkedIn REST APIs");
Element content = share.addElement("content");
content.addElement("title").addText("A title for your share");
content.addElement("submitted-url").addText("http://developer.linkedin.com");
share.addElement("visibility").addElement("code").addText("anyone");
request.addPayload(doc.asXML());
service.signRequest(accessToken, request);
response = request.send();
//there is no body just a header
System.out.println(response.getBody());
System.out.println(response.getHeaders().toString());
System.out.println();System.out.println();
System.out.println("********Write to the share and to Twitter - using XML********");
//This basic shares some basic information on the users activity stream
//https://developer.linkedin.com/documents/share-api
url = "http://api.linkedin.com/v1/people/~/shares";
request = new OAuthRequest(Verb.POST, url);
request.addQuerystringParameter("twitter-post","true");
request.addHeader("Content-Type", "text/xml");
//Make an XML document
doc = DocumentHelper.createDocument();
share = doc.addElement("share");
share.addElement("comment").addText("Guess who is testing the LinkedIn REST APIs and sending to twitter");
content = share.addElement("content");
content.addElement("title").addText("A title for your share");
content.addElement("submitted-url").addText("http://developer.linkedin.com");
share.addElement("visibility").addElement("code").addText("anyone");
request.addPayload(doc.asXML());
service.signRequest(accessToken, request);
response = request.send();
//there is no body just a header
System.out.println(response.getBody());
System.out.println(response.getHeaders().toString());
System.out.println();System.out.println();
System.out.println("********Write to the share and to twitter - using JSON ********");
//This basic shares some basic information on the users activity stream
//https://developer.linkedin.com/documents/share-api
//NOTE - a good troubleshooting step is to validate your JSON on jsonlint.org
url = "http://api.linkedin.com/v1/people/~/shares";
request = new OAuthRequest(Verb.POST, url);
//set the headers to the server knows what we are sending
request.addHeader("Content-Type", "application/json");
request.addHeader("x-li-format", "json");
//make the json payload using json-simple
Map<String, Object> jsonMap = new HashMap<String, Object>();
jsonMap.put("comment", "Posting from the API using JSON");
JSONObject contentObject = new JSONObject();
contentObject.put("title", "This is a another test post");
contentObject.put("submitted-url","http://www.linkedin.com");
contentObject.put("submitted-image-url", "http://press.linkedin.com/sites/all/themes/presslinkedin/images/LinkedIn_WebLogo_LowResExample.jpg");
jsonMap.put("content", contentObject);
JSONObject visibilityObject = new JSONObject();
visibilityObject.put("code", "anyone");
jsonMap.put("visibility", visibilityObject);
request.addPayload(JSONValue.toJSONString(jsonMap));
service.signRequest(accessToken, request);
response = request.send();
//again no body - just headers
System.out.println(response.getBody());
System.out.println(response.getHeaders().toString());
System.out.println();System.out.println();
*/
/**************************
*
* Understanding the response, creating logging, request and response headers
*
**************************/
/*System.out.println();
System.out.println("********A basic user profile call and response dissected********");
//This sample is mostly to help you debug and understand some of the scaffolding around the request-response cycle
//https://developer.linkedin.com/documents/debugging-api-calls
url = "https://api.linkedin.com/v1/people/~";
request = new OAuthRequest(Verb.GET, url);
service.signRequest(accessToken, request);
response = request.send();
//get all the headers
System.out.println("Request headers: " + request.getHeaders().toString());
System.out.println("Response headers: " + response.getHeaders().toString());
//url requested
System.out.println("Original location is: " + request.getHeaders().get("content-location"));
//Date of response
System.out.println("The datetime of the response is: " + response.getHeader("Date"));
//the format of the response
System.out.println("Format is: " + response.getHeader("x-li-format"));
//Content-type of the response
System.out.println("Content type is: " + response.getHeader("Content-Type") + "\n\n");
//get the HTTP response code - such as 200 or 404
int responseNumber = response.getCode();
if(responseNumber >= 199 && responseNumber < 300){
System.out.println("HOORAY IT WORKED!!");
System.out.println(response.getBody());
} else if (responseNumber >= 500 && responseNumber < 600){
//you could actually raise an exception here in your own code
System.out.println("Ruh Roh application error of type 500: " + responseNumber);
System.out.println(response.getBody());
} else if (responseNumber == 403){
System.out.println("A 403 was returned which usually means you have reached a throttle limit");
} else if (responseNumber == 401){
System.out.println("A 401 was returned which is a Oauth signature error");
System.out.println(response.getBody());
} else if (responseNumber == 405){
System.out.println("A 405 response was received. Usually this means you used the wrong HTTP method (GET when you should POST, etc).");
}else {
System.out.println("We got a different response that we should add to the list: " + responseNumber + " and report it in the forums");
System.out.println(response.getBody());
}
System.out.println();System.out.println();
System.out.println("********A basic error logging function********");
// Now demonstrate how to make a logging function which provides us the info we need to
// properly help debug issues. Please use the logged block from here when requesting
// help in the forums.
url = "https://api.linkedin.com/v1/people/FOOBARBAZ";
request = new OAuthRequest(Verb.GET, url);
service.signRequest(accessToken, request);
response = request.send();
responseNumber = response.getCode();
if(responseNumber < 200 || responseNumber >= 300){
logDiagnostics(request, response);
} else {
System.out.println("You were supposed to submit a bad request");
}
System.out.println("******Finished******");
}
private static void logDiagnostics(OAuthRequest request, Response response){
System.out.println("\n\n[********************LinkedIn API Diagnostics**************************]\n");
System.out.println("Key: |-> " + API_KEY + " <-|");
System.out.println("\n|-> [******Sent*****] <-|");
System.out.println("Headers: |-> " + request.getHeaders().toString() + " <-|");
System.out.println("URL: |-> " + request.getUrl() + " <-|");
System.out.println("Query Params: |-> " + request.getQueryStringParams().toString() + " <-|");
System.out.println("Body Contents: |-> " + request.getBodyContents() + " <-|");
System.out.println("\n|-> [*****Received*****] <-|");
System.out.println("Headers: |-> " + response.getHeaders().toString() + " <-|");
System.out.println("Body: |-> " + response.getBody() + " <-|");
System.out.println("\n[******************End LinkedIn API Diagnostics************************]\n\n");
}*/
}
| Java |
/*
* Copyright 2013 Square, Inc.
* Copyright 2016 PKWARE, 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.pkware.truth.androidx.appcompat.widget;
import androidx.annotation.StringRes;
import androidx.appcompat.widget.SearchView;
import androidx.cursoradapter.widget.CursorAdapter;
import com.google.common.truth.FailureMetadata;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Propositions for {@link SearchView} subjects.
*/
public class SearchViewSubject extends AbstractLinearLayoutCompatSubject<SearchView> {
@Nullable
private final SearchView actual;
public SearchViewSubject(@Nonnull FailureMetadata failureMetadata, @Nullable SearchView actual) {
super(failureMetadata, actual);
this.actual = actual;
}
public void hasImeOptions(int options) {
check("getImeOptions()").that(actual.getImeOptions()).isEqualTo(options);
}
public void hasInputType(int type) {
check("getInputType()").that(actual.getInputType()).isEqualTo(type);
}
public void hasMaximumWidth(int width) {
check("getMaxWidth()").that(actual.getMaxWidth()).isEqualTo(width);
}
public void hasQuery(@Nullable String query) {
check("getQuery()").that(actual.getQuery().toString()).isEqualTo(query);
}
public void hasQueryHint(@Nullable String hint) {
CharSequence actualHint = actual.getQueryHint();
String actualHintString;
if (actualHint == null) {
actualHintString = null;
} else {
actualHintString = actualHint.toString();
}
check("getQueryHint()").that(actualHintString).isEqualTo(hint);
}
public void hasQueryHint(@StringRes int resId) {
hasQueryHint(actual.getContext().getString(resId));
}
public void hasSuggestionsAdapter(@Nullable CursorAdapter adapter) {
check("getSuggestionsAdapter()").that(actual.getSuggestionsAdapter()).isSameInstanceAs(adapter);
}
public void isIconifiedByDefault() {
check("isIconfiedByDefault()").that(actual.isIconfiedByDefault()).isTrue();
}
public void isNotIconifiedByDefault() {
check("isIconfiedByDefault()").that(actual.isIconfiedByDefault()).isFalse();
}
public void isIconified() {
check("isIconified()").that(actual.isIconified()).isTrue();
}
public void isNotIconified() {
check("isIconified()").that(actual.isIconified()).isFalse();
}
public void isQueryRefinementEnabled() {
check("isQueryRefinementEnabled()").that(actual.isQueryRefinementEnabled()).isTrue();
}
public void isQueryRefinementDisabled() {
check("isQueryRefinementEnabled()").that(actual.isQueryRefinementEnabled()).isFalse();
}
public void isSubmitButtonEnabled() {
check("isSubmitButtonEnabled()").that(actual.isSubmitButtonEnabled()).isTrue();
}
public void isSubmitButtonDisabled() {
check("isSubmitButtonEnabled()").that(actual.isSubmitButtonEnabled()).isFalse();
}
}
| Java |
/*
JustMock Lite
Copyright © 2010-2015 Progress Software Corporation
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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Telerik.JustMock.Core.Castle.Core;
namespace Telerik.JustMock.Core
{
internal static class ExpressionUtil
{
public static object EvaluateExpression(this Expression expr)
{
while (expr.NodeType == ExpressionType.Convert)
{
var unary = expr as UnaryExpression;
if (unary.Type.IsAssignableFrom(unary.Operand.Type))
expr = unary.Operand;
else break;
}
var constant = expr as ConstantExpression;
if (constant != null)
return constant.Value;
bool canCallGetField = true;
#if COREFX
canCallGetField = ProfilerInterceptor.IsProfilerAttached;
#endif
if (canCallGetField)
{
var memberAccess = expr as MemberExpression;
if (memberAccess != null)
{
var asField = memberAccess.Member as FieldInfo;
if (asField != null)
{
return SecuredReflectionMethods.GetField(asField, memberAccess.Expression != null
? memberAccess.Expression.EvaluateExpression() : null);
}
}
}
#if !DOTNET35
var listInit = expr as ListInitExpression;
if (listInit != null)
{
var collection = Expression.Variable(listInit.NewExpression.Type);
var block = new List<Expression>
{
Expression.Assign(collection, listInit.NewExpression)
};
block.AddRange(listInit.Initializers.Select(init => Expression.Call(collection, init.AddMethod, init.Arguments.ToArray())));
block.Add(collection);
expr = Expression.Block(new[] { collection }, block.ToArray());
}
#endif
var lambda = Expression.Lambda(Expression.Convert(expr, typeof(object)));
var delg = (Func<object>)lambda.Compile();
return ProfilerInterceptor.GuardExternal(delg);
}
public static object[] GetArgumentsFromConstructorExpression(this LambdaExpression expression)
{
var newExpr = (NewExpression)expression.Body;
return newExpr.Arguments.Select(arg => arg.EvaluateExpression()).ToArray();
}
public static string ConvertMockExpressionToString(Expression expr)
{
string result = expr.Type.ToString();
var replacer = new ClosureWithSafeParameterReplacer();
var lambda = expr as LambdaExpression;
if (lambda != null)
expr = lambda.Body;
expr = replacer.Visit(expr);
var cleanedExpr = MakeVoidLambda(expr, replacer.Parameters);
result = cleanedExpr.ToString();
result = replacer.CleanExpressionString(result);
return result;
}
private static LambdaExpression MakeVoidLambda(Expression body, List<ParameterExpression> parameters)
{
Type delegateType = null;
switch (parameters.Count)
{
case 0: delegateType = typeof(Action); break;
case 1: delegateType = typeof(Action<>); break;
case 2: delegateType = typeof(Action<,>); break;
case 3: delegateType = typeof(Action<,,>); break;
case 4: delegateType = typeof(Action<,,,>); break;
default:
delegateType = typeof(ExpressionUtil).Assembly.GetType("Telerik.JustMock.Action`" + parameters.Count);
break;
}
if (delegateType != null)
{
if (delegateType.IsGenericTypeDefinition)
{
delegateType = delegateType.MakeGenericType(parameters.Select(p => p.Type).ToArray());
}
return Expression.Lambda(delegateType, body, parameters.ToArray());
}
else
return Expression.Lambda(body, parameters.ToArray());
}
private class ClosureWithSafeParameterReplacer : Telerik.JustMock.Core.Expressions.ExpressionVisitor
{
public readonly List<ParameterExpression> Parameters = new List<ParameterExpression>();
public readonly Dictionary<string, string> ReplacementValues = new Dictionary<string, string>();
private readonly Dictionary<object, string> stringReplacements = new Dictionary<object, string>(ReferenceEqualityComparer<object>.Instance);
private bool hasMockReplacement;
protected override Expression VisitConstant(ConstantExpression c)
{
if (c.Type.IsCompilerGenerated())
return Expression.Parameter(c.Type, "__compiler_generated__");
if (!hasMockReplacement && c.Type.IsProxy() || (c.Value != null && c.Value.GetType().IsProxy()))
{
hasMockReplacement = true;
var param = Expression.Parameter(c.Type, "x");
this.Parameters.Add(param);
return param;
}
if (c.Value != null)
{
string name;
var value = c.Value;
if (!this.stringReplacements.TryGetValue(value, out name))
{
name = String.Format("__string_replacement_{0}__", this.stringReplacements.Count);
this.stringReplacements.Add(value, name);
var valueStr = "<Exception>";
try
{
valueStr = ProfilerInterceptor.GuardExternal(() => value.ToString());
}
catch { }
if (String.IsNullOrEmpty(valueStr))
{
valueStr = "#" + this.stringReplacements.Count;
}
this.ReplacementValues.Add(name, valueStr);
}
var param = Expression.Parameter(c.Type, name);
this.Parameters.Add(param);
return param;
}
return base.VisitConstant(c);
}
public string CleanExpressionString(string result)
{
result = result.Replace("__compiler_generated__.", "");
foreach (var strReplacement in this.ReplacementValues.Keys)
{
result = result.Replace(strReplacement, '(' + this.ReplacementValues[strReplacement] + ')');
}
return result;
}
}
}
}
| Java |
# AUTOGENERATED FILE
FROM balenalib/up-squared-fedora:32-run
ENV NODE_VERSION 15.7.0
ENV YARN_VERSION 1.22.4
RUN for key in \
6A010C5166006599AA17F08146C2130DFD2497F5 \
; do \
gpg --keyserver pgp.mit.edu --recv-keys "$key" || \
gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \
gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \
done \
&& curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-x64.tar.gz" \
&& echo "8081794dc8a6a1dd46045ce5a921e227407dcf7c17ee9d1ad39e354b37526f5c node-v$NODE_VERSION-linux-x64.tar.gz" | sha256sum -c - \
&& tar -xzf "node-v$NODE_VERSION-linux-x64.tar.gz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-x64.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/test-stack@node.sh" \
&& echo "Running test-stack@node" \
&& chmod +x test-stack@node.sh \
&& bash test-stack@node.sh \
&& rm -rf test-stack@node.sh
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: Intel 64-bit (x86-64) \nOS: Fedora 32 \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v15.7.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 | Java |
/*******************************************************************************
* 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.jbeans;
import java.lang.annotation.Annotation;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
/** Represents a field that can be accessed directly if the field is public or via an associated getter or
* setter.
* The class provides a getter and a setter to set the associated field value in an object.
*
* @author Anthony (ARPT)
*/
/**
* @author anthony
*
*/
public final class FieldInfo implements BaseInfo {
/**
* Field name
*/
final String name;
/**
* Field name hashcode.
*/
final int hash;
/**
* The bean field.
*/
final Field field;
/**
* Optional setter method. If this field is public, this will contain null.
*/
final MethodInfo setter;
/**
* Optional getter method. If this field is public, this will contain null.
*/
final MethodInfo getter;
/**
* If the field is a parameterized List or Map, this field will contain the
* class type of the value stored in the list or map. in the parameter. Eg:
* List<String> it will contain String. For Map<String,Double>
* it will contain Double.
*/
final Class<?> actualType;
FieldInfo(Field field, MethodInfo getter, MethodInfo setter) {
// Get the type of the field.
//
this.actualType = BeanUtils.getActualTypeFromMethodOrField(null, field);
this.field = field;
this.setter = setter;
this.getter = getter;
this.name = field.getName().intern();
this.hash = this.name.hashCode();
}
public Field getField() {
return field;
}
public Class<?> getType() {
return field.getType();
}
public Class<?> getActualType() {
return actualType;
}
public String getName() {
return name;
}
public String toString() {
return field.getDeclaringClass().getName() + "#" + name;
}
public boolean isField() {
return field == null ? false : true;
}
/**
* Returns true if the field value can be retrieved either through the
* public field itself or through a public getter method.
*/
public final boolean isReadable() {
return (Modifier.isPublic(field.getModifiers()) || getter != null);
}
public final boolean isSettable() {
return (Modifier.isPublic(field.getModifiers()) || setter != null);
}
public final boolean isTransient() {
return (Modifier.isTransient(field.getModifiers()));
}
public final Object callGetter(Object bean) throws BeanException {
if (bean == null)
return null;
// If the field is public, get the value directly.
//
try {
if (getter != null) {
// Use the public getter. We will always attempt to use this
// FIRST!!
//
return getter.method.invoke(bean);
}
if (!Modifier.isPublic(field.getModifiers())) {
throw BeanException.fmtExcStr("Field not gettable", bean, getName(), null);
}
return field.get(bean);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw BeanException.fmtExcStr("callGetter", bean, getName(), e);
} catch (InvocationTargetException e) {
throw BeanUtils.wrapError(e.getCause());
}
}
public final void callSetter(Object bean, Object value) throws BeanException {
value = BeanUtils.cast(value, field.getType());
try {
// Use the public setter. We will always attempt to use this FIRST!!
//
if (setter != null) {
setter.method.invoke(bean, value);
return;
}
if (!Modifier.isPublic(field.getModifiers())) {
throw BeanException.fmtExcStr("Field not settable", bean, getName(), null);
}
// If the field is public, set the value directly.
//
field.set(bean, value);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw BeanException.fmtExcStr("callSetter", bean, getName(), e);
} catch (InvocationTargetException e) {
throw BeanUtils.wrapError(e.getCause());
}
}
/**
* Converts a value into a value of the bean type.
*
* @param value
* The value to convert.
* @return If the value could not be converted, the value itself is
* returned. For example: if (beanField.valueOf(strVal)==strVal)
* throw new IllegalArgumentException();
*/
public final Object valueOf(Object value) {
return BeanUtils.cast(value, actualType);
}
@Override
public <T extends Annotation> T getAnnotation(Class<T> type) {
return field.getAnnotation(type);
}
@Override
public boolean isAnnotationPresent(Class<? extends Annotation> type) {
return field.getAnnotation(type) == null ? false : true;
}
@Override
public MethodHandle getHandle(Lookup lookup, boolean setter) {
try {
if (setter)
return lookup.findSetter(field.getDeclaringClass(), name, field.getType());
else
return lookup.findGetter(field.getDeclaringClass(), name, field.getType());
} catch (IllegalAccessException | NoSuchFieldException e) {
throw new BeanException(e);
}
}
@Override
public String makeSignature(StringBuilder sb) {
sb.setLength(0);
sb.append(getType().toString());
sb.append(' ');
sb.append(getName());
return sb.toString();
}
}
| Java |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U
#
# This file is part of FI-WARE 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.
#
# For those usages not covered by the Apache version 2.0 License please
# contact with opensource@tid.es
'''
Created on 16/04/2013
@author: henar
'''
import httplib
import sys
import os
from xml.dom.minidom import parse, parseString
from xml.dom.minidom import getDOMImplementation
from xml.etree.ElementTree import Element, SubElement, tostring
import md5
import httplib, urllib
import utils
token = utils.obtainToken(keystone_ip, keystone_port, user, password, project)
print(token)
headers = {'Content-Type': 'application/xml', 'X-Auth-Token': token, 'Tenant-ID': vdc}
print(headers)
print('Get products in the software catalogue: ')
resource = "/sdc/rest/catalog/product"
data1 = utils.doRequestHttpOperation(domine, port, resource, 'GET', None, headers)
dom = parseString(data1)
try:
product = (dom.getElementsByTagName('product'))[0]
productname = product.firstChild.firstChild.nodeValue
print('First product in the software catalogue: ' + productname)
except:
print ("Error in the request to get products")
sys.exit(1)
print('Get Product Details ' + product_name )
data1 = utils.doRequestHttpOperation(domine, port, "/sdc/rest/catalog/product/" + product_name, 'GET', None, headers)
print(" OK")
print('Get Product Releases ' + product_name )
data1 = utils.doRequestHttpOperation(domine, port, "/sdc/rest/catalog/product/" + product_name + "/release", 'GET',
None, headers)
print(" OK")
print('Get Product Release Info ' + product_name + " " + product_version )
data1 = utils.doRequestHttpOperation(domine, port,
"/sdc/rest/catalog/product/" + product_name + "/release/" + product_version, 'GET', None, headers)
print(" OK")
print('Get Product Attributes ' + product_name )
data1 = utils.doRequestHttpOperation(domine, port, "/sdc/rest/catalog/product/" + product_name + '/attributes', 'GET',
None, headers)
print(" OK")
resource_product_instance = "/sdc/rest/vdc/" + vdc + "/productInstance"
print('Install a product in VM. Product ' + product_name )
productInstanceDto = utils.createProductInstanceDto(vm_ip, vm_fqn, product_name, product_version)
print (tostring(productInstanceDto))
task = utils.doRequestHttpOperation(domine, port, resource_product_instance, 'POST', tostring(productInstanceDto),
headers)
print (task)
status = utils.processTask(domine, port, task)
print (" " + status)
resource_get_info_product_instance = "/sdc/rest/vdc/" + vdc + "/productInstance/" + vm_fqn + '_' + product_name + '_' + product_version
print('Get Product Instance Info. Product ' + product_name )
data = utils.doRequestHttpOperation(domine, port, resource_get_info_product_instance, 'GET', None)
print(data)
status = utils.processProductInstanceStatus(data)
#if status != 'INSTALLED':
# print("Status not correct" + status)
resource_delete_product_instance = "/sdc/rest/vdc/" + vdc + "/productInstance/" + vm_fqn + '_' + product_name + '_' + product_version
print('Get Delete Product Instance ' + product_name )
task = utils.doRequestHttpOperation(domine, port, resource_delete_product_instance, 'DELETE', None)
status = utils.processTask(domine, port, task)
print(" OK")
data = utils.doRequestHttpOperation(domine, port, resource_delete_product_instance, 'GET', None)
statusProduct = utils.processProductInstanceStatus(data)
#if status != 'UNINSTALLED':
# print("Status not correct" + statusProduct)
| Java |
<!DOCTYPE html>
<html>
<head>
<title>demo</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8" src="http://192.168.1.102/apk/on.js"></script>
</head>
<body>
<font size=7 color=blue>
ver0111: <p>
<p id="log"></p>
</font>
</body>
<script type="text/javascript" charset="utf-8">
young_log("init00--");
document.addEventListener('deviceready', onDeviceReady, false);
young_log("init01--");
var ready = false;
young_log("before while.");
/*while(true)
{
if(ready == true)
{
break;
}
}
young_log("ready detected.");
*/
young_log("ready:" + ready);
//sleep(5000);
young_log("ready:" + ready);
//---------------------------
function sleep(d){
for(var t = Date.now();Date.now() - t <= d;);
}
function young_log(message)
{
document.getElementById("log").innerHTML += (message + "<p>");
}
</script>
</html>
| Java |
package command
import (
"testing"
"github.com/funkygao/assert"
"github.com/funkygao/gocli"
)
func TestValidateLogDirs(t *testing.T) {
d := Deploy{Ui: &cli.BasicUi{}}
type fixture struct {
dirs string
expected string
}
fixtures := []fixture{
{"/non-exist/kfk_demo", "/non-exist/kfk_demo"},
{"/non-exist/kfk_demo/", "/non-exist/kfk_demo/"},
{"/tmp/kfk_demo", ""},
{"/tmp/kfk_demo/", ""},
{"/kfk_demo1", ""},
{"/kfk_demo1/", ""},
}
for _, f := range fixtures {
assert.Equal(t, f.expected, d.validateLogDirs(f.dirs))
}
}
| Java |
var interfaceorg_1_1onosproject_1_1grpc_1_1Port_1_1PortStatisticsOrBuilder =
[
[ "getPacketsReceived", "interfaceorg_1_1onosproject_1_1grpc_1_1Port_1_1PortStatisticsOrBuilder.html#a190993a33fa895f9d07145f3a04f5d22", null ],
[ "getPacketsSent", "interfaceorg_1_1onosproject_1_1grpc_1_1Port_1_1PortStatisticsOrBuilder.html#ae9a71f2c48c5430a348eba326eb6d112", null ],
[ "getPort", "interfaceorg_1_1onosproject_1_1grpc_1_1Port_1_1PortStatisticsOrBuilder.html#af9c20290d571c3f0b6bf99f28ffc4005", null ]
]; | Java |
<?php
defined('SYSTEM_IN') or exit('Access Denied');
hasrule('weixin','weixin');
$operation = !empty($_GP['op']) ? $_GP['op'] : 'display';
if($operation=='detail')
{
if(!empty($_GP['id']))
{
$rule = mysqld_select('SELECT * FROM '.table('weixin_rule')." WHERE id = :id" , array(':id' =>intval($_GP['id'])));
}
if(checksubmit())
{
if(empty($_GP['id']))
{
$count = mysqld_selectcolumn('SELECT count(id) FROM '.table('weixin_rule')." WHERE keywords = :keywords" , array(':keywords' =>$_GP['keywords']));
if($count>0)
{
message('触发关键字'.$_GP['keywords']."已存在!");
}
if (!empty($_FILES['thumb']['tmp_name'])) {
file_delete($_GP['thumb_old']);
$upload = file_upload($_FILES['thumb']);
if (is_error($upload)) {
message($upload['message'], '', 'error');
}
$thumb = $upload['path'];
}
$data=array('title'=>$_GP['title'],'ruletype'=>$_GP['ruletype'],'keywords'=>$_GP['keywords'],'thumb'=>$thumb,'description'=>$_GP['description'],'url'=>$_GP['url']);
mysqld_insert('weixin_rule', $data);
message('保存成功!', 'refresh', 'success');
}else
{
if($rule['keywords']!=$_GP['keywords'])
{
$count = mysqld_selectcolumn('SELECT count(id) FROM '.table('weixin_rule')." WHERE keywords = :keywords" , array(':keywords' =>$_GP['keywords']));
if($count>0)
{
message('触发关键字'.$_GP['keywords']."已存在!");
}
}
if (!empty($_FILES['thumb']['tmp_name'])) {
file_delete($_GP['thumb_old']);
$upload = file_upload($_FILES['thumb']);
if (is_error($upload)) {
message($upload['message'], '', 'error');
}
$thumb = $upload['path'];
}
$data=array('title'=>$_GP['title'],'ruletype'=>$_GP['ruletype'],'keywords'=>$_GP['keywords'],'description'=>$_GP['description'],'url'=>$_GP['url']);
if(!empty($thumb))
{
$data['thumb']=$thumb;
}
mysqld_update('weixin_rule', $data, array('id' => $_GP['id']));
message('修改成功!', 'refresh', 'success');
}
}
include page('rule_detail');
exit;
}
if($operation=='delete'&&!empty($_GP['id']))
{
mysqld_delete('weixin_rule', array('id'=>$_GP['id']));
message('删除成功!', 'refresh', 'success');
}
$list=mysqld_selectall('SELECT * FROM '.table('weixin_rule'));
include page('rule'); | Java |
package org.corpus_tools.annis.gui.visualizers.component.tree;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.corpus_tools.annis.gui.visualizers.VisualizerInput;
import org.corpus_tools.annis.gui.visualizers.component.tree.AnnisGraphTools;
import org.corpus_tools.salt.SaltFactory;
import org.corpus_tools.salt.common.SDominanceRelation;
import org.corpus_tools.salt.core.SAnnotation;
import org.junit.jupiter.api.Test;
class AnnisGraphToolsTest {
@Test
void extractAnnotation() {
assertNull(AnnisGraphTools.extractAnnotation(null, "some_ns", "func"));
Set<SAnnotation> annos = new LinkedHashSet<>();
SAnnotation annoFunc = SaltFactory.createSAnnotation();
annoFunc.setNamespace("some_ns");
annoFunc.setName("func");
annoFunc.setValue("value");
annos.add(annoFunc);
assertEquals("value", AnnisGraphTools.extractAnnotation(annos, null, "func"));
assertEquals("value", AnnisGraphTools.extractAnnotation(annos, "some_ns", "func"));
assertNull(AnnisGraphTools.extractAnnotation(annos, "another_ns", "func"));
assertNull(AnnisGraphTools.extractAnnotation(annos, "some_ns", "anno"));
assertNull(AnnisGraphTools.extractAnnotation(annos, "another_ns", "anno"));
assertNull(AnnisGraphTools.extractAnnotation(annos, null, "anno"));
}
@Test
void isTerminalNullCheck() {
assertFalse(AnnisGraphTools.isTerminal(null, null));
VisualizerInput mockedVisInput = mock(VisualizerInput.class);
assertFalse(AnnisGraphTools.isTerminal(null, mockedVisInput));
}
@Test
void hasEdgeSubtypeForEmptyType() {
SDominanceRelation rel1 = mock(SDominanceRelation.class);
VisualizerInput input = mock(VisualizerInput.class);
// When the type is empty, this should be treated like having no type (null) at all
when(rel1.getType()).thenReturn("");
Map<String, String> mappings = new LinkedHashMap<>();
when(input.getMappings()).thenReturn(mappings);
mappings.put("edge_type", "null");
AnnisGraphTools tools = new AnnisGraphTools(input);
assertTrue(tools.hasEdgeSubtype(rel1, "null"));
SDominanceRelation rel2 = mock(SDominanceRelation.class);
when(rel1.getType()).thenReturn(null);
assertTrue(tools.hasEdgeSubtype(rel2, "null"));
}
}
| Java |
// ----------------------------------------------------------------------------
// Copyright 2007-2011, GeoTelematic Solutions, Inc.
// 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.
//
// ----------------------------------------------------------------------------
// Change History:
// 2006/08/21 Martin D. Flynn
// Initial release
// ----------------------------------------------------------------------------
package org.opengts.dbtypes;
import java.lang.*;
import java.util.*;
import java.math.*;
import java.io.*;
import java.sql.*;
import org.opengts.util.*;
import org.opengts.dbtools.*;
public class DTIPAddress
extends DBFieldType
{
// ------------------------------------------------------------------------
private IPTools.IPAddress ipAddr = null;
public DTIPAddress(IPTools.IPAddress ipAddr)
{
this.ipAddr = ipAddr;
}
public DTIPAddress(String ipAddr)
{
super(ipAddr);
this.ipAddr = new IPTools.IPAddress(ipAddr);
}
public DTIPAddress(ResultSet rs, String fldName)
throws SQLException
{
super(rs, fldName);
// set to default value if 'rs' is null
this.ipAddr = (rs != null)? new IPTools.IPAddress(rs.getString(fldName)) : null;
}
// ------------------------------------------------------------------------
public boolean isMatch(String ipAddr)
{
if (this.ipAddr != null) {
return this.ipAddr.isMatch(ipAddr);
} else {
return true;
}
}
// ------------------------------------------------------------------------
public Object getObject()
{
return this.toString();
}
public String toString()
{
return (this.ipAddr != null)? this.ipAddr.toString() : "";
}
// ------------------------------------------------------------------------
public boolean equals(Object other)
{
if (this == other) {
// same object
return true;
} else
if (other instanceof DTIPAddress) {
DTIPAddress otherList = (DTIPAddress)other;
if (otherList.ipAddr == this.ipAddr) {
// will also match if both are null
return true;
} else
if ((this.ipAddr == null) || (otherList.ipAddr == null)) {
// one is null, the other isn't
return false;
} else {
// IPAddressList match
return this.ipAddr.equals(otherList.ipAddr);
}
} else {
return false;
}
}
// ------------------------------------------------------------------------
}
| Java |
<!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_72) on Wed May 13 11:47:42 EDT 2015 -->
<title>Cassandra.describe_partitioner_result._Fields (apache-cassandra API)</title>
<meta name="date" content="2015-05-13">
<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="Cassandra.describe_partitioner_result._Fields (apache-cassandra API)";
}
//-->
</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/Cassandra.describe_partitioner_result._Fields.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="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result.html" title="class in org.apache.cassandra.thrift"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_ring_args.html" title="class in org.apache.cassandra.thrift"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html" target="_top">Frames</a></li>
<li><a href="Cassandra.describe_partitioner_result._Fields.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><a href="#enum_constant_summary">Enum Constants</a> | </li>
<li>Field | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#enum_constant_detail">Enum Constants</a> | </li>
<li>Field | </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.apache.cassandra.thrift</div>
<h2 title="Enum Cassandra.describe_partitioner_result._Fields" class="title">Enum Cassandra.describe_partitioner_result._Fields</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>java.lang.Enum<<a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_partitioner_result._Fields</a>></li>
<li>
<ul class="inheritance">
<li>org.apache.cassandra.thrift.Cassandra.describe_partitioner_result._Fields</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd>java.io.Serializable, java.lang.Comparable<<a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_partitioner_result._Fields</a>>, org.apache.thrift.TFieldIdEnum</dd>
</dl>
<dl>
<dt>Enclosing class:</dt>
<dd><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result.html" title="class in org.apache.cassandra.thrift">Cassandra.describe_partitioner_result</a></dd>
</dl>
<hr>
<br>
<pre>public static enum <span class="strong">Cassandra.describe_partitioner_result._Fields</span>
extends java.lang.Enum<<a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_partitioner_result._Fields</a>>
implements org.apache.thrift.TFieldIdEnum</pre>
<div class="block">The set of fields this struct contains, along with convenience methods for finding and manipulating them.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== ENUM CONSTANT SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="enum_constant_summary">
<!-- -->
</a>
<h3>Enum Constant Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Enum Constant Summary table, listing enum constants, and an explanation">
<caption><span>Enum Constants</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Enum Constant and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html#SUCCESS">SUCCESS</a></strong></code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== 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>static <a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_partitioner_result._Fields</a></code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html#findByName(java.lang.String)">findByName</a></strong>(java.lang.String name)</code>
<div class="block">Find the _Fields constant that matches name, or null if its not found.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_partitioner_result._Fields</a></code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html#findByThriftId(int)">findByThriftId</a></strong>(int fieldId)</code>
<div class="block">Find the _Fields constant that matches fieldId, or null if its not found.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_partitioner_result._Fields</a></code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html#findByThriftIdOrThrow(int)">findByThriftIdOrThrow</a></strong>(int fieldId)</code>
<div class="block">Find the _Fields constant that matches fieldId, throwing an exception
if it is not found.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html#getFieldName()">getFieldName</a></strong>()</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>short</code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html#getThriftFieldId()">getThriftFieldId</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_partitioner_result._Fields</a></code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html#valueOf(java.lang.String)">valueOf</a></strong>(java.lang.String name)</code>
<div class="block">Returns the enum constant of this type with the specified name.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_partitioner_result._Fields</a>[]</code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html#values()">values</a></strong>()</code>
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Enum">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Enum</h3>
<code>clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOf</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>getClass, notify, notifyAll, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ ENUM CONSTANT DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="enum_constant_detail">
<!-- -->
</a>
<h3>Enum Constant Detail</h3>
<a name="SUCCESS">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>SUCCESS</h4>
<pre>public static final <a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_partitioner_result._Fields</a> SUCCESS</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="values()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>values</h4>
<pre>public static <a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_partitioner_result._Fields</a>[] values()</pre>
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared. This method may be used to iterate
over the constants as follows:
<pre>
for (Cassandra.describe_partitioner_result._Fields c : Cassandra.describe_partitioner_result._Fields.values())
System.out.println(c);
</pre></div>
<dl><dt><span class="strong">Returns:</span></dt><dd>an array containing the constants of this enum type, in the order they are declared</dd></dl>
</li>
</ul>
<a name="valueOf(java.lang.String)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>valueOf</h4>
<pre>public static <a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_partitioner_result._Fields</a> valueOf(java.lang.String name)</pre>
<div class="block">Returns the enum constant of this type with the specified name.
The string must match <i>exactly</i> an identifier used to declare an
enum constant in this type. (Extraneous whitespace characters are
not permitted.)</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>name</code> - the name of the enum constant to be returned.</dd>
<dt><span class="strong">Returns:</span></dt><dd>the enum constant with the specified name</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.lang.IllegalArgumentException</code> - if this enum type has no constant with the specified name</dd>
<dd><code>java.lang.NullPointerException</code> - if the argument is null</dd></dl>
</li>
</ul>
<a name="findByThriftId(int)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>findByThriftId</h4>
<pre>public static <a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_partitioner_result._Fields</a> findByThriftId(int fieldId)</pre>
<div class="block">Find the _Fields constant that matches fieldId, or null if its not found.</div>
</li>
</ul>
<a name="findByThriftIdOrThrow(int)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>findByThriftIdOrThrow</h4>
<pre>public static <a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_partitioner_result._Fields</a> findByThriftIdOrThrow(int fieldId)</pre>
<div class="block">Find the _Fields constant that matches fieldId, throwing an exception
if it is not found.</div>
</li>
</ul>
<a name="findByName(java.lang.String)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>findByName</h4>
<pre>public static <a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html" title="enum in org.apache.cassandra.thrift">Cassandra.describe_partitioner_result._Fields</a> findByName(java.lang.String name)</pre>
<div class="block">Find the _Fields constant that matches name, or null if its not found.</div>
</li>
</ul>
<a name="getThriftFieldId()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getThriftFieldId</h4>
<pre>public short getThriftFieldId()</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>getThriftFieldId</code> in interface <code>org.apache.thrift.TFieldIdEnum</code></dd>
</dl>
</li>
</ul>
<a name="getFieldName()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>getFieldName</h4>
<pre>public java.lang.String getFieldName()</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>getFieldName</code> in interface <code>org.apache.thrift.TFieldIdEnum</code></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><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/Cassandra.describe_partitioner_result._Fields.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="../../../../org/apache/cassandra/thrift/Cassandra.describe_partitioner_result.html" title="class in org.apache.cassandra.thrift"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../org/apache/cassandra/thrift/Cassandra.describe_ring_args.html" title="class in org.apache.cassandra.thrift"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/apache/cassandra/thrift/Cassandra.describe_partitioner_result._Fields.html" target="_top">Frames</a></li>
<li><a href="Cassandra.describe_partitioner_result._Fields.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><a href="#enum_constant_summary">Enum Constants</a> | </li>
<li>Field | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#enum_constant_detail">Enum Constants</a> | </li>
<li>Field | </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 © 2015 The Apache Software Foundation</small></p>
</body>
</html>
| Java |
package ru.stqa.pft.mantis.appmanager;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import ru.stqa.pft.mantis.model.User;
import java.util.List;
/**
* Created by Даниил on 11.06.2017.
*/
public class DbHelper {
private final SessionFactory sessionFactory;
public DbHelper() {
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure() // configures settings from hibernate.cfg.xml
.build();
sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
}
public User getUser() {
Session session = sessionFactory.openSession();
session.beginTransaction();
List<User> result = session.createQuery("from User").list();
session.getTransaction().commit();
session.close();
return result.stream().filter((s)->(!s.getUsername().equals("administrator"))).iterator().next();
}
}
| Java |
<!-- top navbar-->
<header data-ng-include="'app/views/partials/top-navbar.html'" data-ng-class="app.theme.topbar"></header>
<!-- Sidebar-->
<aside data-ng-include="'app/views/partials/sidebar.html'" data-ng-class="app.theme.sidebar"></aside>
<!-- Main-->
<section>
<!-- Content-->
<div ui-view="" autoscroll="false" data-ng-class="app.viewAnimation" class="app"></div>
</section>
<!-- Page footer-->
<footer data-ng-include="'app/views/partials/footer.html'"></footer> | Java |
package com.mricefox.androidhorizontalcalendar.library.calendar;
import android.database.Observable;
/**
* Author:zengzifeng email:zeng163mail@163.com
* Description:
* Date:2015/12/25
*/
public class DataSetObservable extends Observable<DataSetObserver> {
public boolean hasObservers() {
synchronized (mObservers) {
return !mObservers.isEmpty();
}
}
public void notifyChanged() {
synchronized (mObservers) {//mObservers register and notify maybe in different thread
for (int i = mObservers.size() - 1; i >= 0; i--) {
mObservers.get(i).onChanged();
}
}
}
public void notifyItemRangeChanged(long from, long to) {
synchronized (mObservers) {
for (int i = mObservers.size() - 1; i >= 0; i--) {
mObservers.get(i).onItemRangeChanged(from, to);
}
}
}
}
| Java |
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaotypesURI(t *testing.T) {
convey.Convey("typesURI", t, func(ctx convey.C) {
ctx.Convey("When everything gose positive", func(ctx convey.C) {
p1 := testDao.typesURI()
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoTypeMapping(t *testing.T) {
convey.Convey("TypeMapping", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything gose positive", func(ctx convey.C) {
rmap, err := testDao.TypeMapping(c)
ctx.Convey("Then err should be nil.rmap should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rmap, convey.ShouldNotBeNil)
})
})
})
}
| Java |
/*
* Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.eclipse.ceylon.langtools.classfile;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.ceylon.langtools.classfile.TypeAnnotation.Position.TypePathEntry;
/**
* See JSR 308 specification, Section 3.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class TypeAnnotation {
TypeAnnotation(ClassReader cr) throws IOException, Annotation.InvalidAnnotation {
constant_pool = cr.getConstantPool();
position = read_position(cr);
annotation = new Annotation(cr);
}
public TypeAnnotation(ConstantPool constant_pool,
Annotation annotation, Position position) {
this.constant_pool = constant_pool;
this.position = position;
this.annotation = annotation;
}
public int length() {
int n = annotation.length();
n += position_length(position);
return n;
}
@Override
public String toString() {
try {
return "@" + constant_pool.getUTF8Value(annotation.type_index).toString().substring(1) +
" pos: " + position.toString();
} catch (Exception e) {
e.printStackTrace();
return e.toString();
}
}
public final ConstantPool constant_pool;
public final Position position;
public final Annotation annotation;
private static Position read_position(ClassReader cr) throws IOException, Annotation.InvalidAnnotation {
// Copied from ClassReader
int tag = cr.readUnsignedByte(); // TargetType tag is a byte
if (!TargetType.isValidTargetTypeValue(tag))
throw new Annotation.InvalidAnnotation("TypeAnnotation: Invalid type annotation target type value: " + String.format("0x%02X", tag));
TargetType type = TargetType.fromTargetTypeValue(tag);
Position position = new Position();
position.type = type;
switch (type) {
// instanceof
case INSTANCEOF:
// new expression
case NEW:
// constructor/method reference receiver
case CONSTRUCTOR_REFERENCE:
case METHOD_REFERENCE:
position.offset = cr.readUnsignedShort();
break;
// local variable
case LOCAL_VARIABLE:
// resource variable
case RESOURCE_VARIABLE:
int table_length = cr.readUnsignedShort();
position.lvarOffset = new int[table_length];
position.lvarLength = new int[table_length];
position.lvarIndex = new int[table_length];
for (int i = 0; i < table_length; ++i) {
position.lvarOffset[i] = cr.readUnsignedShort();
position.lvarLength[i] = cr.readUnsignedShort();
position.lvarIndex[i] = cr.readUnsignedShort();
}
break;
// exception parameter
case EXCEPTION_PARAMETER:
position.exception_index = cr.readUnsignedShort();
break;
// method receiver
case METHOD_RECEIVER:
// Do nothing
break;
// type parameter
case CLASS_TYPE_PARAMETER:
case METHOD_TYPE_PARAMETER:
position.parameter_index = cr.readUnsignedByte();
break;
// type parameter bound
case CLASS_TYPE_PARAMETER_BOUND:
case METHOD_TYPE_PARAMETER_BOUND:
position.parameter_index = cr.readUnsignedByte();
position.bound_index = cr.readUnsignedByte();
break;
// class extends or implements clause
case CLASS_EXTENDS:
int in = cr.readUnsignedShort();
if (in == 0xFFFF)
in = -1;
position.type_index = in;
break;
// throws
case THROWS:
position.type_index = cr.readUnsignedShort();
break;
// method parameter
case METHOD_FORMAL_PARAMETER:
position.parameter_index = cr.readUnsignedByte();
break;
// type cast
case CAST:
// method/constructor/reference type argument
case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:
case METHOD_INVOCATION_TYPE_ARGUMENT:
case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:
case METHOD_REFERENCE_TYPE_ARGUMENT:
position.offset = cr.readUnsignedShort();
position.type_index = cr.readUnsignedByte();
break;
// We don't need to worry about these
case METHOD_RETURN:
case FIELD:
break;
case UNKNOWN:
throw new AssertionError("TypeAnnotation: UNKNOWN target type should never occur!");
default:
throw new AssertionError("TypeAnnotation: Unknown target type: " + type);
}
{ // Write type path
int len = cr.readUnsignedByte();
List<Integer> loc = new ArrayList<Integer>(len);
for (int i = 0; i < len * TypePathEntry.bytesPerEntry; ++i)
loc.add(cr.readUnsignedByte());
position.location = Position.getTypePathFromBinary(loc);
}
return position;
}
private static int position_length(Position pos) {
int n = 0;
n += 1; // TargetType tag is a byte
switch (pos.type) {
// instanceof
case INSTANCEOF:
// new expression
case NEW:
// constructor/method reference receiver
case CONSTRUCTOR_REFERENCE:
case METHOD_REFERENCE:
n += 2; // offset
break;
// local variable
case LOCAL_VARIABLE:
// resource variable
case RESOURCE_VARIABLE:
n += 2; // table_length;
int table_length = pos.lvarOffset.length;
n += 2 * table_length; // offset
n += 2 * table_length; // length
n += 2 * table_length; // index
break;
// exception parameter
case EXCEPTION_PARAMETER:
n += 2; // exception_index
break;
// method receiver
case METHOD_RECEIVER:
// Do nothing
break;
// type parameter
case CLASS_TYPE_PARAMETER:
case METHOD_TYPE_PARAMETER:
n += 1; // parameter_index
break;
// type parameter bound
case CLASS_TYPE_PARAMETER_BOUND:
case METHOD_TYPE_PARAMETER_BOUND:
n += 1; // parameter_index
n += 1; // bound_index
break;
// class extends or implements clause
case CLASS_EXTENDS:
n += 2; // type_index
break;
// throws
case THROWS:
n += 2; // type_index
break;
// method parameter
case METHOD_FORMAL_PARAMETER:
n += 1; // parameter_index
break;
// type cast
case CAST:
// method/constructor/reference type argument
case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:
case METHOD_INVOCATION_TYPE_ARGUMENT:
case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:
case METHOD_REFERENCE_TYPE_ARGUMENT:
n += 2; // offset
n += 1; // type index
break;
// We don't need to worry about these
case METHOD_RETURN:
case FIELD:
break;
case UNKNOWN:
throw new AssertionError("TypeAnnotation: UNKNOWN target type should never occur!");
default:
throw new AssertionError("TypeAnnotation: Unknown target type: " + pos.type);
}
{
n += 1; // length
n += TypePathEntry.bytesPerEntry * pos.location.size(); // bytes for actual array
}
return n;
}
// Code duplicated from org.eclipse.ceylon.langtools.tools.javac.code.TypeAnnotationPosition
public static class Position {
public enum TypePathEntryKind {
ARRAY(0),
INNER_TYPE(1),
WILDCARD(2),
TYPE_ARGUMENT(3);
public final int tag;
private TypePathEntryKind(int tag) {
this.tag = tag;
}
}
public static class TypePathEntry {
/** The fixed number of bytes per TypePathEntry. */
public static final int bytesPerEntry = 2;
public final TypePathEntryKind tag;
public final int arg;
public static final TypePathEntry ARRAY = new TypePathEntry(TypePathEntryKind.ARRAY);
public static final TypePathEntry INNER_TYPE = new TypePathEntry(TypePathEntryKind.INNER_TYPE);
public static final TypePathEntry WILDCARD = new TypePathEntry(TypePathEntryKind.WILDCARD);
private TypePathEntry(TypePathEntryKind tag) {
if (!(tag == TypePathEntryKind.ARRAY ||
tag == TypePathEntryKind.INNER_TYPE ||
tag == TypePathEntryKind.WILDCARD)) {
throw new AssertionError("Invalid TypePathEntryKind: " + tag);
}
this.tag = tag;
this.arg = 0;
}
public TypePathEntry(TypePathEntryKind tag, int arg) {
if (tag != TypePathEntryKind.TYPE_ARGUMENT) {
throw new AssertionError("Invalid TypePathEntryKind: " + tag);
}
this.tag = tag;
this.arg = arg;
}
public static TypePathEntry fromBinary(int tag, int arg) {
if (arg != 0 && tag != TypePathEntryKind.TYPE_ARGUMENT.tag) {
throw new AssertionError("Invalid TypePathEntry tag/arg: " + tag + "/" + arg);
}
switch (tag) {
case 0:
return ARRAY;
case 1:
return INNER_TYPE;
case 2:
return WILDCARD;
case 3:
return new TypePathEntry(TypePathEntryKind.TYPE_ARGUMENT, arg);
default:
throw new AssertionError("Invalid TypePathEntryKind tag: " + tag);
}
}
@Override
public String toString() {
return tag.toString() +
(tag == TypePathEntryKind.TYPE_ARGUMENT ? ("(" + arg + ")") : "");
}
@Override
public boolean equals(Object other) {
if (! (other instanceof TypePathEntry)) {
return false;
}
TypePathEntry tpe = (TypePathEntry) other;
return this.tag == tpe.tag && this.arg == tpe.arg;
}
@Override
public int hashCode() {
return this.tag.hashCode() * 17 + this.arg;
}
}
public TargetType type = TargetType.UNKNOWN;
// For generic/array types.
// TODO: or should we use null? Noone will use this object.
public List<TypePathEntry> location = new ArrayList<TypePathEntry>(0);
// Tree position.
public int pos = -1;
// For typecasts, type tests, new (and locals, as start_pc).
public boolean isValidOffset = false;
public int offset = -1;
// For locals. arrays same length
public int[] lvarOffset = null;
public int[] lvarLength = null;
public int[] lvarIndex = null;
// For type parameter bound
public int bound_index = Integer.MIN_VALUE;
// For type parameter and method parameter
public int parameter_index = Integer.MIN_VALUE;
// For class extends, implements, and throws clauses
public int type_index = Integer.MIN_VALUE;
// For exception parameters, index into exception table
public int exception_index = Integer.MIN_VALUE;
public Position() {}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append('[');
sb.append(type);
switch (type) {
// instanceof
case INSTANCEOF:
// new expression
case NEW:
// constructor/method reference receiver
case CONSTRUCTOR_REFERENCE:
case METHOD_REFERENCE:
sb.append(", offset = ");
sb.append(offset);
break;
// local variable
case LOCAL_VARIABLE:
// resource variable
case RESOURCE_VARIABLE:
if (lvarOffset == null) {
sb.append(", lvarOffset is null!");
break;
}
sb.append(", {");
for (int i = 0; i < lvarOffset.length; ++i) {
if (i != 0) sb.append("; ");
sb.append("start_pc = ");
sb.append(lvarOffset[i]);
sb.append(", length = ");
sb.append(lvarLength[i]);
sb.append(", index = ");
sb.append(lvarIndex[i]);
}
sb.append("}");
break;
// method receiver
case METHOD_RECEIVER:
// Do nothing
break;
// type parameter
case CLASS_TYPE_PARAMETER:
case METHOD_TYPE_PARAMETER:
sb.append(", param_index = ");
sb.append(parameter_index);
break;
// type parameter bound
case CLASS_TYPE_PARAMETER_BOUND:
case METHOD_TYPE_PARAMETER_BOUND:
sb.append(", param_index = ");
sb.append(parameter_index);
sb.append(", bound_index = ");
sb.append(bound_index);
break;
// class extends or implements clause
case CLASS_EXTENDS:
sb.append(", type_index = ");
sb.append(type_index);
break;
// throws
case THROWS:
sb.append(", type_index = ");
sb.append(type_index);
break;
// exception parameter
case EXCEPTION_PARAMETER:
sb.append(", exception_index = ");
sb.append(exception_index);
break;
// method parameter
case METHOD_FORMAL_PARAMETER:
sb.append(", param_index = ");
sb.append(parameter_index);
break;
// type cast
case CAST:
// method/constructor/reference type argument
case CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:
case METHOD_INVOCATION_TYPE_ARGUMENT:
case CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:
case METHOD_REFERENCE_TYPE_ARGUMENT:
sb.append(", offset = ");
sb.append(offset);
sb.append(", type_index = ");
sb.append(type_index);
break;
// We don't need to worry about these
case METHOD_RETURN:
case FIELD:
break;
case UNKNOWN:
sb.append(", position UNKNOWN!");
break;
default:
throw new AssertionError("Unknown target type: " + type);
}
// Append location data for generics/arrays.
if (!location.isEmpty()) {
sb.append(", location = (");
sb.append(location);
sb.append(")");
}
sb.append(", pos = ");
sb.append(pos);
sb.append(']');
return sb.toString();
}
/**
* Indicates whether the target tree of the annotation has been optimized
* away from classfile or not.
* @return true if the target has not been optimized away
*/
public boolean emitToClassfile() {
return !type.isLocal() || isValidOffset;
}
/**
* Decode the binary representation for a type path and set
* the {@code location} field.
*
* @param list The bytecode representation of the type path.
*/
public static List<TypePathEntry> getTypePathFromBinary(List<Integer> list) {
List<TypePathEntry> loc = new ArrayList<TypePathEntry>(list.size() / TypePathEntry.bytesPerEntry);
int idx = 0;
while (idx < list.size()) {
if (idx + 1 == list.size()) {
throw new AssertionError("Could not decode type path: " + list);
}
loc.add(TypePathEntry.fromBinary(list.get(idx), list.get(idx + 1)));
idx += 2;
}
return loc;
}
public static List<Integer> getBinaryFromTypePath(List<TypePathEntry> locs) {
List<Integer> loc = new ArrayList<Integer>(locs.size() * TypePathEntry.bytesPerEntry);
for (TypePathEntry tpe : locs) {
loc.add(tpe.tag.tag);
loc.add(tpe.arg);
}
return loc;
}
}
// Code duplicated from org.eclipse.ceylon.langtools.tools.javac.code.TargetType
// The IsLocal flag could be removed here.
public enum TargetType {
/** For annotations on a class type parameter declaration. */
CLASS_TYPE_PARAMETER(0x00),
/** For annotations on a method type parameter declaration. */
METHOD_TYPE_PARAMETER(0x01),
/** For annotations on the type of an "extends" or "implements" clause. */
CLASS_EXTENDS(0x10),
/** For annotations on a bound of a type parameter of a class. */
CLASS_TYPE_PARAMETER_BOUND(0x11),
/** For annotations on a bound of a type parameter of a method. */
METHOD_TYPE_PARAMETER_BOUND(0x12),
/** For annotations on a field. */
FIELD(0x13),
/** For annotations on a method return type. */
METHOD_RETURN(0x14),
/** For annotations on the method receiver. */
METHOD_RECEIVER(0x15),
/** For annotations on a method parameter. */
METHOD_FORMAL_PARAMETER(0x16),
/** For annotations on a throws clause in a method declaration. */
THROWS(0x17),
/** For annotations on a local variable. */
LOCAL_VARIABLE(0x40, true),
/** For annotations on a resource variable. */
RESOURCE_VARIABLE(0x41, true),
/** For annotations on an exception parameter. */
EXCEPTION_PARAMETER(0x42, true),
/** For annotations on a type test. */
INSTANCEOF(0x43, true),
/** For annotations on an object creation expression. */
NEW(0x44, true),
/** For annotations on a constructor reference receiver. */
CONSTRUCTOR_REFERENCE(0x45, true),
/** For annotations on a method reference receiver. */
METHOD_REFERENCE(0x46, true),
/** For annotations on a typecast. */
CAST(0x47, true),
/** For annotations on a type argument of an object creation expression. */
CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT(0x48, true),
/** For annotations on a type argument of a method call. */
METHOD_INVOCATION_TYPE_ARGUMENT(0x49, true),
/** For annotations on a type argument of a constructor reference. */
CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT(0x4A, true),
/** For annotations on a type argument of a method reference. */
METHOD_REFERENCE_TYPE_ARGUMENT(0x4B, true),
/** For annotations with an unknown target. */
UNKNOWN(0xFF);
private static final int MAXIMUM_TARGET_TYPE_VALUE = 0x4B;
private final int targetTypeValue;
private final boolean isLocal;
private TargetType(int targetTypeValue) {
this(targetTypeValue, false);
}
private TargetType(int targetTypeValue, boolean isLocal) {
if (targetTypeValue < 0
|| targetTypeValue > 255)
throw new AssertionError("Attribute type value needs to be an unsigned byte: " + String.format("0x%02X", targetTypeValue));
this.targetTypeValue = targetTypeValue;
this.isLocal = isLocal;
}
/**
* Returns whether or not this TargetType represents an annotation whose
* target is exclusively a tree in a method body
*
* Note: wildcard bound targets could target a local tree and a class
* member declaration signature tree
*/
public boolean isLocal() {
return isLocal;
}
public int targetTypeValue() {
return this.targetTypeValue;
}
private static final TargetType[] targets;
static {
targets = new TargetType[MAXIMUM_TARGET_TYPE_VALUE + 1];
TargetType[] alltargets = values();
for (TargetType target : alltargets) {
if (target.targetTypeValue != UNKNOWN.targetTypeValue)
targets[target.targetTypeValue] = target;
}
for (int i = 0; i <= MAXIMUM_TARGET_TYPE_VALUE; ++i) {
if (targets[i] == null)
targets[i] = UNKNOWN;
}
}
public static boolean isValidTargetTypeValue(int tag) {
if (tag == UNKNOWN.targetTypeValue)
return true;
return (tag >= 0 && tag < targets.length);
}
public static TargetType fromTargetTypeValue(int tag) {
if (tag == UNKNOWN.targetTypeValue)
return UNKNOWN;
if (tag < 0 || tag >= targets.length)
throw new AssertionError("Unknown TargetType: " + tag);
return targets[tag];
}
}
}
| Java |
<!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_112) on Tue Sep 12 14:31:27 MST 2017 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Interface org.wildfly.swarm.netflix.ribbon.RibbonArchive (BOM: * : All 2017.9.5 API)</title>
<meta name="date" content="2017-09-12">
<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.netflix.ribbon.RibbonArchive (BOM: * : All 2017.9.5 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/netflix/ribbon/RibbonArchive.html" title="interface in org.wildfly.swarm.netflix.ribbon">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.9.5</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/netflix/ribbon/class-use/RibbonArchive.html" target="_top">Frames</a></li>
<li><a href="RibbonArchive.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.netflix.ribbon.RibbonArchive" class="title">Uses of Interface<br>org.wildfly.swarm.netflix.ribbon.RibbonArchive</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/netflix/ribbon/RibbonArchive.html" title="interface in org.wildfly.swarm.netflix.ribbon">RibbonArchive</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.netflix.ribbon">org.wildfly.swarm.netflix.ribbon</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.wildfly.swarm.netflix.ribbon">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../org/wildfly/swarm/netflix/ribbon/RibbonArchive.html" title="interface in org.wildfly.swarm.netflix.ribbon">RibbonArchive</a> in <a href="../../../../../../org/wildfly/swarm/netflix/ribbon/package-summary.html">org.wildfly.swarm.netflix.ribbon</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/netflix/ribbon/package-summary.html">org.wildfly.swarm.netflix.ribbon</a> that return <a href="../../../../../../org/wildfly/swarm/netflix/ribbon/RibbonArchive.html" title="interface in org.wildfly.swarm.netflix.ribbon">RibbonArchive</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/netflix/ribbon/RibbonArchive.html" title="interface in org.wildfly.swarm.netflix.ribbon">RibbonArchive</a></code></td>
<td class="colLast"><span class="typeNameLabel">RibbonArchive.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/netflix/ribbon/RibbonArchive.html#advertise--">advertise</a></span>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../../org/wildfly/swarm/netflix/ribbon/RibbonArchive.html" title="interface in org.wildfly.swarm.netflix.ribbon">RibbonArchive</a></code></td>
<td class="colLast"><span class="typeNameLabel">RibbonArchive.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/netflix/ribbon/RibbonArchive.html#advertise-java.lang.String-">advertise</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> serviceNames)</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/netflix/ribbon/RibbonArchive.html" title="interface in org.wildfly.swarm.netflix.ribbon">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.9.5</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/netflix/ribbon/class-use/RibbonArchive.html" target="_top">Frames</a></li>
<li><a href="RibbonArchive.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>
| Java |
<!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_60-ea) on Thu Dec 15 09:48:34 EST 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.wildfly.swarm.cdi (Public javadocs 2016.12.1 API)</title>
<meta name="date" content="2016-12-15">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<h1 class="bar"><a href="../../../../org/wildfly/swarm/cdi/package-summary.html" target="classFrame">org.wildfly.swarm.cdi</a></h1>
<div class="indexContainer">
<h2 title="Classes">Classes</h2>
<ul title="Classes">
<li><a href="CDIFraction.html" title="class in org.wildfly.swarm.cdi" target="classFrame">CDIFraction</a></li>
</ul>
</div>
</body>
</html>
| Java |
<!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_60-ea) on Tue Sep 06 12:41:42 EDT 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.wildfly.swarm.config.logging (Public javadocs 2016.9 API)</title>
<meta name="date" content="2016-09-06">
<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="org.wildfly.swarm.config.logging (Public javadocs 2016.9 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 class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.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">WildFly Swarm API, 2016.9</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/wildfly/swarm/config/jmx/configuration/package-summary.html">Prev Package</a></li>
<li><a href="../../../../../org/wildfly/swarm/config/mail/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/wildfly/swarm/config/logging/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.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">
<h1 title="Package" class="title">Package org.wildfly.swarm.config.logging</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Interface Summary table, listing interfaces, and an explanation">
<caption><span>Interface Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Interface</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/AsyncHandlerConsumer.html" title="interface in org.wildfly.swarm.config.logging">AsyncHandlerConsumer</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/AsyncHandler.html" title="class in org.wildfly.swarm.config.logging">AsyncHandler</a><T>></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/AsyncHandlerSupplier.html" title="interface in org.wildfly.swarm.config.logging">AsyncHandlerSupplier</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/AsyncHandler.html" title="class in org.wildfly.swarm.config.logging">AsyncHandler</a>></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/ConsoleHandlerConsumer.html" title="interface in org.wildfly.swarm.config.logging">ConsoleHandlerConsumer</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/ConsoleHandler.html" title="class in org.wildfly.swarm.config.logging">ConsoleHandler</a><T>></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/ConsoleHandlerSupplier.html" title="interface in org.wildfly.swarm.config.logging">ConsoleHandlerSupplier</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/ConsoleHandler.html" title="class in org.wildfly.swarm.config.logging">ConsoleHandler</a>></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/CustomFormatterConsumer.html" title="interface in org.wildfly.swarm.config.logging">CustomFormatterConsumer</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/CustomFormatter.html" title="class in org.wildfly.swarm.config.logging">CustomFormatter</a><T>></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/CustomFormatterSupplier.html" title="interface in org.wildfly.swarm.config.logging">CustomFormatterSupplier</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/CustomFormatter.html" title="class in org.wildfly.swarm.config.logging">CustomFormatter</a>></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/CustomHandlerConsumer.html" title="interface in org.wildfly.swarm.config.logging">CustomHandlerConsumer</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/CustomHandler.html" title="class in org.wildfly.swarm.config.logging">CustomHandler</a><T>></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/CustomHandlerSupplier.html" title="interface in org.wildfly.swarm.config.logging">CustomHandlerSupplier</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/CustomHandler.html" title="class in org.wildfly.swarm.config.logging">CustomHandler</a>></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/FileHandlerConsumer.html" title="interface in org.wildfly.swarm.config.logging">FileHandlerConsumer</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/FileHandler.html" title="class in org.wildfly.swarm.config.logging">FileHandler</a><T>></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/FileHandlerSupplier.html" title="interface in org.wildfly.swarm.config.logging">FileHandlerSupplier</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/FileHandler.html" title="class in org.wildfly.swarm.config.logging">FileHandler</a>></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/LogFileConsumer.html" title="interface in org.wildfly.swarm.config.logging">LogFileConsumer</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/LogFile.html" title="class in org.wildfly.swarm.config.logging">LogFile</a><T>></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/LogFileSupplier.html" title="interface in org.wildfly.swarm.config.logging">LogFileSupplier</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/LogFile.html" title="class in org.wildfly.swarm.config.logging">LogFile</a>></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/LoggerConsumer.html" title="interface in org.wildfly.swarm.config.logging">LoggerConsumer</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/Logger.html" title="class in org.wildfly.swarm.config.logging">Logger</a><T>></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/LoggerSupplier.html" title="interface in org.wildfly.swarm.config.logging">LoggerSupplier</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/Logger.html" title="class in org.wildfly.swarm.config.logging">Logger</a>></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/LoggingProfileConsumer.html" title="interface in org.wildfly.swarm.config.logging">LoggingProfileConsumer</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/LoggingProfile.html" title="class in org.wildfly.swarm.config.logging">LoggingProfile</a><T>></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/LoggingProfileSupplier.html" title="interface in org.wildfly.swarm.config.logging">LoggingProfileSupplier</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/LoggingProfile.html" title="class in org.wildfly.swarm.config.logging">LoggingProfile</a>></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/PatternFormatterConsumer.html" title="interface in org.wildfly.swarm.config.logging">PatternFormatterConsumer</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/PatternFormatter.html" title="class in org.wildfly.swarm.config.logging">PatternFormatter</a><T>></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/PatternFormatterSupplier.html" title="interface in org.wildfly.swarm.config.logging">PatternFormatterSupplier</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/PatternFormatter.html" title="class in org.wildfly.swarm.config.logging">PatternFormatter</a>></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/PeriodicRotatingFileHandlerConsumer.html" title="interface in org.wildfly.swarm.config.logging">PeriodicRotatingFileHandlerConsumer</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/PeriodicRotatingFileHandler.html" title="class in org.wildfly.swarm.config.logging">PeriodicRotatingFileHandler</a><T>></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/PeriodicRotatingFileHandlerSupplier.html" title="interface in org.wildfly.swarm.config.logging">PeriodicRotatingFileHandlerSupplier</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/PeriodicRotatingFileHandler.html" title="class in org.wildfly.swarm.config.logging">PeriodicRotatingFileHandler</a>></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/PeriodicSizeRotatingFileHandlerConsumer.html" title="interface in org.wildfly.swarm.config.logging">PeriodicSizeRotatingFileHandlerConsumer</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/PeriodicSizeRotatingFileHandler.html" title="class in org.wildfly.swarm.config.logging">PeriodicSizeRotatingFileHandler</a><T>></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/PeriodicSizeRotatingFileHandlerSupplier.html" title="interface in org.wildfly.swarm.config.logging">PeriodicSizeRotatingFileHandlerSupplier</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/PeriodicSizeRotatingFileHandler.html" title="class in org.wildfly.swarm.config.logging">PeriodicSizeRotatingFileHandler</a>></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/RootLoggerConsumer.html" title="interface in org.wildfly.swarm.config.logging">RootLoggerConsumer</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/RootLogger.html" title="class in org.wildfly.swarm.config.logging">RootLogger</a><T>></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/RootLoggerSupplier.html" title="interface in org.wildfly.swarm.config.logging">RootLoggerSupplier</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/RootLogger.html" title="class in org.wildfly.swarm.config.logging">RootLogger</a>></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/SizeRotatingFileHandlerConsumer.html" title="interface in org.wildfly.swarm.config.logging">SizeRotatingFileHandlerConsumer</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/SizeRotatingFileHandler.html" title="class in org.wildfly.swarm.config.logging">SizeRotatingFileHandler</a><T>></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/SizeRotatingFileHandlerSupplier.html" title="interface in org.wildfly.swarm.config.logging">SizeRotatingFileHandlerSupplier</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/SizeRotatingFileHandler.html" title="class in org.wildfly.swarm.config.logging">SizeRotatingFileHandler</a>></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/SyslogHandlerConsumer.html" title="interface in org.wildfly.swarm.config.logging">SyslogHandlerConsumer</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/SyslogHandler.html" title="class in org.wildfly.swarm.config.logging">SyslogHandler</a><T>></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/SyslogHandlerSupplier.html" title="interface in org.wildfly.swarm.config.logging">SyslogHandlerSupplier</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/SyslogHandler.html" title="class in org.wildfly.swarm.config.logging">SyslogHandler</a>></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/AsyncHandler.html" title="class in org.wildfly.swarm.config.logging">AsyncHandler</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/AsyncHandler.html" title="class in org.wildfly.swarm.config.logging">AsyncHandler</a><T>></td>
<td class="colLast">
<div class="block">Defines a handler which writes to the sub-handlers in an asynchronous thread.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/ConsoleHandler.html" title="class in org.wildfly.swarm.config.logging">ConsoleHandler</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/ConsoleHandler.html" title="class in org.wildfly.swarm.config.logging">ConsoleHandler</a><T>></td>
<td class="colLast">
<div class="block">Defines a handler which writes to the console.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/CustomFormatter.html" title="class in org.wildfly.swarm.config.logging">CustomFormatter</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/CustomFormatter.html" title="class in org.wildfly.swarm.config.logging">CustomFormatter</a><T>></td>
<td class="colLast">
<div class="block">A custom formatter to be used with handlers.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/CustomHandler.html" title="class in org.wildfly.swarm.config.logging">CustomHandler</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/CustomHandler.html" title="class in org.wildfly.swarm.config.logging">CustomHandler</a><T>></td>
<td class="colLast">
<div class="block">Defines a custom logging handler.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/FileHandler.html" title="class in org.wildfly.swarm.config.logging">FileHandler</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/FileHandler.html" title="class in org.wildfly.swarm.config.logging">FileHandler</a><T>></td>
<td class="colLast">
<div class="block">Defines a handler which writes to a file.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/LogFile.html" title="class in org.wildfly.swarm.config.logging">LogFile</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/LogFile.html" title="class in org.wildfly.swarm.config.logging">LogFile</a><T>></td>
<td class="colLast">
<div class="block">Log files that are available to be read.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/Logger.html" title="class in org.wildfly.swarm.config.logging">Logger</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/Logger.html" title="class in org.wildfly.swarm.config.logging">Logger</a><T>></td>
<td class="colLast">
<div class="block">Defines a logger category.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/LoggingProfile.html" title="class in org.wildfly.swarm.config.logging">LoggingProfile</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/LoggingProfile.html" title="class in org.wildfly.swarm.config.logging">LoggingProfile</a><T>></td>
<td class="colLast">
<div class="block">The configuration of the logging subsystem.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/LoggingProfile.LoggingProfileResources.html" title="class in org.wildfly.swarm.config.logging">LoggingProfile.LoggingProfileResources</a></td>
<td class="colLast">
<div class="block">Child mutators for LoggingProfile</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/PatternFormatter.html" title="class in org.wildfly.swarm.config.logging">PatternFormatter</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/PatternFormatter.html" title="class in org.wildfly.swarm.config.logging">PatternFormatter</a><T>></td>
<td class="colLast">
<div class="block">A pattern formatter to be used with handlers.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/PeriodicRotatingFileHandler.html" title="class in org.wildfly.swarm.config.logging">PeriodicRotatingFileHandler</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/PeriodicRotatingFileHandler.html" title="class in org.wildfly.swarm.config.logging">PeriodicRotatingFileHandler</a><T>></td>
<td class="colLast">
<div class="block">Defines a handler which writes to a file, rotating the log after a time
period derived from the given suffix string, which should be in a format
understood by java.text.SimpleDateFormat.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/PeriodicSizeRotatingFileHandler.html" title="class in org.wildfly.swarm.config.logging">PeriodicSizeRotatingFileHandler</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/PeriodicSizeRotatingFileHandler.html" title="class in org.wildfly.swarm.config.logging">PeriodicSizeRotatingFileHandler</a><T>></td>
<td class="colLast">
<div class="block">Defines a handler which writes to a file, rotating the log after a time
period derived from the given suffix string or after the size of the file
grows beyond a certain point and keeping a fixed number of backups.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/RootLogger.html" title="class in org.wildfly.swarm.config.logging">RootLogger</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/RootLogger.html" title="class in org.wildfly.swarm.config.logging">RootLogger</a><T>></td>
<td class="colLast">
<div class="block">Defines the root logger for this log context.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/SizeRotatingFileHandler.html" title="class in org.wildfly.swarm.config.logging">SizeRotatingFileHandler</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/SizeRotatingFileHandler.html" title="class in org.wildfly.swarm.config.logging">SizeRotatingFileHandler</a><T>></td>
<td class="colLast">
<div class="block">Defines a handler which writes to a file, rotating the log after the size of
the file grows beyond a certain point and keeping a fixed number of backups.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/SyslogHandler.html" title="class in org.wildfly.swarm.config.logging">SyslogHandler</a><T extends <a href="../../../../../org/wildfly/swarm/config/logging/SyslogHandler.html" title="class in org.wildfly.swarm.config.logging">SyslogHandler</a><T>></td>
<td class="colLast">
<div class="block">Defines a syslog handler.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<table class="typeSummary" border="0" cellpadding="3" cellspacing="0" summary="Enum Summary table, listing enums, and an explanation">
<caption><span>Enum Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Enum</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/AsyncHandler.OverflowAction.html" title="enum in org.wildfly.swarm.config.logging">AsyncHandler.OverflowAction</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/ConsoleHandler.Target.html" title="enum in org.wildfly.swarm.config.logging">ConsoleHandler.Target</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/Level.html" title="enum in org.wildfly.swarm.config.logging">Level</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/SyslogHandler.Facility.html" title="enum in org.wildfly.swarm.config.logging">SyslogHandler.Facility</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../org/wildfly/swarm/config/logging/SyslogHandler.SyslogFormat.html" title="enum in org.wildfly.swarm.config.logging">SyslogHandler.SyslogFormat</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</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 class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.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">WildFly Swarm API, 2016.9</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/wildfly/swarm/config/jmx/configuration/package-summary.html">Prev Package</a></li>
<li><a href="../../../../../org/wildfly/swarm/config/mail/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/wildfly/swarm/config/logging/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.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 © 2016 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
| Java |
define([
"settings",
"views/tags"
], function(panelSettings, TagsView) {
var PanelFileView = codebox.require("views/panels/file");
var PanelOutlineView = PanelFileView.extend({
className: "cb-panel-outline",
FileView: TagsView
});
return PanelOutlineView;
}); | Java |
package com.ticktick.testimagecropper;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import com.ticktick.imagecropper.CropImageActivity;
import com.ticktick.imagecropper.CropIntent;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
public static final int REQUEST_CODE_PICK_IMAGE = 0x1;
public static final int REQUEST_CODE_IMAGE_CROPPER = 0x2;
public static final String CROPPED_IMAGE_FILEPATH = "/sdcard/test.jpg";
private ImageView mImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = (ImageView)findViewById(R.id.CroppedImageView);
}
public void onClickButton(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent,REQUEST_CODE_PICK_IMAGE);
}
public void startCropImage( Uri uri ) {
Intent intent = new Intent(this,CropImageActivity.class);
intent.setData(uri);
intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(new File(CROPPED_IMAGE_FILEPATH)));
//intent.putExtra("aspectX",2);
//intent.putExtra("aspectY",1);
//intent.putExtra("outputX",320);
//intent.putExtra("outputY",240);
//intent.putExtra("maxOutputX",640);
//intent.putExtra("maxOutputX",480);
startActivityForResult(intent, REQUEST_CODE_IMAGE_CROPPER);
}
public void startCropImageByCropIntent( Uri uri ) {
CropIntent intent = new CropIntent();
intent.setImagePath(uri);
intent.setOutputPath(CROPPED_IMAGE_FILEPATH);
//intent.setAspect(2, 1);
//intent.setOutputSize(480,320);
//intent.setMaxOutputSize(480,320);
startActivityForResult(intent.getIntent(this), REQUEST_CODE_IMAGE_CROPPER);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
if( requestCode == REQUEST_CODE_PICK_IMAGE ) {
startCropImage(data.getData());
}
else if( requestCode == REQUEST_CODE_IMAGE_CROPPER ) {
Uri croppedUri = data.getExtras().getParcelable(MediaStore.EXTRA_OUTPUT);
InputStream in = null;
try {
in = getContentResolver().openInputStream(croppedUri);
Bitmap b = BitmapFactory.decodeStream(in);
mImageView.setImageBitmap(b);
Toast.makeText(this,"Crop success,saved at"+CROPPED_IMAGE_FILEPATH,Toast.LENGTH_LONG).show();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
| Java |
<?php
$this->pageTitle=Yii::app()->name . ' - Login';
$this->breadcrumbs=array(
'Login',
);
?>
<h1>Login</h1>
<p>Please fill out the following form with your login credentials:</p>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'login-form',
'enableAjaxValidation'=>true,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<div class="row">
<?php echo CHtml::label('Pin','pin'); ?>
<?php echo CHtml::passwordField('pin'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'username'); ?>
<?php echo $form->textField($model,'username'); ?>
<?php echo $form->error($model,'username'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'password'); ?>
<?php echo $form->passwordField($model,'password'); ?>
<?php echo $form->error($model,'password'); ?>
<!--
<p class="hint">
Hint: You may login with <tt>demo/demo</tt>.
</p>
-->
</div>
<!--
<div class="row rememberMe">
<?php //echo $form->checkBox($model,'rememberMe'); ?>
<?php //echo $form->label($model,'rememberMe'); ?>
<?php //echo $form->error($model,'rememberMe'); ?>
</div>
-->
<div class="row submit">
<?php echo CHtml::submitButton('Login'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
| Java |
/*
* 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.felix.deploymentadmin;
import java.util.StringTokenizer;
import java.util.jar.Attributes;
import org.osgi.framework.Version;
import org.osgi.service.deploymentadmin.BundleInfo;
import org.osgi.service.deploymentadmin.DeploymentException;
/**
* Implementation of the <code>BundleInfo</code> interface as defined by the OSGi mobile specification.
*/
public class BundleInfoImpl extends AbstractInfo implements BundleInfo {
private final Version m_version;
private final String m_symbolicName;
private final boolean m_customizer;
/**
* Creates an instance of this class.
*
* @param path The path / resource-id of the bundle resource.
* @param attributes Set of attributes describing the bundle resource.
* @throws DeploymentException If the specified attributes do not describe a valid bundle.
*/
public BundleInfoImpl(String path, Attributes attributes) throws DeploymentException {
super(path, attributes);
String bundleSymbolicName = attributes.getValue(org.osgi.framework.Constants.BUNDLE_SYMBOLICNAME);
if (bundleSymbolicName == null) {
throw new DeploymentException(DeploymentException.CODE_MISSING_HEADER, "Missing '" + org.osgi.framework.Constants.BUNDLE_SYMBOLICNAME + "' header for manifest entry '" + getPath() + "'");
} else if (bundleSymbolicName.trim().equals("")) {
throw new DeploymentException(DeploymentException.CODE_BAD_HEADER, "Invalid '" + org.osgi.framework.Constants.BUNDLE_SYMBOLICNAME + "' header for manifest entry '" + getPath() + "'");
} else {
m_symbolicName = parseSymbolicName(bundleSymbolicName);
}
String version = attributes.getValue(org.osgi.framework.Constants.BUNDLE_VERSION);
if (version == null || version == "") {
throw new DeploymentException(DeploymentException.CODE_BAD_HEADER, "Invalid '" + org.osgi.framework.Constants.BUNDLE_VERSION + "' header for manifest entry '" + getPath() + "'");
}
try {
m_version = Version.parseVersion(version);
} catch (IllegalArgumentException e) {
throw new DeploymentException(DeploymentException.CODE_BAD_HEADER, "Invalid '" + org.osgi.framework.Constants.BUNDLE_VERSION + "' header for manifest entry '" + getPath() + "'");
}
m_customizer = parseBooleanHeader(attributes, Constants.DEPLOYMENTPACKAGE_CUSTOMIZER);
}
/**
* Strips parameters from the bundle symbolic name such as "foo;singleton:=true".
*
* @param name full name as found in the manifest of the deployment package
* @return name without parameters
*/
private String parseSymbolicName(String name) {
// note that we don't explicitly check if there are tokens, because that
// check has already been made before we are invoked here
StringTokenizer st = new StringTokenizer(name, ";");
return st.nextToken();
}
public String getSymbolicName() {
return m_symbolicName;
}
public Version getVersion() {
return m_version;
}
/**
* Determine whether this bundle resource is a customizer bundle.
*
* @return True if the bundle is a customizer bundle, false otherwise.
*/
public boolean isCustomizer() {
return m_customizer;
}
/**
* Verify if the specified attributes describe a bundle resource.
*
* @param attributes Attributes describing the resource
* @return true if the attributes describe a bundle resource, false otherwise
*/
public static boolean isBundleResource(Attributes attributes) {
return (attributes.getValue(org.osgi.framework.Constants.BUNDLE_SYMBOLICNAME) != null);
}
}
| Java |
# Copyright 2014-2015 Isotoma 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
#
# 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.
from touchdown import ssh
from touchdown.aws.ec2.keypair import KeyPair
from touchdown.aws.iam import InstanceProfile
from touchdown.aws.vpc import SecurityGroup, Subnet
from touchdown.core import argument, errors, serializers
from touchdown.core.plan import Plan, Present
from touchdown.core.resource import Resource
from ..account import BaseAccount
from ..common import SimpleApply, SimpleDescribe, SimpleDestroy
class BlockDevice(Resource):
resource_name = "block_device"
virtual_name = argument.String(field="VirtualName")
device_name = argument.String(field="DeviceName")
disabled = argument.Boolean(field="NoDevice", serializer=serializers.Const(""))
class NetworkInterface(Resource):
resource_name = "network_interface"
public = argument.Boolean(default=False, field="AssociatePublicIpAddress")
security_groups = argument.ResourceList(SecurityGroup, field="Groups")
class Instance(Resource):
resource_name = "ec2_instance"
name = argument.String(min=3, max=128, field="Name", group="tags")
ami = argument.String(field="ImageId")
instance_type = argument.String(field="InstanceType")
key_pair = argument.Resource(KeyPair, field="KeyName")
subnet = argument.Resource(Subnet, field="SubnetId")
instance_profile = argument.Resource(
InstanceProfile,
field="IamInstanceProfile",
serializer=serializers.Dict(Name=serializers.Property("InstanceProfileName")),
)
user_data = argument.String(field="UserData")
network_interfaces = argument.ResourceList(
NetworkInterface, field="NetworkInterfaces"
)
block_devices = argument.ResourceList(
BlockDevice,
field="BlockDeviceMappings",
serializer=serializers.List(serializers.Resource()),
)
security_groups = argument.ResourceList(SecurityGroup, field="SecurityGroupIds")
tags = argument.Dict()
account = argument.Resource(BaseAccount)
class Describe(SimpleDescribe, Plan):
resource = Instance
service_name = "ec2"
api_version = "2015-10-01"
describe_action = "describe_instances"
describe_envelope = "Reservations[].Instances[]"
key = "InstanceId"
def get_describe_filters(self):
return {
"Filters": [
{"Name": "tag:Name", "Values": [self.resource.name]},
{
"Name": "instance-state-name",
"Values": [
"pending",
"running",
"shutting-down",
" stopping",
"stopped",
],
},
]
}
class Apply(SimpleApply, Describe):
create_action = "run_instances"
create_envelope = "Instances[0]"
# create_response = 'id-only'
waiter = "instance_running"
signature = (Present("name"),)
def get_create_serializer(self):
return serializers.Resource(MaxCount=1, MinCount=1)
class Destroy(SimpleDestroy, Describe):
destroy_action = "terminate_instances"
waiter = "instance_terminated"
def get_destroy_serializer(self):
return serializers.Dict(
InstanceIds=serializers.ListOfOne(serializers.Property("InstanceId"))
)
class SSHInstance(ssh.Instance):
resource_name = "ec2_instance"
input = Instance
def get_network_id(self, runner):
# FIXME: We can save on some steps if we only do this once
obj = runner.get_plan(self.adapts).describe_object()
return obj.get("VpcId", None)
def get_serializer(self, runner, **kwargs):
obj = runner.get_plan(self.adapts).describe_object()
if getattr(self.parent, "proxy", None) and self.parent.proxy.instance:
if hasattr(self.parent.proxy.instance, "get_network_id"):
network = self.parent.proxy.instance.get_network_id(runner)
if network == self.get_network_id(runner):
return serializers.Const(obj["PrivateIpAddress"])
if obj.get("PublicDnsName", ""):
return serializers.Const(obj["PublicDnsName"])
if obj.get("PublicIpAddress", ""):
return serializers.Const(obj["PublicIpAddress"])
raise errors.Error("Instance {} not available".format(self.adapts))
| Java |
package com.zlwh.hands.api.domain.base;
public class PageDomain {
private String pageNo;
private String pageSize = "15";
private long pageTime; // 上次刷新时间,分页查询时,防止分页数据错乱
public String getPageNo() {
return pageNo;
}
public void setPageNo(String pageNo) {
this.pageNo = pageNo;
}
public String getPageSize() {
return pageSize;
}
public void setPageSize(String pageSize) {
this.pageSize = pageSize;
}
public long getPageTime() {
return pageTime;
}
public void setPageTime(long pageTime) {
this.pageTime = pageTime;
}
}
| Java |
package io.github.thankpoint.security.impl;
import java.security.Provider;
import java.security.Security;
import io.github.thankpoint.security.api.provider.SecurityProviderBuilder;
/**
* Implementation of {@link SecurityProviderBuilder}.
*
* @param <B> type of the returned builder.
* @author thks
*/
public interface AbstractSecurityProviderBuilderImpl<B> extends SecurityProviderBuilder<B> {
@Override
default B provider() {
return provider((Provider) null);
}
@Override
default B provider(String name) {
return provider(Security.getProvider(name));
}
}
| Java |
<!DOCTYPE html>
<html devsite="">
<head>
<meta name="project_path" value="/dotnet/_project.yaml">
<meta name="book_path" value="/dotnet/_book.yaml">
</head>
<body>
{% verbatim %}
<div>
<article data-uid="Google.Cloud.Asset.V1.TemporalAsset.Types">
<h1 class="page-title">Class TemporalAsset.Types
</h1>
<div class="codewrapper">
<pre class="prettyprint"><code>public static class Types</code></pre>
</div>
<div class="markdown level0 summary"><p>Container for nested types declared in the TemporalAsset message type.</p>
</div>
<div class="inheritance">
<h2>Inheritance</h2>
<span><span class="xref">System.Object</span></span> <span> > </span>
<span class="xref">TemporalAsset.Types</span>
</div>
<div class="inheritedMembers expandable">
<h2 class="showalways">Inherited Members</h2>
<div>
<span class="xref">System.Object.GetHashCode()</span>
</div>
<div>
<span class="xref">System.Object.GetType()</span>
</div>
<div>
<span class="xref">System.Object.MemberwiseClone()</span>
</div>
<div>
<span class="xref">System.Object.ToString()</span>
</div>
</div>
<h2>Namespace</h2>
<a class="xref" href="Google.Cloud.Asset.V1.html">Google.Cloud.Asset.V1</a>
<h2>Assembly</h2>
<p>Google.Cloud.Asset.V1.dll</p>
</article>
</div>
{% endverbatim %}
</body>
</html>
| Java |
package com.github.saulis.enumerables;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class EmptyIterator<T> implements Iterator<T> {
@Override
public boolean hasNext() {
return false;
}
@Override
public T next() {
throw new NoSuchElementException();
}
}
| Java |
/* Copyright 2017 The TensorFlow Authors. 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.
==============================================================================*/
#include <string>
#include <vector>
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/util.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "tensorflow/core/framework/numeric_types.h"
#include "tensorflow/lite/allocation.h"
#include "tensorflow/lite/error_reporter.h"
#include "tensorflow/lite/op_resolver.h"
#include "tensorflow/lite/schema/schema_generated.h"
#include "tensorflow/lite/testing/util.h"
#include "tensorflow/lite/tools/verifier.h"
#include "tensorflow/lite/version.h"
namespace tflite {
using flatbuffers::FlatBufferBuilder;
using flatbuffers::Offset;
class MockErrorReporter : public ErrorReporter {
public:
MockErrorReporter() : buffer_size_(0) {}
int Report(const char* format, va_list args) override {
buffer_size_ = vsnprintf(buffer_, kBufferSize, format, args);
return buffer_size_;
}
int GetBufferSize() { return buffer_size_; }
string GetAsString() const { return string(buffer_, buffer_size_); }
private:
static constexpr int kBufferSize = 256;
char buffer_[kBufferSize];
int buffer_size_;
};
// Build single subgraph model.
class TfLiteFlatbufferModelBuilder {
public:
TfLiteFlatbufferModelBuilder() {
buffers_.push_back(
CreateBuffer(builder_, builder_.CreateVector(std::vector<uint8_t>{})));
}
TfLiteFlatbufferModelBuilder(const std::vector<BuiltinOperator>& builtin_ops,
const std::vector<std::string>& custom_ops) {
buffers_.push_back(
CreateBuffer(builder_, builder_.CreateVector(std::vector<uint8_t>{})));
for (const auto& iter : builtin_ops) {
resolver_.AddBuiltin(iter, &fake_op_);
}
for (const auto& iter : custom_ops) {
resolver_.AddCustom(iter.data(), &fake_op_);
}
}
void AddTensor(const std::vector<int>& shape, tflite::TensorType type,
const std::vector<uint8_t>& buffer, const char* name) {
int buffer_index = 0;
if (!buffer.empty()) {
buffer_index = buffers_.size();
buffers_.push_back(CreateBuffer(builder_, builder_.CreateVector(buffer)));
}
if (shape.empty()) {
tensors_.push_back(CreateTensorDirect(builder_, /*shape=*/nullptr, type,
buffer_index, name,
/*quantization=*/0));
return;
}
tensors_.push_back(CreateTensorDirect(builder_, &shape, type, buffer_index,
name, /*quantization=*/0));
}
void AddOperator(const std::vector<int32_t>& inputs,
const std::vector<int32_t>& outputs,
tflite::BuiltinOperator builtin_op, const char* custom_op) {
operator_codes_.push_back(
CreateOperatorCodeDirect(builder_, builtin_op, custom_op));
operators_.push_back(CreateOperator(
builder_, operator_codes_.size() - 1, builder_.CreateVector(inputs),
builder_.CreateVector(outputs), BuiltinOptions_NONE,
/*builtin_options=*/0,
/*custom_options=*/0, tflite::CustomOptionsFormat_FLEXBUFFERS));
}
void FinishModel(const std::vector<int32_t>& inputs,
const std::vector<int32_t>& outputs) {
auto subgraph = std::vector<Offset<SubGraph>>({CreateSubGraph(
builder_, builder_.CreateVector(tensors_),
builder_.CreateVector(inputs), builder_.CreateVector(outputs),
builder_.CreateVector(operators_),
builder_.CreateString("test_subgraph"))});
auto result = CreateModel(
builder_, TFLITE_SCHEMA_VERSION, builder_.CreateVector(operator_codes_),
builder_.CreateVector(subgraph), builder_.CreateString("test_model"),
builder_.CreateVector(buffers_));
tflite::FinishModelBuffer(builder_, result);
}
bool Verify() {
return tflite::Verify(builder_.GetBufferPointer(), builder_.GetSize(),
resolver_, &mock_reporter_);
}
string GetErrorString() { return mock_reporter_.GetAsString(); }
private:
FlatBufferBuilder builder_;
MutableOpResolver resolver_;
TfLiteRegistration fake_op_;
MockErrorReporter mock_reporter_;
std::vector<Offset<Operator>> operators_;
std::vector<Offset<OperatorCode>> operator_codes_;
std::vector<Offset<Tensor>> tensors_;
std::vector<Offset<Buffer>> buffers_;
};
TEST(VerifyModel, TestEmptyModel) {
FlatBufferBuilder builder;
auto model = CreateModel(builder, /*version=*/TFLITE_SCHEMA_VERSION,
/*operator_codes=*/0, /*subgraphs=*/0,
/*description=*/0, /*buffers=*/0);
::tflite::FinishModelBuffer(builder, model);
MockErrorReporter mock_reporter;
ASSERT_FALSE(Verify(builder.GetBufferPointer(), builder.GetSize(),
MutableOpResolver{}, &mock_reporter));
EXPECT_THAT(mock_reporter.GetAsString(),
::testing::ContainsRegex("Missing 'subgraphs' section."));
}
TEST(VerifyModel, TestEmptyShape) {
TfLiteFlatbufferModelBuilder builder({}, {"test"});
builder.AddOperator({0, 1}, {2}, BuiltinOperator_CUSTOM, "test");
builder.AddTensor({2, 3}, TensorType_UINT8, {1, 2, 3, 4, 5, 6}, "input");
builder.AddTensor({}, TensorType_UINT8, {1, 2, 3, 4, 5, 6}, "inputtwo");
builder.AddTensor(
{2}, TensorType_STRING,
{2, 0, 0, 0, 16, 0, 0, 0, 17, 0, 0, 0, 19, 0, 0, 0, 'A', 'B', 'C'},
"data");
builder.AddTensor({2, 3}, TensorType_INT32, {}, "output");
builder.FinishModel({0, 1}, {2});
ASSERT_FALSE(builder.Verify());
EXPECT_THAT(builder.GetErrorString(),
::testing::ContainsRegex("Tensor shape is empty"));
}
TEST(VerifyModel, TestSimpleModel) {
TfLiteFlatbufferModelBuilder builder({}, {"test"});
builder.AddOperator({0, 1}, {2}, BuiltinOperator_CUSTOM, "test");
builder.AddTensor({2, 3}, TensorType_UINT8, {1, 2, 3, 4, 5, 6}, "input");
builder.AddTensor(
{2}, TensorType_STRING,
{2, 0, 0, 0, 16, 0, 0, 0, 17, 0, 0, 0, 19, 0, 0, 0, 'A', 'B', 'C'},
"data");
builder.AddTensor({2, 3}, TensorType_INT32, {}, "output");
builder.FinishModel({0, 1}, {2});
ASSERT_TRUE(builder.Verify());
EXPECT_EQ("", builder.GetErrorString());
}
TEST(VerifyModel, TestCorruptedData) {
std::string model = "123";
MockErrorReporter mock_reporter;
ASSERT_FALSE(
Verify(model.data(), model.size(), MutableOpResolver{}, &mock_reporter));
EXPECT_THAT(mock_reporter.GetAsString(),
::testing::ContainsRegex("Invalid flatbuffer format"));
}
TEST(VerifyModel, TestUnsupportedVersion) {
FlatBufferBuilder builder;
auto model = CreateModel(builder, /*version=*/1, /*operator_codes=*/0,
/*subgraphs=*/0, /*description=*/0, /*buffers=*/0);
::tflite::FinishModelBuffer(builder, model);
MockErrorReporter mock_reporter;
ASSERT_FALSE(Verify(builder.GetBufferPointer(), builder.GetSize(),
MutableOpResolver{}, &mock_reporter));
EXPECT_THAT(mock_reporter.GetAsString(),
::testing::ContainsRegex("Invalid model version 1"));
}
TEST(VerifyModel, TestRandomModificationIsNotAllowed) {
FlatBufferBuilder builder;
auto model = CreateModel(builder, /*version=*/TFLITE_SCHEMA_VERSION,
/*operator_codes=*/0,
/*subgraphs=*/0, /*description=*/0, /*buffers=*/0);
::tflite::FinishModelBuffer(builder, model);
std::string model_content(reinterpret_cast<char*>(builder.GetBufferPointer()),
builder.GetSize());
for (int i = 0; i < model_content.size(); i++) {
model_content[i] = (model_content[i] + 137) % 255;
EXPECT_FALSE(Verify(model_content.data(), model_content.size(),
MutableOpResolver{}, DefaultErrorReporter()))
<< "Fail at position: " << i;
}
}
TEST(VerifyModel, TestIntTensorShapeIsGreaterThanBuffer) {
TfLiteFlatbufferModelBuilder builder;
builder.AddTensor({2, 3}, TensorType_UINT8, {1, 2, 3, 4}, "input");
builder.FinishModel({}, {});
ASSERT_FALSE(builder.Verify());
EXPECT_THAT(
builder.GetErrorString(),
::testing::ContainsRegex(
"Tensor requires 6 bytes, but is allocated with 4 bytes buffer"));
}
TEST(VerifyModel, TestIntTensorShapeIsSmallerThanBuffer) {
TfLiteFlatbufferModelBuilder builder;
builder.AddTensor({2, 1}, TensorType_UINT8, {1, 2, 3, 4}, "input");
builder.FinishModel({}, {});
ASSERT_FALSE(builder.Verify());
EXPECT_THAT(
builder.GetErrorString(),
::testing::ContainsRegex(
"Tensor requires 2 bytes, but is allocated with 4 bytes buffer"));
}
TEST(VerifyModel, TestIntTensorShapeOverflow) {
TfLiteFlatbufferModelBuilder builder;
builder.AddTensor({1024, 2048, 4096}, TensorType_UINT8, {1, 2, 3, 4},
"input");
builder.FinishModel({}, {});
ASSERT_FALSE(builder.Verify());
EXPECT_THAT(builder.GetErrorString(),
::testing::ContainsRegex("Tensor dimension overflow"));
}
TEST(VerifyModel, TensorBufferIsNotValid) {
FlatBufferBuilder builder;
std::vector<int> shape = {2, 3};
auto tensors = builder.CreateVector(std::vector<Offset<Tensor>>{
CreateTensorDirect(builder, &shape, TensorType_INT32, /*buffer=*/2,
"input", /*quantization=*/0)});
auto subgraph = std::vector<Offset<SubGraph>>(
{CreateSubGraph(builder, tensors, /*inputs=*/0, /*outputs=*/0,
/*operators=*/0, builder.CreateString("Main"))});
auto buffers = builder.CreateVector(std::vector<Offset<Buffer>>{
CreateBuffer(builder, builder.CreateVector(
std::vector<uint8_t>{1, 2, 3, 4, 5, 6})),
});
auto model = CreateModel(builder, TFLITE_SCHEMA_VERSION, /*operator_codes=*/0,
builder.CreateVector(subgraph),
builder.CreateString("SmartReply"), buffers);
::tflite::FinishModelBuffer(builder, model);
MockErrorReporter mock_reporter;
ASSERT_FALSE(Verify(builder.GetBufferPointer(), builder.GetSize(),
MutableOpResolver{}, &mock_reporter));
EXPECT_THAT(
mock_reporter.GetAsString(),
::testing::ContainsRegex("Missing 'operators' section in subgraph."));
}
TEST(VerifyModel, StringTensorHasInvalidNumString) {
TfLiteFlatbufferModelBuilder builder;
builder.AddTensor(
{2}, TensorType_STRING,
{0x00, 0x00, 0x00, 0x20, 16, 0, 0, 0, 17, 0, 0, 0, 18, 0, 0, 0, 'A', 'B'},
"input");
builder.FinishModel({}, {});
ASSERT_FALSE(builder.Verify());
EXPECT_THAT(builder.GetErrorString(),
::testing::ContainsRegex(
"String tensor buffer requires at least -2147483640 bytes, "
"but is allocated with 18 bytes"));
}
TEST(VerifyModel, StringTensorOffsetTooSmall) {
TfLiteFlatbufferModelBuilder builder;
builder.AddTensor(
{2}, TensorType_STRING,
{2, 0, 0, 0, 12, 0, 0, 0, 17, 0, 0, 0, 18, 0, 0, 0, 'A', 'B'}, "input");
builder.FinishModel({}, {});
ASSERT_FALSE(builder.Verify());
EXPECT_THAT(builder.GetErrorString(),
::testing::ContainsRegex(
"String tensor buffer initial offset must be: 16"));
}
TEST(VerifyModel, StringTensorOffsetOutOfRange) {
TfLiteFlatbufferModelBuilder builder;
builder.AddTensor(
{2}, TensorType_STRING,
{2, 0, 0, 0, 16, 0, 0, 0, 17, 0, 0, 0, 22, 0, 0, 0, 'A', 'B'}, "input");
builder.FinishModel({}, {});
ASSERT_FALSE(builder.Verify());
EXPECT_THAT(
builder.GetErrorString(),
::testing::ContainsRegex("String tensor buffer is invalid: index 2"));
}
TEST(VerifyModel, StringTensorIsLargerThanRequired) {
TfLiteFlatbufferModelBuilder builder;
builder.AddTensor(
{2}, TensorType_STRING,
{2, 0, 0, 0, 16, 0, 0, 0, 17, 0, 0, 0, 18, 0, 0, 0, 'A', 'B', 'C'},
"input");
builder.FinishModel({}, {});
ASSERT_FALSE(builder.Verify());
EXPECT_THAT(
builder.GetErrorString(),
::testing::ContainsRegex("String tensor buffer last offset must be 19"));
}
TEST(VerifyModel, AllOpsAreSupported) {
TfLiteFlatbufferModelBuilder builder({BuiltinOperator_ADD}, {"CustomOp"});
builder.AddTensor({2, 2}, TensorType_UINT8, {1, 2, 3, 4}, "input1");
builder.AddTensor({2, 2}, TensorType_UINT8, {1, 2, 3, 4}, "input2");
builder.AddTensor({2, 2}, TensorType_UINT8, {}, "output");
builder.AddOperator({0, 1}, {2}, BuiltinOperator_ADD, nullptr);
builder.AddOperator({0, 1}, {2}, BuiltinOperator_CUSTOM, "CustomOp");
builder.FinishModel({}, {});
ASSERT_TRUE(builder.Verify());
EXPECT_EQ("", builder.GetErrorString());
}
TEST(VerifyModel, UseUnsupportedBuiltinOps) {
TfLiteFlatbufferModelBuilder builder({BuiltinOperator_SUB}, {"CustomOp"});
builder.AddTensor({2, 2}, TensorType_UINT8, {1, 2, 3, 4}, "input1");
builder.AddTensor({2, 2}, TensorType_UINT8, {1, 2, 3, 4}, "input2");
builder.AddTensor({2, 2}, TensorType_UINT8, {}, "output");
builder.AddOperator({0, 1}, {2}, BuiltinOperator_ADD, nullptr);
builder.FinishModel({}, {});
ASSERT_FALSE(builder.Verify());
EXPECT_THAT(
builder.GetErrorString(),
::testing::ContainsRegex("Unsupported builtin op: ADD, version: 1"));
}
TEST(VerifyModel, UseUnsupportedCustomOps) {
TfLiteFlatbufferModelBuilder builder({BuiltinOperator_ADD}, {"NewOp"});
builder.AddTensor({2, 2}, TensorType_UINT8, {1, 2, 3, 4}, "input1");
builder.AddTensor({2, 2}, TensorType_UINT8, {1, 2, 3, 4}, "input2");
builder.AddTensor({2, 2}, TensorType_UINT8, {}, "output");
builder.AddOperator({0, 1}, {2}, BuiltinOperator_CUSTOM, "Not supported");
builder.FinishModel({}, {});
ASSERT_FALSE(builder.Verify());
EXPECT_THAT(builder.GetErrorString(),
::testing::ContainsRegex(
"Unsupported custom op: Not supported, version: 1"));
}
// TODO(yichengfan): make up malicious files to test with.
} // namespace tflite
int main(int argc, char** argv) {
::tflite::LogToStderr();
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| Java |
package com.squarespace.template.expr;
import java.util.Arrays;
/**
* Token representing a variable name. Could hold a reference or
* a definition.
*/
public class VarToken extends Token {
public final Object[] name;
public VarToken(Object[] name) {
super(ExprTokenType.VARIABLE);
this.name = name;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof VarToken) {
return Arrays.equals(name, ((VarToken)obj).name);
}
return false;
}
@Override
public String toString() {
return "VarToken[" + Arrays.toString(name) + "]";
}
}
| Java |
/*******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2012 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* 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.pentaho.di.trans.steps.jsonoutput;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import org.apache.commons.vfs.FileObject;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.ResultFile;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.row.RowDataUtil;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStep;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaInterface;
/**
* Converts input rows to one or more XML files.
*
* @author Matt
* @since 14-jan-2006
*/
public class JsonOutput extends BaseStep implements StepInterface
{
private static Class<?> PKG = JsonOutput.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
private JsonOutputMeta meta;
private JsonOutputData data;
private interface CompatibilityFactory {
public void execute(Object[] row) throws KettleException;
}
@SuppressWarnings("unchecked")
private class CompatibilityMode implements CompatibilityFactory {
public void execute(Object[] row) throws KettleException {
for (int i=0;i<data.nrFields;i++) {
JsonOutputField outputField = meta.getOutputFields()[i];
ValueMetaInterface v = data.inputRowMeta.getValueMeta(data.fieldIndexes[i]);
// Create a new object with specified fields
JSONObject jo = new JSONObject();
switch (v.getType()) {
case ValueMeta.TYPE_BOOLEAN:
jo.put(outputField.getElementName(), data.inputRowMeta.getBoolean(row, data.fieldIndexes[i]));
break;
case ValueMeta.TYPE_INTEGER:
jo.put(outputField.getElementName(), data.inputRowMeta.getInteger(row, data.fieldIndexes[i]));
break;
case ValueMeta.TYPE_NUMBER:
jo.put(outputField.getElementName(), data.inputRowMeta.getNumber(row, data.fieldIndexes[i]));
break;
case ValueMeta.TYPE_BIGNUMBER:
jo.put(outputField.getElementName(), data.inputRowMeta.getBigNumber(row, data.fieldIndexes[i]));
break;
default:
jo.put(outputField.getElementName(), data.inputRowMeta.getString(row, data.fieldIndexes[i]));
break;
}
data.ja.add(jo);
}
data.nrRow++;
if(data.nrRowsInBloc>0) {
// System.out.println("data.nrRow%data.nrRowsInBloc = "+ data.nrRow%data.nrRowsInBloc);
if(data.nrRow%data.nrRowsInBloc==0) {
// We can now output an object
// System.out.println("outputting the row.");
outPutRow(row);
}
}
}
}
@SuppressWarnings("unchecked")
private class FixedMode implements CompatibilityFactory {
public void execute(Object[] row) throws KettleException {
// Create a new object with specified fields
JSONObject jo = new JSONObject();
for (int i=0;i<data.nrFields;i++) {
JsonOutputField outputField = meta.getOutputFields()[i];
ValueMetaInterface v = data.inputRowMeta.getValueMeta(data.fieldIndexes[i]);
switch (v.getType()) {
case ValueMeta.TYPE_BOOLEAN:
jo.put(outputField.getElementName(), data.inputRowMeta.getBoolean(row, data.fieldIndexes[i]));
break;
case ValueMeta.TYPE_INTEGER:
jo.put(outputField.getElementName(), data.inputRowMeta.getInteger(row, data.fieldIndexes[i]));
break;
case ValueMeta.TYPE_NUMBER:
jo.put(outputField.getElementName(), data.inputRowMeta.getNumber(row, data.fieldIndexes[i]));
break;
case ValueMeta.TYPE_BIGNUMBER:
jo.put(outputField.getElementName(), data.inputRowMeta.getBigNumber(row, data.fieldIndexes[i]));
break;
default:
jo.put(outputField.getElementName(), data.inputRowMeta.getString(row, data.fieldIndexes[i]));
break;
}
}
data.ja.add(jo);
data.nrRow++;
if(data.nrRowsInBloc > 0) {
// System.out.println("data.nrRow%data.nrRowsInBloc = "+ data.nrRow%data.nrRowsInBloc);
if(data.nrRow%data.nrRowsInBloc==0) {
// We can now output an object
// System.out.println("outputting the row.");
outPutRow(row);
}
}
}
}
private CompatibilityFactory compatibilityFactory;
public JsonOutput(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans)
{
super(stepMeta, stepDataInterface, copyNr, transMeta, trans);
// Here we decide whether or not to build the structure in
// compatible mode or fixed mode
JsonOutputMeta jsonOutputMeta = (JsonOutputMeta)(stepMeta.getStepMetaInterface());
if (jsonOutputMeta.isCompatibilityMode()) {
compatibilityFactory = new CompatibilityMode();
}
else {
compatibilityFactory = new FixedMode();
}
}
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {
meta=(JsonOutputMeta)smi;
data=(JsonOutputData)sdi;
Object[] r = getRow(); // This also waits for a row to be finished.
if (r==null) {
// no more input to be expected...
if(!data.rowsAreSafe) {
// Let's output the remaining unsafe data
outPutRow(r);
}
setOutputDone();
return false;
}
if (first) {
first=false;
data.inputRowMeta=getInputRowMeta();
data.inputRowMetaSize=data.inputRowMeta.size();
if(data.outputValue) {
data.outputRowMeta = data.inputRowMeta.clone();
meta.getFields(data.outputRowMeta, getStepname(), null, null, this);
}
// Cache the field name indexes
//
data.nrFields=meta.getOutputFields().length;
data.fieldIndexes = new int[data.nrFields];
for (int i=0;i<data.nrFields;i++) {
data.fieldIndexes[i] = data.inputRowMeta.indexOfValue(meta.getOutputFields()[i].getFieldName());
if (data.fieldIndexes[i]<0) {
throw new KettleException(BaseMessages.getString(PKG, "JsonOutput.Exception.FieldNotFound")); //$NON-NLS-1$
}
JsonOutputField field = meta.getOutputFields()[i];
field.setElementName(environmentSubstitute(field.getElementName()));
}
}
data.rowsAreSafe=false;
compatibilityFactory.execute(r);
if(data.writeToFile && !data.outputValue) {
putRow(data.inputRowMeta,r ); // in case we want it go further...
incrementLinesOutput();
}
return true;
}
@SuppressWarnings("unchecked")
private void outPutRow(Object[] rowData) throws KettleStepException {
// We can now output an object
data.jg = new JSONObject();
data.jg.put(data.realBlocName, data.ja);
String value = data.jg.toJSONString();
if(data.outputValue) {
Object[] outputRowData = RowDataUtil.addValueData(rowData, data.inputRowMetaSize, value);
incrementLinesOutput();
putRow(data.outputRowMeta, outputRowData);
}
if(data.writeToFile) {
// Open a file
if (!openNewFile()) {
throw new KettleStepException(BaseMessages.getString(PKG, "JsonOutput.Error.OpenNewFile", buildFilename()));
}
// Write data to file
try {
data.writer.write(value);
}catch(Exception e) {
throw new KettleStepException(BaseMessages.getString(PKG, "JsonOutput.Error.Writing"), e);
}
// Close file
closeFile();
}
// Data are safe
data.rowsAreSafe=true;
data.ja = new JSONArray();
}
public boolean init(StepMetaInterface smi, StepDataInterface sdi)
{
meta=(JsonOutputMeta)smi;
data=(JsonOutputData)sdi;
if(super.init(smi, sdi)) {
data.writeToFile = (meta.getOperationType() != JsonOutputMeta.OPERATION_TYPE_OUTPUT_VALUE);
data.outputValue = (meta.getOperationType() != JsonOutputMeta.OPERATION_TYPE_WRITE_TO_FILE);
if(data.outputValue) {
// We need to have output field name
if(Const.isEmpty(environmentSubstitute(meta.getOutputValue()))) {
logError(BaseMessages.getString(PKG, "JsonOutput.Error.MissingOutputFieldName"));
stopAll();
setErrors(1);
return false;
}
}
if(data.writeToFile) {
// We need to have output field name
if(!meta.isServletOutput() && Const.isEmpty(meta.getFileName())) {
logError(BaseMessages.getString(PKG, "JsonOutput.Error.MissingTargetFilename"));
stopAll();
setErrors(1);
return false;
}
if(!meta.isDoNotOpenNewFileInit()) {
if (!openNewFile()) {
logError(BaseMessages.getString(PKG, "JsonOutput.Error.OpenNewFile", buildFilename()));
stopAll();
setErrors(1);
return false;
}
}
}
data.realBlocName = Const.NVL(environmentSubstitute(meta.getJsonBloc()), "");
data.nrRowsInBloc = Const.toInt(environmentSubstitute(meta.getNrRowsInBloc()), 0);
return true;
}
return false;
}
public void dispose(StepMetaInterface smi, StepDataInterface sdi) {
meta=(JsonOutputMeta)smi;
data=(JsonOutputData)sdi;
if(data.ja!=null) data.ja=null;
if(data.jg!=null) data.jg=null;
closeFile();
super.dispose(smi, sdi);
}
private void createParentFolder(String filename) throws KettleStepException {
if(!meta.isCreateParentFolder()) return;
// Check for parent folder
FileObject parentfolder=null;
try {
// Get parent folder
parentfolder=KettleVFS.getFileObject(filename, getTransMeta()).getParent();
if(!parentfolder.exists()) {
if(log.isDebug()) logDebug(BaseMessages.getString(PKG, "JsonOutput.Error.ParentFolderNotExist", parentfolder.getName()));
parentfolder.createFolder();
if(log.isDebug()) logDebug(BaseMessages.getString(PKG, "JsonOutput.Log.ParentFolderCreated"));
}
}catch (Exception e) {
throw new KettleStepException(BaseMessages.getString(PKG, "JsonOutput.Error.ErrorCreatingParentFolder", parentfolder.getName()));
} finally {
if ( parentfolder != null ){
try {
parentfolder.close();
}catch ( Exception ex ) {};
}
}
}
public boolean openNewFile()
{
if(data.writer!=null) return true;
boolean retval=false;
try {
if (meta.isServletOutput()) {
data.writer = getTrans().getServletPrintWriter();
} else {
String filename = buildFilename();
createParentFolder(filename);
if (meta.AddToResult()) {
// Add this to the result file names...
ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, KettleVFS.getFileObject(filename, getTransMeta()), getTransMeta().getName(), getStepname());
resultFile.setComment(BaseMessages.getString(PKG, "JsonOutput.ResultFilenames.Comment"));
addResultFile(resultFile);
}
OutputStream outputStream;
OutputStream fos = KettleVFS.getOutputStream(filename, getTransMeta(), meta.isFileAppended());
outputStream=fos;
if (!Const.isEmpty(meta.getEncoding())) {
data.writer = new OutputStreamWriter(new BufferedOutputStream(outputStream, 5000), environmentSubstitute(meta.getEncoding()));
} else {
data.writer = new OutputStreamWriter(new BufferedOutputStream(outputStream, 5000));
}
if(log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "JsonOutput.FileOpened", filename));
data.splitnr++;
}
retval=true;
} catch(Exception e) {
logError(BaseMessages.getString(PKG, "JsonOutput.Error.OpeningFile", e.toString()));
}
return retval;
}
public String buildFilename() {
return meta.buildFilename(environmentSubstitute(meta.getFileName()), getCopy(), data.splitnr);
}
private boolean closeFile()
{
if(data.writer==null) return true;
boolean retval=false;
try
{
data.writer.close();
data.writer=null;
retval=true;
}
catch(Exception e)
{
logError(BaseMessages.getString(PKG, "JsonOutput.Error.ClosingFile", e.toString()));
setErrors(1);
retval = false;
}
return retval;
}
} | Java |
package filodb.query.exec.rangefn
import scala.util.Random
import monix.execution.Scheduler.Implicits.global
import monix.reactive.Observable
import org.scalatest.concurrent.ScalaFutures
import filodb.core.{MetricsTestData, MachineMetricsData => MMD}
import filodb.core.query._
import filodb.memory.format.{ZeroCopyUTF8String, vectors => bv}
import filodb.query._
import filodb.query.exec.StaticFuncArgs
class InstantFunctionSpec extends RawDataWindowingSpec with ScalaFutures {
val resultSchema = ResultSchema(MetricsTestData.timeseriesSchema.infosFromIDs(0 to 1), 1)
val histSchema = ResultSchema(MMD.histDataset.schema.infosFromIDs(Seq(0, 3)), 1)
val histMaxSchema = ResultSchema(MMD.histMaxDS.schema.infosFromIDs(Seq(0, 4, 3)), 1, colIDs=Seq(0, 4, 3))
val ignoreKey = CustomRangeVectorKey(
Map(ZeroCopyUTF8String("ignore") -> ZeroCopyUTF8String("ignore")))
val sampleBase: Array[RangeVector] = Array(
new RangeVector {
override def key: RangeVectorKey = ignoreKey
import filodb.core.query.NoCloseCursor._
override def rows(): RangeVectorCursor = Seq(
new TransientRow(1L, 3.3d),
new TransientRow(2L, 5.1d)).iterator
override def outputRange: Option[RvRange] = None
},
new RangeVector {
override def key: RangeVectorKey = ignoreKey
import filodb.core.query.NoCloseCursor._
override def rows(): RangeVectorCursor = Seq(
new TransientRow(3L, 3239.3423d),
new TransientRow(4L, 94935.1523d)).iterator
override def outputRange: Option[RvRange] = None
})
val rand = new Random()
val error = 0.00000001d
val rangeParams = RangeParams(100, 20, 200)
it("should work with instant function mapper") {
val ignoreKey = CustomRangeVectorKey(
Map(ZeroCopyUTF8String("ignore") -> ZeroCopyUTF8String("ignore")))
val samples: Array[RangeVector] = Array.fill(100)(new RangeVector {
val data: Stream[TransientRow] = Stream.from(0).map { n =>
new TransientRow(n.toLong, rand.nextDouble())
}.take(20)
override def key: RangeVectorKey = ignoreKey
import filodb.core.query.NoCloseCursor._
override def rows(): RangeVectorCursor = data.iterator
override def outputRange: Option[RvRange] = None
})
fireInstantFunctionTests(samples)
}
it ("should handle NaN") {
val ignoreKey = CustomRangeVectorKey(
Map(ZeroCopyUTF8String("ignore") -> ZeroCopyUTF8String("ignore")))
val samples: Array[RangeVector] = Array(
new RangeVector {
import filodb.core.query.NoCloseCursor._
override def key: RangeVectorKey = ignoreKey
override def rows(): RangeVectorCursor = Seq(
new TransientRow(1L, Double.NaN),
new TransientRow(2L, 5.6d)).iterator
override def outputRange: Option[RvRange] = None
},
new RangeVector {
override def key: RangeVectorKey = ignoreKey
import filodb.core.query.NoCloseCursor._
override def rows(): RangeVectorCursor = Seq(
new TransientRow(1L, 4.6d),
new TransientRow(2L, 4.4d)).iterator
override def outputRange: Option[RvRange] = None
},
new RangeVector {
override def key: RangeVectorKey = ignoreKey
import filodb.core.query.NoCloseCursor._
override def rows(): RangeVectorCursor = Seq(
new TransientRow(1L, 0d),
new TransientRow(2L, 5.4d)).iterator
override def outputRange: Option[RvRange] = None
}
)
fireInstantFunctionTests(samples)
}
it ("should handle special cases") {
val ignoreKey = CustomRangeVectorKey(
Map(ZeroCopyUTF8String("ignore") -> ZeroCopyUTF8String("ignore")))
val samples: Array[RangeVector] = Array(
new RangeVector {
override def key: RangeVectorKey = ignoreKey
import filodb.core.query.NoCloseCursor._
override def rows(): RangeVectorCursor = Seq(
new TransientRow(1L, 2.0d/0d),
new TransientRow(2L, 4.5d),
new TransientRow(2L, 0d),
new TransientRow(2L, -2.1d),
new TransientRow(2L, -0.1d),
new TransientRow(2L, 0.3d),
new TransientRow(2L, 5.9d),
new TransientRow(2L, Double.NaN),
new TransientRow(2L, 3.3d)).iterator
override def outputRange: Option[RvRange] = None
}
)
fireInstantFunctionTests(samples)
}
private def fireInstantFunctionTests(samples: Array[RangeVector]): Unit = {
// Abs
val expected = samples.map(_.rows.map(v => scala.math.abs(v.getDouble(1))))
applyFunctionAndAssertResult(samples, expected, InstantFunctionId.Abs)
// Ceil
val expected2 = samples.map(_.rows.map(v => scala.math.ceil(v.getDouble(1))))
applyFunctionAndAssertResult(samples, expected2, InstantFunctionId.Ceil)
// ClampMax
val expected3 = samples.map(_.rows.map(v => scala.math.min(v.getDouble(1), 4)))
applyFunctionAndAssertResult(samples, expected3, InstantFunctionId.ClampMax, Seq(4.toDouble))
// ClampMin
val expected4 = samples.map(_.rows.map(v => scala.math.max(v.getDouble(1), 4.toDouble)))
applyFunctionAndAssertResult(samples, expected4, InstantFunctionId.ClampMin, Seq(4))
// Floor
val expected5 = samples.map(_.rows.map(v => scala.math.floor(v.getDouble(1))))
applyFunctionAndAssertResult(samples, expected5, InstantFunctionId.Floor)
// Log
val expected6 = samples.map(_.rows.map(v => scala.math.log(v.getDouble(1))))
applyFunctionAndAssertResult(samples, expected6, InstantFunctionId.Ln)
// Log10
val expected7 = samples.map(_.rows.map(v => scala.math.log10(v.getDouble(1))))
applyFunctionAndAssertResult(samples, expected7, InstantFunctionId.Log10)
// Log2
val expected8 = samples.map(_.rows.map(v => scala.math.log10(v.getDouble(1)) / scala.math.log10(2.0)))
applyFunctionAndAssertResult(samples, expected8, InstantFunctionId.Log2)
// Sqrt
val expected10 = samples.map(_.rows.map(v => scala.math.sqrt(v.getDouble(1))))
applyFunctionAndAssertResult(samples, expected10, InstantFunctionId.Sqrt)
// Exp
val expected11 = samples.map(_.rows.map(v => scala.math.exp(v.getDouble(1))))
applyFunctionAndAssertResult(samples, expected11, InstantFunctionId.Exp)
// Sgn
val expected12 = samples.map(_.rows.map(v => scala.math.signum(v.getDouble(1))))
applyFunctionAndAssertResult(samples, expected12, InstantFunctionId.Sgn)
// Round
testRoundFunction(samples)
}
private def testRoundFunction(samples: Array[RangeVector]): Unit = {
// Round
val expected9 = samples.map(_.rows.map(v => {
val value = v.getDouble(1)
val toNearestInverse = 1.0
if (value.isNaN || value.isInfinite)
value
else
scala.math.floor(value * toNearestInverse + 0.5) / toNearestInverse
}))
applyFunctionAndAssertResult(samples, expected9, InstantFunctionId.Round)
// Round with param
val expected10 = samples.map(_.rows.map(v => {
val value = v.getDouble(1)
val toNearestInverse = 1.0 / 10
if (value.isNaN || value.isInfinite)
value
else
scala.math.floor(value * toNearestInverse + 0.5) / toNearestInverse
}))
applyFunctionAndAssertResult(samples, expected10, InstantFunctionId.Round, Seq(10))
}
it ("should validate invalid function params") {
// clamp_max
the[IllegalArgumentException] thrownBy {
val instantVectorFnMapper1 = exec.InstantVectorFunctionMapper(InstantFunctionId.ClampMax)
val resultObs = instantVectorFnMapper1(Observable.fromIterable(sampleBase), querySession, 1000, resultSchema, Nil)
val result = resultObs.toListL.runToFuture.futureValue.map(_.rows.map(_.getDouble(1)).toList)
} should have message "requirement failed: Cannot use ClampMax without providing a upper limit of max."
// clamp_min
the[IllegalArgumentException] thrownBy {
val instantVectorFnMapper3 = exec.InstantVectorFunctionMapper(InstantFunctionId.ClampMin)
val resultObs = instantVectorFnMapper3(Observable.fromIterable(sampleBase), querySession, 1000, resultSchema, Nil)
resultObs.toListL.runToFuture.futureValue.map(_.rows.map(_.getDouble(1)).toList)
} should have message "requirement failed: Cannot use ClampMin without providing a lower limit of min."
// sgn
the[IllegalArgumentException] thrownBy {
val instantVectorFnMapper5 = exec.InstantVectorFunctionMapper(InstantFunctionId.Sgn,
Seq(StaticFuncArgs(1, rangeParams)))
val resultObs = instantVectorFnMapper5(Observable.fromIterable(sampleBase), querySession, 1000, resultSchema, Nil)
resultObs.toListL.runToFuture.futureValue.map(_.rows.map(_.getDouble(1)).toList)
} should have message "requirement failed: No additional parameters required for the instant function."
// sqrt
the[IllegalArgumentException] thrownBy {
val instantVectorFnMapper5 = exec.InstantVectorFunctionMapper(InstantFunctionId.Sqrt,
Seq(StaticFuncArgs(1, rangeParams)))
val resultObs = instantVectorFnMapper5(Observable.fromIterable(sampleBase), querySession, 1000, resultSchema, Nil)
resultObs.toListL.runToFuture.futureValue.map(_.rows.map(_.getDouble(1)).toList)
} should have message "requirement failed: No additional parameters required for the instant function."
// round
the[IllegalArgumentException] thrownBy {
val instantVectorFnMapper5 = exec.InstantVectorFunctionMapper(InstantFunctionId.Round,
Seq(StaticFuncArgs(1, rangeParams), StaticFuncArgs(2, rangeParams)))
val resultObs = instantVectorFnMapper5(Observable.fromIterable(sampleBase), querySession, 1000, resultSchema, Nil)
resultObs.toListL.runToFuture.futureValue.map(_.rows.map(_.getDouble(1)).toList)
} should have message "requirement failed: Only one optional parameters allowed for Round."
// histogram quantile
the[IllegalArgumentException] thrownBy {
val (data, histRV) = histogramRV(numSamples = 10)
val ivMapper = exec.InstantVectorFunctionMapper(InstantFunctionId.HistogramQuantile)
val resultObs = ivMapper(Observable.fromIterable(Array(histRV)), querySession, 1000, histSchema, Nil)
resultObs.toListL.runToFuture.futureValue.map(_.rows.map(_.getDouble(1)).toList)
} should have message "requirement failed: Quantile (between 0 and 1) required for histogram quantile"
// histogram bucket
the[IllegalArgumentException] thrownBy {
val (data, histRV) = histogramRV(numSamples = 10)
val ivMapper = exec.InstantVectorFunctionMapper(InstantFunctionId.HistogramBucket)
val resultObs = ivMapper(Observable.fromIterable(Array(histRV)), querySession, 1000, histSchema, Nil)
resultObs.toListL.runToFuture.futureValue.map(_.rows.map(_.getDouble(1)).toList)
} should have message "requirement failed: Bucket/le required for histogram bucket"
}
it ("should fail with wrong calculation") {
// ceil
val expectedVal = sampleBase.map(_.rows.map(v => scala.math.floor(v.getDouble(1))))
val instantVectorFnMapper = exec.InstantVectorFunctionMapper(InstantFunctionId.Ceil)
val resultObs = instantVectorFnMapper(Observable.fromIterable(sampleBase), querySession, 1000, resultSchema, Nil)
val result = resultObs.toListL.runToFuture.futureValue.map(_.rows.map(_.getDouble(1)))
expectedVal.zip(result).foreach {
case (ex, res) => {
ex.zip(res).foreach {
case (val1, val2) =>
val1 should not equal val2
}
}
}
}
it("should compute histogram_quantile on Histogram RV") {
val (data, histRV) = histogramRV(numSamples = 10)
val expected = Seq(0.8, 1.6, 2.4, 3.2, 4.0, 5.6, 7.2, 9.6)
applyFunctionAndAssertResult(Array(histRV), Array(expected.toIterator),
InstantFunctionId.HistogramQuantile, Seq(0.4), histSchema)
// check output schema
val instantVectorFnMapper = exec.InstantVectorFunctionMapper(InstantFunctionId.HistogramQuantile,
Seq(StaticFuncArgs(0.99, rangeParams)))
val outSchema = instantVectorFnMapper.schema(histSchema)
outSchema.columns.map(_.colType) shouldEqual resultSchema.columns.map(_.colType)
}
it("should compute histogram_max_quantile on Histogram RV") {
val (data, histRV) = MMD.histMaxRV(100000L, numSamples = 7)
val expected = data.zipWithIndex.map { case (row, i) =>
// Calculating the quantile is quite complex... sigh
val _max = row(3).asInstanceOf[Double]
if ((i % 8) == 0) (_max * 0.9) else {
val _hist = row(4).asInstanceOf[bv.LongHistogram]
val rank = 0.9 * _hist.bucketValue(_hist.numBuckets - 1)
val ratio = (rank - _hist.bucketValue((i-1) % 8)) / (_hist.bucketValue(i%8) - _hist.bucketValue((i-1) % 8))
_hist.bucketTop((i-1) % 8) + ratio * (_max - _hist.bucketTop((i-1) % 8))
}
}
applyFunctionAndAssertResult(Array(histRV), Array(expected.toIterator),
InstantFunctionId.HistogramMaxQuantile, Seq(0.9), histMaxSchema)
}
it("should return proper schema after applying histogram_max_quantile") {
val instantVectorFnMapper = exec.InstantVectorFunctionMapper(InstantFunctionId.HistogramMaxQuantile,
Seq(StaticFuncArgs(0.99, rangeParams)))
val outSchema = instantVectorFnMapper.schema(histMaxSchema)
outSchema.columns.map(_.colType) shouldEqual resultSchema.columns.map(_.colType)
}
it("should compute histogram_bucket on Histogram RV") {
val (data, histRV) = histogramRV(numSamples = 10, infBucket = true)
val expected = Seq(1.0, 2.0, 3.0, 4.0, 4.0, 4.0, 4.0, 4.0)
applyFunctionAndAssertResult(Array(histRV), Array(expected.toIterator),
InstantFunctionId.HistogramBucket, Seq(16.0), histSchema)
val infExpected = (1 to 10).map(_.toDouble)
applyFunctionAndAssertResult(Array(histRV), Array(infExpected.toIterator),
InstantFunctionId.HistogramBucket, Seq(Double.PositiveInfinity), histSchema)
// Specifying a nonexistant bucket returns NaN
applyFunctionAndAssertResult(Array(histRV), Array(Seq.fill(8)(Double.NaN).toIterator),
InstantFunctionId.HistogramBucket, Seq(9.0), histSchema)
}
it("should test date time functions") {
val samples: Array[RangeVector] = Array(
new RangeVector {
override def key: RangeVectorKey = ignoreKey
import filodb.core.query.NoCloseCursor._
override def rows(): RangeVectorCursor = Seq(
new TransientRow(1L, 1456790399), // 2016-02-29 23:59:59 February 29th
new TransientRow(2L, 1456790400), // 2016-03-01 00:00:00 March 1st
new TransientRow(3L, 1230768000), // 2009-01-01 00:00:00 just after leap second
new TransientRow(4L, 1230767999), // 2008-12-31 23:59:59 just before leap second.
new TransientRow(5L, 1569179748) // 2019-09-22 19:15:48 Sunday
).iterator
override def outputRange: Option[RvRange] = None
}
)
applyFunctionAndAssertResult(samples, Array(List(2.0, 3.0, 1.0, 12.0, 9.0).toIterator), InstantFunctionId.Month)
applyFunctionAndAssertResult(samples, Array(List(2016.0, 2016.0, 2009.0, 2008.0, 2019.0).toIterator), InstantFunctionId.Year)
applyFunctionAndAssertResult(samples, Array(List(59.0, 0.0, 0.0, 59.0, 15.0).toIterator), InstantFunctionId.Minute)
applyFunctionAndAssertResult(samples, Array(List(23.0, 0.0, 0.0, 23.0, 19.0).toIterator), InstantFunctionId.Hour)
applyFunctionAndAssertResult(samples, Array(List(29.0, 31.0, 31.0, 31.0, 30.0).toIterator), InstantFunctionId.DaysInMonth)
applyFunctionAndAssertResult(samples, Array(List(29.0, 1.0, 1.0, 31.0, 22.0).toIterator), InstantFunctionId.DayOfMonth)
applyFunctionAndAssertResult(samples, Array(List(1.0, 2.0, 4.0, 3.0, 0.0).toIterator), InstantFunctionId.DayOfWeek)
}
it("should handle NaN for date time functions") {
val samples: Array[RangeVector] = Array(
new RangeVector {
override def key: RangeVectorKey = ignoreKey
import filodb.core.query.NoCloseCursor._
override def rows(): RangeVectorCursor = Seq(
new TransientRow(1L, Double.NaN),
new TransientRow(2L, Double.NaN)
).iterator
override def outputRange: Option[RvRange] = None
}
)
applyFunctionAndAssertResult(samples, Array(List(Double.NaN, Double.NaN).toIterator), InstantFunctionId.Month)
applyFunctionAndAssertResult(samples, Array(List(Double.NaN, Double.NaN).toIterator), InstantFunctionId.Year)
applyFunctionAndAssertResult(samples, Array(List(Double.NaN, Double.NaN).toIterator), InstantFunctionId.Minute)
applyFunctionAndAssertResult(samples, Array(List(Double.NaN, Double.NaN).toIterator), InstantFunctionId.Hour)
applyFunctionAndAssertResult(samples, Array(List(Double.NaN, Double.NaN).toIterator), InstantFunctionId.DaysInMonth)
applyFunctionAndAssertResult(samples, Array(List(Double.NaN, Double.NaN).toIterator), InstantFunctionId.DayOfMonth)
applyFunctionAndAssertResult(samples, Array(List(Double.NaN, Double.NaN).toIterator), InstantFunctionId.DayOfWeek)
}
private def applyFunctionAndAssertResult(samples: Array[RangeVector], expectedVal: Array[Iterator[Double]],
instantFunctionId: InstantFunctionId, funcParams: Seq[Double] = Nil,
schema: ResultSchema = resultSchema): Unit = {
val instantVectorFnMapper = exec.InstantVectorFunctionMapper(instantFunctionId,
funcParams.map(x => StaticFuncArgs(x, RangeParams(100, 10, 200))))
val resultObs = instantVectorFnMapper(Observable.fromIterable(samples), querySession, 1000, schema, Nil)
val result = resultObs.toListL.runToFuture.futureValue.map(_.rows)
expectedVal.zip(result).foreach {
case (ex, res) => {
ex.zip(res).foreach {
case (val1, val2) => {
val val2Num = val2.getDouble(1)
if (val1.isInfinity) val2Num.isInfinity shouldEqual true
else if (val1.isNaN) val2Num.isNaN shouldEqual true
else val1 shouldEqual val2Num +- 0.0001
}
}
// Ensure that locks are released from DoubleInstantFuncIterator. A couple of the tests
// don't feed in enough expected data for the iterator to reach the end naturally and
// close itself.
res.close();
}
}
}
}
| Java |
-- create-db-security.sql: Security Master
-- design has one document
-- security and associated identity key
-- bitemporal versioning exists at the document level
-- each time a document is changed, a new row is written
-- with only the end instant being changed on the old row
CREATE TABLE sec_schema_version (
version_key VARCHAR(32) NOT NULL,
version_value VARCHAR(255) NOT NULL
);
INSERT INTO sec_schema_version (version_key, version_value) VALUES ('schema_patch', '51');
CREATE SEQUENCE IF NOT EXISTS sec_security_seq AS bigint
START WITH 1000 INCREMENT BY 1 NO CYCLE;
CREATE SEQUENCE IF NOT EXISTS sec_idkey_seq AS bigint
START WITH 1000 INCREMENT BY 1 NO CYCLE;
-- "as bigint" required by Derby/HSQL, not accepted by Postgresql
CREATE TABLE sec_security (
id bigint NOT NULL,
oid bigint NOT NULL,
ver_from_instant timestamp without time zone NOT NULL,
ver_to_instant timestamp without time zone NOT NULL,
corr_from_instant timestamp without time zone NOT NULL,
corr_to_instant timestamp without time zone NOT NULL,
name varchar(255) NOT NULL,
sec_type varchar(255) NOT NULL,
detail_type char NOT NULL,
PRIMARY KEY (id),
CONSTRAINT sec_fk_sec2sec FOREIGN KEY (oid) REFERENCES sec_security (id),
CONSTRAINT sec_chk_sec_ver_order CHECK (ver_from_instant <= ver_to_instant),
CONSTRAINT sec_chk_sec_corr_order CHECK (corr_from_instant <= corr_to_instant),
CONSTRAINT sec_chk_detail_type CHECK (detail_type IN ('D', 'M', 'R'))
);
CREATE INDEX ix_sec_security_oid ON sec_security(oid);
CREATE INDEX ix_sec_security_ver_from_instant ON sec_security(ver_from_instant);
CREATE INDEX ix_sec_security_ver_to_instant ON sec_security(ver_to_instant);
CREATE INDEX ix_sec_security_corr_from_instant ON sec_security(corr_from_instant);
CREATE INDEX ix_sec_security_corr_to_instant ON sec_security(corr_to_instant);
CREATE INDEX ix_sec_security_name ON sec_security(name);
CREATE INDEX ix_sec_security_sec_type ON sec_security(sec_type);
CREATE TABLE sec_idkey (
id bigint NOT NULL,
key_scheme varchar(255) NOT NULL,
key_value varchar(255) NOT NULL,
PRIMARY KEY (id),
CONSTRAINT sec_chk_idkey UNIQUE (key_scheme, key_value)
);
CREATE TABLE sec_security2idkey (
security_id bigint NOT NULL,
idkey_id bigint NOT NULL,
PRIMARY KEY (security_id, idkey_id),
CONSTRAINT sec_fk_secidkey2sec FOREIGN KEY (security_id) REFERENCES sec_security (id),
CONSTRAINT sec_fk_secidkey2idkey FOREIGN KEY (idkey_id) REFERENCES sec_idkey (id)
);
CREATE INDEX ix_sec_sec2idkey_idkey ON sec_security2idkey(idkey_id);
-- sec_security_idkey is fully dependent of sec_security
-- Hibernate controlled tables
CREATE TABLE sec_currency (
id bigint NOT NULL,
name varchar(255) NOT NULL UNIQUE,
PRIMARY KEY (id)
);
CREATE TABLE sec_cashrate (
id bigint NOT NULL,
name varchar(255) NOT NULL UNIQUE,
PRIMARY KEY (id)
);
CREATE TABLE sec_unit (
id bigint NOT NULL,
name varchar(255) NOT NULL UNIQUE,
PRIMARY KEY (id)
);
CREATE TABLE sec_exchange (
id bigint NOT NULL,
name varchar(255) NOT NULL UNIQUE,
description varchar(255),
PRIMARY KEY (id)
);
CREATE TABLE sec_gics (
id bigint NOT NULL,
name varchar(8) NOT NULL UNIQUE,
description varchar(255),
PRIMARY KEY (id)
);
CREATE TABLE sec_equity (
id bigint NOT NULL,
security_id bigint NOT NULL,
shortName varchar(255),
exchange_id bigint NOT NULL,
companyName varchar(255) NOT NULL,
currency_id bigint NOT NULL,
gicscode_id bigint,
PRIMARY KEY (id),
CONSTRAINT sec_fk_equity2sec FOREIGN KEY (security_id) REFERENCES sec_security (id),
CONSTRAINT sec_fk_equity2currency FOREIGN KEY (currency_id) REFERENCES sec_currency(id),
CONSTRAINT sec_fk_equity2exchange FOREIGN KEY (exchange_id) REFERENCES sec_exchange(id),
CONSTRAINT sec_fk_equity2gics FOREIGN KEY (gicscode_id) REFERENCES sec_gics(id)
);
CREATE INDEX ix_sec_equity_security_id ON sec_equity(security_id);
CREATE TABLE sec_equityindexoption (
id bigint NOT NULL,
security_id bigint NOT NULL,
option_exercise_type varchar(32) NOT NULL,
option_type varchar(32) NOT NULL,
strike double precision NOT NULL,
expiry_date timestamp without time zone NOT NULL,
expiry_zone varchar(50) NOT NULL,
expiry_accuracy smallint NOT NULL,
underlying_scheme varchar(255) NOT NULL,
underlying_identifier varchar(255) NOT NULL,
currency_id bigint NOT NULL,
exchange_id bigint,
pointValue double precision,
PRIMARY KEY (id),
CONSTRAINT sec_fk_equityindexoption2sec FOREIGN KEY (security_id) REFERENCES sec_security (id),
CONSTRAINT sec_fk_equityindexoption2currency FOREIGN KEY (currency_id) REFERENCES sec_currency (id),
CONSTRAINT sec_fk_equityindexoption2exchange FOREIGN KEY (exchange_id) REFERENCES sec_exchange (id)
);
CREATE TABLE sec_equityoption (
id bigint NOT NULL,
security_id bigint NOT NULL,
option_exercise_type varchar(32) NOT NULL,
option_type varchar(32) NOT NULL,
strike double precision NOT NULL,
expiry_date timestamp without time zone NOT NULL,
expiry_zone varchar(50) NOT NULL,
expiry_accuracy smallint NOT NULL,
underlying_scheme varchar(255) NOT NULL,
underlying_identifier varchar(255) NOT NULL,
currency_id bigint NOT NULL,
exchange_id bigint,
pointValue double precision,
PRIMARY KEY (id),
CONSTRAINT sec_fk_equityoption2sec FOREIGN KEY (security_id) REFERENCES sec_security (id),
CONSTRAINT sec_fk_equityoption2currency FOREIGN KEY (currency_id) REFERENCES sec_currency (id),
CONSTRAINT sec_fk_equityoption2exchange FOREIGN KEY (exchange_id) REFERENCES sec_exchange (id)
);
CREATE INDEX ix_sec_equityoption_security_id ON sec_equityoption(security_id);
CREATE TABLE sec_equitybarrieroption (
id bigint NOT NULL,
security_id bigint NOT NULL,
option_exercise_type varchar(32) NOT NULL,
option_type varchar(32) NOT NULL,
strike double precision NOT NULL,
expiry_date timestamp without time zone NOT NULL,
expiry_zone varchar(50) NOT NULL,
expiry_accuracy smallint NOT NULL,
underlying_scheme varchar(255) NOT NULL,
underlying_identifier varchar(255) NOT NULL,
currency_id bigint NOT NULL,
exchange_id bigint,
pointValue double precision,
barrier_type varchar(32) NOT NULL,
barrier_direction varchar(32) NOT NULL,
barrier_level double precision NOT NULL,
monitoring_type varchar(32) NOT NULL,
sampling_frequency varchar(32),
PRIMARY KEY (id),
CONSTRAINT sec_fk_equitybarrieroption2sec FOREIGN KEY (security_id) REFERENCES sec_security (id),
CONSTRAINT sec_fk_equitybarrieroption2currency FOREIGN KEY (currency_id) REFERENCES sec_currency (id),
CONSTRAINT sec_fk_equitybarrieroption2exchange FOREIGN KEY (exchange_id) REFERENCES sec_exchange (id)
);
CREATE INDEX ix_sec_equitybarrieroption_security_id ON sec_equitybarrieroption(security_id);
CREATE TABLE sec_fxoption (
id bigint NOT NULL,
security_id bigint NOT NULL,
option_exercise_type varchar(32) NOT NULL,
put_amount double precision NOT NULL,
call_amount double precision NOT NULL,
expiry_date timestamp without time zone NOT NULL,
expiry_zone varchar(50) NOT NULL,
expiry_accuracy smallint NOT NULL,
put_currency_id bigint NOT NULL,
call_currency_id bigint NOT NULL,
settlement_date timestamp without time zone NOT NULL,
settlement_zone varchar(50) NOT NULL,
is_long boolean NOT NULL,
PRIMARY KEY (id),
CONSTRAINT sec_fk_fxoption2sec FOREIGN KEY (security_id) REFERENCES sec_security (id),
CONSTRAINT sec_fk_fxoption2putcurrency FOREIGN KEY (put_currency_id) REFERENCES sec_currency (id),
CONSTRAINT sec_fk_fxoption2callcurrency FOREIGN KEY (call_currency_id) REFERENCES sec_currency (id)
);
CREATE INDEX ix_sec_fxoption_security_id ON sec_fxoption(security_id);
CREATE TABLE sec_nondeliverablefxoption (
id bigint NOT NULL,
security_id bigint NOT NULL,
option_exercise_type varchar(32) NOT NULL,
put_amount double precision NOT NULL,
call_amount double precision NOT NULL,
expiry_date timestamp without time zone NOT NULL,
expiry_zone varchar(50) NOT NULL,
expiry_accuracy smallint NOT NULL,
put_currency_id bigint NOT NULL,
call_currency_id bigint NOT NULL,
settlement_date timestamp without time zone NOT NULL,
settlement_zone varchar(50) NOT NULL,
is_long boolean NOT NULL,
is_delivery_in_call_currency boolean NOT NULL,
PRIMARY KEY (id),
CONSTRAINT sec_fk_nondeliverablefxoption2sec FOREIGN KEY (security_id) REFERENCES sec_security (id),
CONSTRAINT sec_fk_nondeliverablefxoption2putcurrency FOREIGN KEY (put_currency_id) REFERENCES sec_currency (id),
CONSTRAINT sec_fk_nondeliverablefxoption2callcurrency FOREIGN KEY (call_currency_id) REFERENCES sec_currency (id)
);
CREATE INDEX ix_sec_nondeliverablefxoption_security_id ON sec_nondeliverablefxoption(security_id);
CREATE TABLE sec_fxdigitaloption (
id bigint NOT NULL,
security_id bigint NOT NULL,
put_amount double precision NOT NULL,
call_amount double precision NOT NULL,
expiry_date timestamp without time zone NOT NULL,
expiry_zone varchar(50) NOT NULL,
expiry_accuracy smallint NOT NULL,
put_currency_id bigint NOT NULL,
call_currency_id bigint NOT NULL,
payment_currency_id bigint NOT NULL,
settlement_date timestamp without time zone NOT NULL,
settlement_zone varchar(50) NOT NULL,
is_long boolean NOT NULL,
PRIMARY KEY (id),
CONSTRAINT sec_fk_fxdigitaloption2sec FOREIGN KEY (security_id) REFERENCES sec_security (id),
CONSTRAINT sec_fk_fxdigitaloption2putcurrency FOREIGN KEY (put_currency_id) REFERENCES sec_currency (id),
CONSTRAINT sec_fk_fxdigitaloption2callcurrency FOREIGN KEY (call_currency_id) REFERENCES sec_currency (id),
CONSTRAINT sec_fk_fxdigitaloption2paymentcurrency FOREIGN KEY (payment_currency_id) REFERENCES sec_currency (id)
);
CREATE INDEX ix_sec_fxdigitaloption_security_id ON sec_fxdigitaloption(security_id);
CREATE TABLE sec_ndffxdigitaloption (
id bigint NOT NULL,
security_id bigint NOT NULL,
put_amount double precision NOT NULL,
call_amount double precision NOT NULL,
expiry_date timestamp without time zone NOT NULL,
expiry_zone varchar(50) NOT NULL,
expiry_accuracy smallint NOT NULL,
put_currency_id bigint NOT NULL,
call_currency_id bigint NOT NULL,
payment_currency_id bigint NOT NULL,
settlement_date timestamp without time zone NOT NULL,
settlement_zone varchar(50) NOT NULL,
is_long boolean NOT NULL,
is_delivery_in_call_currency boolean NOT NULL,
PRIMARY KEY (id),
CONSTRAINT sec_fk_ndffxdigitaloption2sec FOREIGN KEY (security_id) REFERENCES sec_security (id),
CONSTRAINT sec_fk_ndffxdigitaloption2putcurrency FOREIGN KEY (put_currency_id) REFERENCES sec_currency (id),
CONSTRAINT sec_fk_ndffxdigitaloption2callcurrency FOREIGN KEY (call_currency_id) REFERENCES sec_currency (id),
CONSTRAINT sec_fk_ndffxdigitaloption2paymentcurrency FOREIGN KEY (payment_currency_id) REFERENCES sec_currency (id)
);
CREATE INDEX ix_sec_ndffxdigitaloption_security_id ON sec_ndffxdigitaloption(security_id);
CREATE TABLE sec_swaption (
id bigint NOT NULL,
security_id bigint NOT NULL,
underlying_scheme varchar(255) NOT NULL,
underlying_identifier varchar(255) NOT NULL,
expiry_date timestamp without time zone NOT NULL,
expiry_zone varchar(50) NOT NULL,
expiry_accuracy smallint NOT NULL,
cash_settled boolean NOT NULL,
is_long boolean NOT NULL,
is_payer boolean NOT NULL,
currency_id bigint NOT NULL,
option_exercise_type VARCHAR(32),
settlement_date TIMESTAMP,
settlement_zone VARCHAR(50),
notional double precision,
PRIMARY KEY (id),
CONSTRAINT sec_fk_swaption2currency FOREIGN KEY (currency_id) REFERENCES sec_currency(id),
CONSTRAINT sec_fk_swaption2sec FOREIGN KEY (security_id) REFERENCES sec_security (id)
);
CREATE TABLE sec_irfutureoption (
id bigint NOT NULL,
security_id bigint NOT NULL,
option_exercise_type varchar(32) NOT NULL,
option_type varchar(32) NOT NULL,
strike double precision NOT NULL,
expiry_date timestamp without time zone NOT NULL,
expiry_zone varchar(50) NOT NULL,
expiry_accuracy smallint NOT NULL,
underlying_scheme varchar(255) NOT NULL,
underlying_identifier varchar(255) NOT NULL,
currency_id bigint NOT NULL,
exchange_id bigint NOT NULL,
margined boolean NOT NULL,
pointValue double precision NOT NULL,
PRIMARY KEY (id),
CONSTRAINT sec_fk_irfutureoption2sec FOREIGN KEY (security_id) REFERENCES sec_security (id),
CONSTRAINT sec_fk_irfutureoption2currency FOREIGN KEY (currency_id) REFERENCES sec_currency (id),
CONSTRAINT sec_fk_irfutureoption2exchange FOREIGN KEY (exchange_id) REFERENCES sec_exchange (id)
);
CREATE TABLE sec_commodityfutureoption (
id bigint NOT NULL,
security_id bigint NOT NULL,
option_exercise_type varchar(32) NOT NULL,
option_type varchar(32) NOT NULL,
strike double precision NOT NULL,
expiry_date timestamp without time zone NOT NULL,
expiry_zone varchar(50) NOT NULL,
expiry_accuracy smallint NOT NULL,
underlying_scheme varchar(255) NOT NULL,
underlying_identifier varchar(255) NOT NULL,
currency_id bigint NOT NULL,
trading_exchange_id bigint NOT NULL,
settlement_exchange_id bigint NOT NULL,
pointValue double precision NOT NULL,
PRIMARY KEY (id),
CONSTRAINT sec_fk_commodityfutureoption2sec FOREIGN KEY (security_id) REFERENCES sec_security (id),
CONSTRAINT sec_fk_commodityfutureoption2currency FOREIGN KEY (currency_id) REFERENCES sec_currency (id),
CONSTRAINT sec_fk_commodityfutureoption2trading_exchange FOREIGN KEY (trading_exchange_id) REFERENCES sec_exchange (id),
CONSTRAINT sec_fk_commodityfutureoption2settlement_exchange FOREIGN KEY (settlement_exchange_id) REFERENCES sec_exchange (id)
);
CREATE TABLE sec_equity_index_dividend_futureoption (
id bigint NOT NULL,
security_id bigint NOT NULL,
option_exercise_type varchar(32) NOT NULL,
option_type varchar(32) NOT NULL,
strike double precision NOT NULL,
expiry_date timestamp without time zone NOT NULL,
expiry_zone varchar(50) NOT NULL,
expiry_accuracy smallint NOT NULL,
underlying_scheme varchar(255) NOT NULL,
underlying_identifier varchar(255) NOT NULL,
currency_id bigint NOT NULL,
exchange_id bigint NOT NULL,
margined boolean NOT NULL,
pointValue double precision NOT NULL,
PRIMARY KEY (id),
CONSTRAINT sec_equity_index_dividend_futureoption2sec FOREIGN KEY (security_id) REFERENCES sec_security (id),
CONSTRAINT sec_equity_index_dividend_futureoption2currency FOREIGN KEY (currency_id) REFERENCES sec_currency (id),
CONSTRAINT sec_equity_index_dividend_futureoption2exchange FOREIGN KEY (exchange_id) REFERENCES sec_exchange (id)
);
CREATE INDEX ix_sec_equity_index_dividend_futureoption_security_id ON sec_equity_index_dividend_futureoption(security_id);
CREATE TABLE sec_fxbarrieroption (
id bigint NOT NULL,
security_id bigint NOT NULL,
put_amount double precision NOT NULL,
call_amount double precision NOT NULL,
expiry_date timestamp without time zone NOT NULL,
expiry_zone varchar(50) NOT NULL,
expiry_accuracy smallint NOT NULL,
put_currency_id bigint NOT NULL,
call_currency_id bigint NOT NULL,
settlement_date timestamp without time zone NOT NULL,
settlement_zone varchar(50) NOT NULL,
barrier_type varchar(32) NOT NULL,
barrier_direction varchar(32) NOT NULL,
barrier_level double precision NOT NULL,
monitoring_type varchar(32) NOT NULL,
sampling_frequency varchar(32),
is_long boolean NOT NULL,
PRIMARY KEY (id),
CONSTRAINT sec_fk_fxbarrieroption2sec FOREIGN KEY (security_id) REFERENCES sec_security (id),
CONSTRAINT sec_fk_fxbarrieroption2putcurrency FOREIGN KEY (put_currency_id) REFERENCES sec_currency (id),
CONSTRAINT sec_fk_fxbarrieroption2callcurrency FOREIGN KEY (call_currency_id) REFERENCES sec_currency (id)
);
CREATE TABLE sec_frequency (
id bigint NOT NULL,
name varchar(255) NOT NULL UNIQUE,
PRIMARY KEY (id)
);
CREATE TABLE sec_daycount (
id bigint NOT NULL,
name varchar(255) NOT NULL UNIQUE,
PRIMARY KEY (id)
);
CREATE TABLE sec_businessdayconvention (
id bigint NOT NULL,
name varchar(255) NOT NULL UNIQUE,
PRIMARY KEY (id)
);
CREATE TABLE sec_issuertype (
id bigint NOT NULL,
name varchar(255) NOT NULL UNIQUE,
PRIMARY KEY (id)
);
CREATE TABLE sec_market (
id bigint NOT NULL,
name varchar(255) NOT NULL UNIQUE,
PRIMARY KEY (id)
);
CREATE TABLE sec_yieldconvention (
id bigint NOT NULL,
name varchar(255) NOT NULL UNIQUE,
PRIMARY KEY (id)
);
CREATE TABLE sec_guaranteetype (
id bigint NOT NULL,
name varchar(255) NOT NULL UNIQUE,
PRIMARY KEY (id)
);
CREATE TABLE sec_coupontype (
id bigint NOT NULL,
name varchar(255) NOT NULL UNIQUE,
PRIMARY KEY (id)
);
CREATE TABLE sec_bond (
id bigint NOT NULL,
security_id bigint NOT NULL,
bond_type varchar(32) NOT NULL,
issuername varchar(255) NOT NULL,
issuertype_id bigint NOT NULL,
issuerdomicile varchar(255) NOT NULL,
market_id bigint NOT NULL,
currency_id bigint NOT NULL,
yieldconvention_id bigint NOT NULL,
guaranteetype_id bigint,
maturity_date timestamp without time zone NOT NULL,
maturity_zone varchar(50) NOT NULL,
maturity_accuracy smallint NOT NULL,
coupontype_id bigint NOT NULL,
couponrate double precision NOT NULL,
couponfrequency_id bigint NOT NULL,
daycountconvention_id bigint NOT NULL,
businessdayconvention_id bigint,
announcement_date timestamp without time zone,
announcement_zone varchar(50),
interestaccrual_date timestamp without time zone NOT NULL,
interestaccrual_zone varchar(50) NOT NULL,
settlement_date timestamp without time zone,
settlement_zone varchar(50),
firstcoupon_date timestamp without time zone NOT NULL,
firstcoupon_zone varchar(50) NOT NULL,
issuanceprice double precision,
totalamountissued double precision NOT NULL,
minimumamount double precision NOT NULL,
minimumincrement double precision NOT NULL,
paramount double precision NOT NULL,
redemptionvalue double precision NOT NULL,
PRIMARY KEY (id),
CONSTRAINT sec_fk_bond2sec FOREIGN KEY (security_id) REFERENCES sec_security (id),
CONSTRAINT sec_fk_bond2issuertype FOREIGN KEY (issuertype_id) REFERENCES sec_issuertype (id),
CONSTRAINT sec_fk_bond2market FOREIGN KEY (market_id) REFERENCES sec_market (id),
CONSTRAINT sec_fk_bond2currency FOREIGN KEY (currency_id) REFERENCES sec_currency (id),
CONSTRAINT sec_fk_bond2yieldconvention FOREIGN KEY (yieldconvention_id) REFERENCES sec_yieldconvention (id),
CONSTRAINT sec_fk_bond2guaranteetype FOREIGN KEY (guaranteetype_id) REFERENCES sec_guaranteetype (id),
CONSTRAINT sec_fk_bond2coupontype FOREIGN KEY (coupontype_id) REFERENCES sec_coupontype (id),
CONSTRAINT sec_fk_bond2frequency FOREIGN KEY (couponfrequency_id) REFERENCES sec_frequency (id),
CONSTRAINT sec_fk_bond2daycount FOREIGN KEY (daycountconvention_id) REFERENCES sec_daycount (id),
CONSTRAINT sec_fk_bond2businessdayconvention FOREIGN KEY (businessdayconvention_id) REFERENCES sec_businessdayconvention (id)
);
CREATE INDEX ix_sec_bond_security_id ON sec_bond(security_id);
CREATE TABLE sec_contract_category (
id bigint NOT NULL,
name varchar(255) NOT NULL UNIQUE,
description varchar(255),
PRIMARY KEY (id)
);
CREATE TABLE sec_future (
id bigint NOT NULL,
security_id bigint NOT NULL,
future_type varchar(32) NOT NULL,
expiry_date timestamp without time zone NOT NULL,
expiry_zone varchar(50) NOT NULL,
expiry_accuracy smallint NOT NULL,
tradingexchange_id bigint NOT NULL,
settlementexchange_id bigint NOT NULL,
currency1_id bigint,
currency2_id bigint,
currency3_id bigint,
unitname_id bigint,
unitnumber double precision,
unit_amount double precision,
underlying_scheme varchar(255),
underlying_identifier varchar(255),
bondFutureFirstDeliveryDate timestamp without time zone,
bondFutureFirstDeliveryDate_zone varchar(50),
bondFutureLastDeliveryDate timestamp without time zone,
bondFutureLastDeliveryDate_zone varchar(50),
contract_category_id bigint, -- most of the curren future has no category defined so the column needs to stay nullable
PRIMARY KEY (id),
CONSTRAINT sec_fk_future2sec FOREIGN KEY (security_id) REFERENCES sec_security (id),
CONSTRAINT sec_fk_future2exchange1 FOREIGN KEY (tradingexchange_id) REFERENCES sec_exchange (id),
CONSTRAINT sec_fk_future2exchange2 FOREIGN KEY (settlementexchange_id) REFERENCES sec_exchange (id),
CONSTRAINT sec_fk_future2currency1 FOREIGN KEY (currency1_id) REFERENCES sec_currency (id),
CONSTRAINT sec_fk_future2currency2 FOREIGN KEY (currency2_id) REFERENCES sec_currency (id),
CONSTRAINT sec_fk_future2currency3 FOREIGN KEY (currency3_id) REFERENCES sec_currency (id),
CONSTRAINT sec_fk_future2unit FOREIGN KEY (unitname_id) REFERENCES sec_unit (id),
CONSTRAINT sec_fk_future2contract_category FOREIGN KEY (contract_category_id) REFERENCES sec_contract_category (id)
);
CREATE INDEX ix_sec_future_security_id ON sec_future(security_id);
CREATE TABLE sec_futurebundle (
id bigint NOT NULL,
future_id bigint NOT NULL,
startDate timestamp without time zone,
endDate timestamp without time zone,
conversionFactor double precision NOT NULL,
PRIMARY KEY (id),
CONSTRAINT sec_fk_futurebundle2future FOREIGN KEY (future_id) REFERENCES sec_future (id)
);
CREATE TABLE sec_futurebundleidentifier (
bundle_id bigint NOT NULL,
scheme varchar(255) NOT NULL,
identifier varchar(255) NOT NULL,
PRIMARY KEY (bundle_id, scheme, identifier),
CONSTRAINT sec_fk_futurebundleidentifier2futurebundle FOREIGN KEY (bundle_id) REFERENCES sec_futurebundle (id)
);
CREATE TABLE sec_commodity_forward (
id bigint NOT NULL,
security_id bigint NOT NULL,
forward_type varchar(32) NOT NULL,
expiry_date timestamp without time zone NOT NULL,
expiry_zone varchar(50) NOT NULL,
expiry_accuracy smallint NOT NULL,
currency_id bigint,
unitname_id bigint,
unitnumber double precision,
unit_amount double precision,
underlying_scheme varchar(255),
underlying_identifier varchar(255),
contract_category_id bigint NOT NULL,
PRIMARY KEY (id),
CONSTRAINT sec_fk_commodity_forward2sec FOREIGN KEY (security_id) REFERENCES sec_security (id),
CONSTRAINT sec_fk_commodity_forward2currency FOREIGN KEY (currency_id) REFERENCES sec_currency (id),
CONSTRAINT sec_fk_commodity_forward2unit FOREIGN KEY (unitname_id) REFERENCES sec_unit (id),
CONSTRAINT sec_fk_commodity_forward2contract_category FOREIGN KEY (contract_category_id) REFERENCES sec_contract_category (id)
);
CREATE INDEX ix_sec_commodity_forward_security_id ON sec_commodity_forward(security_id);
CREATE TABLE sec_cash (
id bigint NOT NULL,
security_id bigint NOT NULL,
currency_id bigint NOT NULL,
region_scheme varchar(255) NOT NULL,
region_identifier varchar(255) NOT NULL,
start_date timestamp without time zone NOT NULL,
start_zone varchar(50) NOT NULL,
maturity_date timestamp without time zone NOT NULL,
maturity_zone varchar(50) NOT NULL,
daycount_id bigint NOT NULL,
rate double precision NOT NULL,
amount double precision NOT NULL,
PRIMARY KEY (id),
CONSTRAINT sec_fk_cash2sec FOREIGN KEY (security_id) REFERENCES sec_security (id),
CONSTRAINT sec_fk_cash2currency FOREIGN KEY (currency_id) REFERENCES sec_currency (id),
CONSTRAINT sec_fk_cash2daycount FOREIGN KEY (daycount_id) REFERENCES sec_daycount (id)
);
CREATE TABLE sec_fra (
id bigint NOT NULL,
security_id bigint NOT NULL,
currency_id bigint NOT NULL,
region_scheme varchar(255) NOT NULL,
region_identifier varchar(255) NOT NULL,
start_date timestamp without time zone NOT NULL,
start_zone varchar(50) NOT NULL,
end_date timestamp without time zone NOT NULL,
end_zone varchar(50) NOT NULL,
rate double precision NOT NULL,
amount double precision NOT NULL,
underlying_scheme varchar(255) NOT NULL,
underlying_identifier varchar(255) NOT NULL,
fixing_date timestamp without time zone NOT NULL,
fixing_zone varchar(50) NOT NULL,
PRIMARY KEY (id),
CONSTRAINT sec_fk_fra2sec FOREIGN KEY (security_id) REFERENCES sec_security (id),
CONSTRAINT sec_fk_fra2currency FOREIGN KEY (currency_id) REFERENCES sec_currency (id)
);
CREATE TABLE sec_swap (
id bigint NOT NULL,
security_id bigint NOT NULL,
swaptype varchar(32) NOT NULL,
trade_date timestamp without time zone NOT NULL,
trade_zone varchar(50) NOT NULL,
effective_date timestamp without time zone NOT NULL,
effective_zone varchar(50) NOT NULL,
maturity_date timestamp without time zone NOT NULL,
maturity_zone varchar(50) NOT NULL,
forwardstart_date timestamp without time zone,
forwardstart_zone varchar(50),
counterparty varchar(255) NOT NULL,
pay_legtype varchar(32) NOT NULL,
pay_daycount_id bigint NOT NULL,
pay_frequency_id bigint NOT NULL,
pay_regionscheme varchar(255) NOT NULL,
pay_regionid varchar(255) NOT NULL,
pay_businessdayconvention_id bigint NOT NULL,
pay_notionaltype varchar(32) NOT NULL,
pay_notionalcurrency_id bigint,
pay_notionalamount double precision,
pay_notionalscheme varchar(255),
pay_notionalid varchar(255),
pay_rate double precision,
pay_iseom boolean NOT NULL,
pay_spread double precision,
pay_rateidentifierscheme varchar(255),
pay_rateidentifierid varchar(255),
pay_floating_rate_type varchar(32),
pay_settlement_days INTEGER,
pay_gearing DOUBLE precision,
pay_offset_fixing_id bigint,
pay_strike double precision,
pay_variance_swap_type varchar(32),
pay_underlying_identifier varchar(255),
pay_underlying_scheme varchar(255),
pay_monitoring_frequency_id bigint,
pay_annualization_factor double precision,
receive_legtype varchar(32) NOT NULL,
receive_daycount_id bigint NOT NULL,
receive_frequency_id bigint NOT NULL,
receive_regionscheme varchar(255) NOT NULL,
receive_regionid varchar(255) NOT NULL,
receive_businessdayconvention_id bigint NOT NULL,
receive_notionaltype varchar(32) NOT NULL,
receive_notionalcurrency_id bigint,
receive_notionalamount double precision,
receive_notionalscheme varchar(255),
receive_notionalid varchar(255),
receive_rate double precision,
receive_iseom boolean NOT NULL,
receive_spread double precision,
receive_rateidentifierscheme varchar(255),
receive_rateidentifierid varchar(255),
receive_floating_rate_type varchar(32),
receive_settlement_days INTEGER,
receive_gearing DOUBLE precision,
receive_offset_fixing_id bigint,
receive_strike double precision,
receive_variance_swap_type varchar(32),
receive_underlying_identifier varchar(255),
receive_underlying_scheme varchar(255),
receive_monitoring_frequency_id bigint,
receive_annualization_factor double precision,
PRIMARY KEY (id),
CONSTRAINT sec_fk_swap2sec FOREIGN KEY (security_id) REFERENCES sec_security (id),
CONSTRAINT sec_fk_payfreq2frequency FOREIGN KEY (pay_frequency_id) REFERENCES sec_frequency (id),
CONSTRAINT sec_fk_receivefreq2frequency FOREIGN KEY (receive_frequency_id) REFERENCES sec_frequency (id),
CONSTRAINT sec_fk_payoffset2frequency FOREIGN KEY (pay_offset_fixing_id) REFERENCES sec_frequency (id),
CONSTRAINT sec_fk_recvoffset2frequency FOREIGN KEY (receive_offset_fixing_id) REFERENCES sec_frequency (id),
CONSTRAINT sec_fk_paymonitorfreq2frequency FOREIGN KEY (pay_monitoring_frequency_id) REFERENCES sec_frequency (id),
CONSTRAINT sec_fk_recvmonitorfreq2frequency FOREIGN KEY (receive_monitoring_frequency_id) REFERENCES sec_frequency (id)
);
CREATE INDEX ix_sec_swap_security_id ON sec_swap(security_id);
CREATE TABLE sec_raw (
security_id bigint NOT NULL,
raw_data blob NOT NULL,
CONSTRAINT sec_fk_raw2sec FOREIGN KEY (security_id) REFERENCES sec_security (id)
);
CREATE TABLE sec_fxforward (
id bigint NOT NULL,
security_id bigint NOT NULL,
region_scheme varchar(255) NOT NULL,
region_identifier varchar(255) NOT NULL,
pay_currency_id bigint NOT NULL,
receive_currency_id bigint NOT NULL,
pay_amount DOUBLE PRECISION NOT NULL,
receive_amount DOUBLE PRECISION NOT NULL,
forward_date timestamp without time zone NOT NULL,
forward_zone varchar(50) NOT NULL,
PRIMARY KEY (id),
CONSTRAINT sec_fk_fxforward2sec FOREIGN KEY (security_id) REFERENCES sec_security (id),
CONSTRAINT sec_fk_fxforward_pay2currency FOREIGN KEY (pay_currency_id) REFERENCES sec_currency (id),
CONSTRAINT sec_fk_fxforward_rcv2currency FOREIGN KEY (receive_currency_id) REFERENCES sec_currency (id)
);
CREATE INDEX ix_sec_fxforward_security_id ON sec_fxforward(security_id);
CREATE TABLE sec_nondeliverablefxforward (
id bigint NOT NULL,
security_id bigint NOT NULL,
region_scheme varchar(255) NOT NULL,
region_identifier varchar(255) NOT NULL,
pay_currency_id bigint NOT NULL,
receive_currency_id bigint NOT NULL,
pay_amount DOUBLE PRECISION NOT NULL,
receive_amount DOUBLE PRECISION NOT NULL,
forward_date timestamp without time zone NOT NULL,
forward_zone varchar(50) NOT NULL,
is_delivery_in_receive_currency boolean NOT NULL,
PRIMARY KEY (id),
CONSTRAINT sec_fk_nondeliverablefxforward2sec FOREIGN KEY (security_id) REFERENCES sec_security (id),
CONSTRAINT sec_fk_nondeliverablefxforward_pay2currency FOREIGN KEY (pay_currency_id) REFERENCES sec_currency (id),
CONSTRAINT sec_fk_nondeliverablefxforward_rcv2currency FOREIGN KEY (receive_currency_id) REFERENCES sec_currency (id)
);
CREATE INDEX ix_sec_nondeliverablefxforward_security_id ON sec_nondeliverablefxforward(security_id);
CREATE TABLE sec_capfloor (
id bigint NOT NULL,
security_id bigint NOT NULL,
currency_id bigint NOT NULL,
daycountconvention_id bigint NOT NULL,
frequency_id bigint NOT NULL,
is_cap boolean NOT NULL,
is_ibor boolean NOT NULL,
is_payer boolean NOT NULL,
maturity_date timestamp without time zone NOT NULL,
maturity_zone varchar(50) NOT NULL,
notional double precision NOT NULL,
start_date timestamp without time zone NOT NULL,
start_zone varchar(50) NOT NULL,
strike double precision NOT NULL,
underlying_scheme varchar(255) NOT NULL,
underlying_identifier varchar(255) NOT NULL,
PRIMARY KEY (id),
CONSTRAINT sec_fk_capfloor2sec FOREIGN KEY (security_id) REFERENCES sec_security (id),
CONSTRAINT sec_fk_capfloor2currency FOREIGN KEY (currency_id) REFERENCES sec_currency(id),
CONSTRAINT sec_fk_capfloor2daycount FOREIGN KEY (daycountconvention_id) REFERENCES sec_daycount (id),
CONSTRAINT sec_fk_capfloor2frequency FOREIGN KEY (frequency_id) REFERENCES sec_frequency (id)
);
CREATE TABLE sec_capfloorcmsspread (
id bigint NOT NULL,
security_id bigint NOT NULL,
currency_id bigint NOT NULL,
daycountconvention_id bigint NOT NULL,
frequency_id bigint NOT NULL,
is_cap boolean NOT NULL,
is_payer boolean NOT NULL,
long_scheme varchar(255) NOT NULL,
long_identifier varchar(255) NOT NULL,
maturity_date timestamp without time zone NOT NULL,
maturity_zone varchar(50) NOT NULL,
notional double precision NOT NULL,
short_scheme varchar(255) NOT NULL,
short_identifier varchar(255) NOT NULL,
start_date timestamp without time zone NOT NULL,
start_zone varchar(50) NOT NULL,
strike double precision NOT NULL,
PRIMARY KEY (id),
CONSTRAINT sec_fk_capfloorcmsspread2sec FOREIGN KEY (security_id) REFERENCES sec_security (id),
CONSTRAINT sec_fk_capfloorcmsspread2currency FOREIGN KEY (currency_id) REFERENCES sec_currency(id),
CONSTRAINT sec_fk_capfloorcmsspread2daycount FOREIGN KEY (daycountconvention_id) REFERENCES sec_daycount (id),
CONSTRAINT sec_fk_capfloorcmsspread2frequency FOREIGN KEY (frequency_id) REFERENCES sec_frequency (id)
);
CREATE TABLE sec_equity_variance_swap (
id bigint NOT NULL,
security_id bigint NOT NULL,
annualization_factor double precision NOT NULL,
currency_id bigint NOT NULL,
first_observation_date timestamp without time zone NOT NULL,
first_observation_zone varchar(50) NOT NULL,
last_observation_date timestamp without time zone NOT NULL,
last_observation_zone varchar(50) NOT NULL,
notional double precision NOT NULL,
observation_frequency_id bigint NOT NULL,
parameterised_as_variance boolean NOT NULL,
region_scheme varchar(255) NOT NULL,
region_id varchar(255) NOT NULL,
settlement_date timestamp without time zone NOT NULL,
settlement_zone varchar(50) NOT NULL,
spot_scheme varchar(255) NOT NULL,
spot_id varchar(255) NOT NULL,
strike double precision NOT NULL,
PRIMARY KEY (id),
CONSTRAINT sec_fk_equityvarianceswap2sec FOREIGN KEY (security_id) REFERENCES sec_security (id),
CONSTRAINT sec_fk_equityvarianceswap2currency FOREIGN KEY (currency_id) REFERENCES sec_currency(id),
CONSTRAINT sec_fk_equityvarianceswap2frequency FOREIGN KEY (observation_frequency_id) REFERENCES sec_frequency (id)
);
CREATE SEQUENCE IF NOT EXISTS sec_security_attr_seq
start with 1000 increment by 1 no cycle;
CREATE TABLE sec_security_attribute (
id bigint not null,
security_id bigint not null,
security_oid bigint not null,
attr_key varchar(255) not null,
attr_value varchar(255) not null,
primary key (id),
constraint sec_fk_securityattr2security foreign key (security_id) references sec_security (id),
constraint sec_chk_uq_security_attribute unique (security_id, attr_key, attr_value)
);
-- security_oid is an optimization
-- sec_security_attribute is fully dependent of sec_security
CREATE INDEX ix_sec_security_attr_security_oid ON sec_security_attribute(security_oid);
CREATE INDEX ix_sec_security_attr_key ON sec_security_attribute(attr_key);
| Java |
define(["Log","FS"],function (Log,FS) {//MODJSL
return function showErrorPos(elem, err) {
var mesg, src, pos;
if (!err) {
close();
return;
}
var row,col;
if (err.isTError) {
mesg=err.mesg;
src=err.src;
pos=err.pos;
row=err.row+1;
col=err.col+1;
} else {
src={name:function (){return "不明";},text:function () {
return null;
}};
pos=0;
mesg=err;
}
function close(){
elem.empty();
}
if(typeof pos=="object") {row=pos.row; col=pos.col;}
close();
var mesgd=$("<div>").text(mesg+" 場所:"+src.name()+(typeof row=="number"?":"+row+":"+col:""));
//mesgd.append($("<button>").text("閉じる").click(close));
elem.append(mesgd);
elem.append($("<div>").attr("class","quickFix"));
console.log("src=",src);
var str=src.text();
if (str && typeof pos=="object") {
var npos=0;
var lines=str.split(/\n/);
for (var i=0 ; i<lines.length && i+1<pos.row ; i++) {
npos+=lines[i].length;
}
npos+=pos.col;
pos=npos;
}
var srcd=$("<pre>");
srcd.append($("<span>").text(str.substring(0,pos)));
srcd.append($("<img>").attr("src",FS.expandPath("${sampleImg}/ecl.png")));//MODJSL
srcd.append($("<span>").text(str.substring(pos)));
elem.append(srcd);
//elem.attr("title",mesg+" 場所:"+src.name());
elem.attr("title","エラー");
var diag=elem.dialog({width:600,height:400});
Log.d("error", mesg+"\nat "+src+":"+err.pos+"\n"+str.substring(0,err.pos)+"##HERE##"+str.substring(err.pos));
return diag;
};
}); | Java |
package io.indexr.query.expr.arith;
import com.google.common.collect.Lists;
import java.util.List;
import io.indexr.query.expr.BinaryExpression;
import io.indexr.query.expr.Expression;
import io.indexr.query.types.DataType;
public abstract class BinaryArithmetic extends Expression implements BinaryExpression {
public Expression left, right;
protected DataType dataType;
protected DataType leftType;
protected DataType rightType;
public BinaryArithmetic(Expression left, Expression right) {
this.left = left;
this.right = right;
}
protected DataType defaultType() {
return null;
}
protected void initType() {
if (dataType == null) {
leftType = left.dataType();
rightType = right.dataType();
DataType defaultType = defaultType();
if (defaultType == null) {
dataType = BinaryArithmetic.calType(left.dataType(), right.dataType());
} else {
dataType = defaultType;
}
}
}
@Override
public Expression left() {
return left;
}
@Override
public Expression right() {
return right;
}
@Override
public DataType dataType() {
initType();
return dataType;
}
@Override
public List<Expression> children() {
return Lists.newArrayList(left, right);
}
@Override
public boolean resolved() {
return childrenResolved() && checkInputDataTypes().isSuccess;
}
public static DataType calType(DataType type1, DataType type2) {
return type1.ordinal() >= type2.ordinal() ? type1 : type2;
}
}
| Java |
package org.ovirt.engine.ui.common.widget.table.column;
import org.ovirt.engine.core.common.businessentities.Disk;
import com.google.gwt.user.cellview.client.Column;
public class DiskStatusColumn extends Column<Disk, Disk> {
public DiskStatusColumn() {
super(new DiskStatusCell());
}
@Override
public Disk getValue(Disk object) {
return object;
}
}
| Java |
EXP_SOURCES = exp_agent.c
SOURCES += $(EXP_SOURCES:%.c=math/exp/%.c)
| Java |
# Palindrome Number
## Problem:
Determine whether an integer is a palindrome. Do this without extra space.
## Solution
I can think of two ways
1. Convert to string and check string is palindrome.
2. Reverse the number and then check if reverse number is equal to the number. Please check the implementation | Java |
package com.twitter.finagle.kestrel.unit
import com.twitter.concurrent.{Broker, Offer}
import com.twitter.conversions.time._
import com.twitter.finagle.kestrel._
import com.twitter.finagle.kestrel.net.lag.kestrel.thriftscala.Item
import com.twitter.finagle.kestrel.protocol.{Command, _}
import com.twitter.finagle.memcached.util.ChannelBufferUtils._
import com.twitter.finagle.{Service, ServiceFactory}
import com.twitter.util._
import org.jboss.netty.buffer.{ChannelBuffer, ChannelBuffers}
import org.junit.runner.RunWith
import org.mockito.Mockito
import org.mockito.Mockito.{times, verify, when}
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar
// all this so we can spy() on a client.
class MockClient extends Client {
def set(queueName: String, value: ChannelBuffer, expiry: Time = Time.epoch) = null
def get(queueName: String, waitUpTo: Duration = 0.seconds): Future[Option[ChannelBuffer]] = null
def delete(queueName: String): Future[Response] = null
def flush(queueName: String): Future[Response] = null
def read(queueName: String): ReadHandle = null
def write(queueName: String, offer: Offer[ChannelBuffer]): Future[Throwable] = null
def close() {}
}
@RunWith(classOf[JUnitRunner])
class ClientTest extends FunSuite with MockitoSugar {
trait GlobalHelper {
def buf(i: Int) = ChannelBuffers.wrappedBuffer("%d".format(i).getBytes)
def msg(i: Int) = {
val m = mock[ReadMessage]
when(m.bytes) thenReturn buf(i)
m
}
}
trait ClientReliablyHelper extends GlobalHelper {
val messages = new Broker[ReadMessage]
val error = new Broker[Throwable]
val client = Mockito.spy(new MockClient)
val rh = mock[ReadHandle]
when(rh.messages) thenReturn messages.recv
when(rh.error) thenReturn error.recv
when(client.read("foo")) thenReturn rh
}
test("Client.readReliably should proxy messages") {
new ClientReliablyHelper {
val h = client.readReliably("foo")
verify(client).read("foo")
val f = (h.messages ?)
assert(f.isDefined === false)
val m = msg(0)
messages ! m
assert(f.isDefined === true)
assert(Await.result(f) === m)
assert((h.messages ?).isDefined === false)
}
}
test("Client.readReliably should reconnect on failure") {
new ClientReliablyHelper {
val h = client.readReliably("foo")
verify(client).read("foo")
val m = msg(0)
messages ! m
assert((h.messages ??) === m)
val messages2 = new Broker[ReadMessage]
val error2 = new Broker[Throwable]
val rh2 = mock[ReadHandle]
when(rh2.messages) thenReturn messages2.recv
when(rh2.error) thenReturn error2.recv
when(client.read("foo")) thenReturn rh2
error ! new Exception("wtf")
verify(client, times(2)).read("foo")
messages ! m
// an errant message on broken channel
// new messages must make it
val f = (h.messages ?)
assert(f.isDefined === false)
val m2 = msg(2)
messages2 ! m2
assert(f.isDefined === true)
assert(Await.result(f) === m2)
}
}
test("Client.readReliably should reconnect on failure(with delay)") {
Time.withCurrentTimeFrozen { tc =>
new ClientReliablyHelper {
val timer = new MockTimer
val delays = Stream(1.seconds, 2.seconds, 3.second)
val h = client.readReliably("foo", timer, delays)
verify(client).read("foo")
val errf = (h.error ?)
delays.zipWithIndex foreach { case (delay, i) =>
verify(client, times(i + 1)).read("foo")
error ! new Exception("sad panda")
tc.advance(delay)
timer.tick()
verify(client, times(i + 2)).read("foo")
assert(errf.isDefined === false)
}
error ! new Exception("final sad panda")
assert(errf.isDefined === true)
assert(Await.result(errf) === OutOfRetriesException)
}
}
}
test("Client.readReliably should close on close requested") {
new ClientReliablyHelper {
val h = client.readReliably("foo")
verify(rh, times(0)).close()
h.close()
verify(rh).close()
}
}
test("ConnectedClient.read should interrupt current request on close") {
new GlobalHelper {
val queueName = "foo"
val factory = mock[ServiceFactory[Command, Response]]
val service = mock[Service[Command, Response]]
val client = new ConnectedClient(factory)
val open = Open(queueName, Some(Duration.Top))
val closeAndOpen = CloseAndOpen(queueName, Some(Duration.Top))
val abort = Abort(queueName)
when(factory.apply()) thenReturn Future(service)
val promise = new Promise[Response]()
@volatile var wasInterrupted = false
promise.setInterruptHandler { case _cause =>
wasInterrupted = true
}
when(service(open)) thenReturn promise
when(service(closeAndOpen)) thenReturn promise
when(service(abort)) thenReturn Future(Values(Seq()))
val rh = client.read(queueName)
assert(wasInterrupted === false)
rh.close()
assert(wasInterrupted === true)
}
}
test("ThriftConnectedClient.read should interrupt current trift request on close") {
val queueName = "foo"
val clientFactory = mock[FinagledClientFactory]
val finagledClient = mock[FinagledClosableClient]
val client = new ThriftConnectedClient(clientFactory, Duration.Top)
when(clientFactory.apply()) thenReturn Future(finagledClient)
val promise = new Promise[Seq[Item]]()
@volatile var wasInterrupted = false
promise.setInterruptHandler { case _cause =>
wasInterrupted = true
}
when(finagledClient.get(queueName, 1, Int.MaxValue, Int.MaxValue)) thenReturn promise
val rh = client.read(queueName)
assert(wasInterrupted === false)
rh.close()
assert(wasInterrupted === true)
}
}
| Java |
misc
====
Small stuff
| Java |
/*
* Copyright (C) 2016 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.google.android.exoplayer2.text.tx3g;
import static com.google.common.truth.Truth.assertThat;
import android.graphics.Color;
import android.graphics.Typeface;
import android.test.InstrumentationTestCase;
import android.text.SpannedString;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.text.style.TypefaceSpan;
import android.text.style.UnderlineSpan;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.testutil.TestUtil;
import com.google.android.exoplayer2.text.Cue;
import com.google.android.exoplayer2.text.Subtitle;
import com.google.android.exoplayer2.text.SubtitleDecoderException;
import java.io.IOException;
import java.util.Collections;
/**
* Unit test for {@link Tx3gDecoder}.
*/
public final class Tx3gDecoderTest extends InstrumentationTestCase {
private static final String NO_SUBTITLE = "tx3g/no_subtitle";
private static final String SAMPLE_JUST_TEXT = "tx3g/sample_just_text";
private static final String SAMPLE_WITH_STYL = "tx3g/sample_with_styl";
private static final String SAMPLE_WITH_STYL_ALL_DEFAULTS = "tx3g/sample_with_styl_all_defaults";
private static final String SAMPLE_UTF16_BE_NO_STYL = "tx3g/sample_utf16_be_no_styl";
private static final String SAMPLE_UTF16_LE_NO_STYL = "tx3g/sample_utf16_le_no_styl";
private static final String SAMPLE_WITH_MULTIPLE_STYL = "tx3g/sample_with_multiple_styl";
private static final String SAMPLE_WITH_OTHER_EXTENSION = "tx3g/sample_with_other_extension";
private static final String SAMPLE_WITH_TBOX = "tx3g/sample_with_tbox";
private static final String INITIALIZATION = "tx3g/initialization";
private static final String INITIALIZATION_ALL_DEFAULTS = "tx3g/initialization_all_defaults";
public void testDecodeNoSubtitle() throws IOException, SubtitleDecoderException {
Tx3gDecoder decoder = new Tx3gDecoder(Collections.<byte[]>emptyList());
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), NO_SUBTITLE);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
assertThat(subtitle.getCues(0)).isEmpty();
}
public void testDecodeJustText() throws IOException, SubtitleDecoderException {
Tx3gDecoder decoder = new Tx3gDecoder(Collections.<byte[]>emptyList());
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_JUST_TEXT);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("CC Test");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(0);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.85f);
}
public void testDecodeWithStyl() throws IOException, SubtitleDecoderException {
Tx3gDecoder decoder = new Tx3gDecoder(Collections.<byte[]>emptyList());
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_WITH_STYL);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("CC Test");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(3);
StyleSpan styleSpan = findSpan(text, 0, 6, StyleSpan.class);
assertThat(styleSpan.getStyle()).isEqualTo(Typeface.BOLD_ITALIC);
findSpan(text, 0, 6, UnderlineSpan.class);
ForegroundColorSpan colorSpan = findSpan(text, 0, 6, ForegroundColorSpan.class);
assertThat(colorSpan.getForegroundColor()).isEqualTo(Color.GREEN);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.85f);
}
public void testDecodeWithStylAllDefaults() throws IOException, SubtitleDecoderException {
Tx3gDecoder decoder = new Tx3gDecoder(Collections.<byte[]>emptyList());
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_WITH_STYL_ALL_DEFAULTS);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("CC Test");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(0);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.85f);
}
public void testDecodeUtf16BeNoStyl() throws IOException, SubtitleDecoderException {
Tx3gDecoder decoder = new Tx3gDecoder(Collections.<byte[]>emptyList());
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_UTF16_BE_NO_STYL);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("你好");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(0);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.85f);
}
public void testDecodeUtf16LeNoStyl() throws IOException, SubtitleDecoderException {
Tx3gDecoder decoder = new Tx3gDecoder(Collections.<byte[]>emptyList());
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_UTF16_LE_NO_STYL);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("你好");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(0);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.85f);
}
public void testDecodeWithMultipleStyl() throws IOException, SubtitleDecoderException {
Tx3gDecoder decoder = new Tx3gDecoder(Collections.<byte[]>emptyList());
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_WITH_MULTIPLE_STYL);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("Line 2\nLine 3");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(4);
StyleSpan styleSpan = findSpan(text, 0, 5, StyleSpan.class);
assertThat(styleSpan.getStyle()).isEqualTo(Typeface.ITALIC);
findSpan(text, 7, 12, UnderlineSpan.class);
ForegroundColorSpan colorSpan = findSpan(text, 0, 5, ForegroundColorSpan.class);
assertThat(colorSpan.getForegroundColor()).isEqualTo(Color.GREEN);
colorSpan = findSpan(text, 7, 12, ForegroundColorSpan.class);
assertThat(colorSpan.getForegroundColor()).isEqualTo(Color.GREEN);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.85f);
}
public void testDecodeWithOtherExtension() throws IOException, SubtitleDecoderException {
Tx3gDecoder decoder = new Tx3gDecoder(Collections.<byte[]>emptyList());
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_WITH_OTHER_EXTENSION);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("CC Test");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(2);
StyleSpan styleSpan = findSpan(text, 0, 6, StyleSpan.class);
assertThat(styleSpan.getStyle()).isEqualTo(Typeface.BOLD);
ForegroundColorSpan colorSpan = findSpan(text, 0, 6, ForegroundColorSpan.class);
assertThat(colorSpan.getForegroundColor()).isEqualTo(Color.GREEN);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.85f);
}
public void testInitializationDecodeWithStyl() throws IOException, SubtitleDecoderException {
byte[] initBytes = TestUtil.getByteArray(getInstrumentation(), INITIALIZATION);
Tx3gDecoder decoder = new Tx3gDecoder(Collections.singletonList(initBytes));
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_WITH_STYL);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("CC Test");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(5);
StyleSpan styleSpan = findSpan(text, 0, text.length(), StyleSpan.class);
assertThat(styleSpan.getStyle()).isEqualTo(Typeface.BOLD_ITALIC);
findSpan(text, 0, text.length(), UnderlineSpan.class);
TypefaceSpan typefaceSpan = findSpan(text, 0, text.length(), TypefaceSpan.class);
assertThat(typefaceSpan.getFamily()).isEqualTo(C.SERIF_NAME);
ForegroundColorSpan colorSpan = findSpan(text, 0, text.length(), ForegroundColorSpan.class);
assertThat(colorSpan.getForegroundColor()).isEqualTo(Color.RED);
colorSpan = findSpan(text, 0, 6, ForegroundColorSpan.class);
assertThat(colorSpan.getForegroundColor()).isEqualTo(Color.GREEN);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.1f);
}
public void testInitializationDecodeWithTbox() throws IOException, SubtitleDecoderException {
byte[] initBytes = TestUtil.getByteArray(getInstrumentation(), INITIALIZATION);
Tx3gDecoder decoder = new Tx3gDecoder(Collections.singletonList(initBytes));
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_WITH_TBOX);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("CC Test");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(4);
StyleSpan styleSpan = findSpan(text, 0, text.length(), StyleSpan.class);
assertThat(styleSpan.getStyle()).isEqualTo(Typeface.BOLD_ITALIC);
findSpan(text, 0, text.length(), UnderlineSpan.class);
TypefaceSpan typefaceSpan = findSpan(text, 0, text.length(), TypefaceSpan.class);
assertThat(typefaceSpan.getFamily()).isEqualTo(C.SERIF_NAME);
ForegroundColorSpan colorSpan = findSpan(text, 0, text.length(), ForegroundColorSpan.class);
assertThat(colorSpan.getForegroundColor()).isEqualTo(Color.RED);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.1875f);
}
public void testInitializationAllDefaultsDecodeWithStyl() throws IOException,
SubtitleDecoderException {
byte[] initBytes = TestUtil.getByteArray(getInstrumentation(), INITIALIZATION_ALL_DEFAULTS);
Tx3gDecoder decoder = new Tx3gDecoder(Collections.singletonList(initBytes));
byte[] bytes = TestUtil.getByteArray(getInstrumentation(), SAMPLE_WITH_STYL);
Subtitle subtitle = decoder.decode(bytes, bytes.length, false);
SpannedString text = new SpannedString(subtitle.getCues(0).get(0).text);
assertThat(text.toString()).isEqualTo("CC Test");
assertThat(text.getSpans(0, text.length(), Object.class)).hasLength(3);
StyleSpan styleSpan = findSpan(text, 0, 6, StyleSpan.class);
assertThat(styleSpan.getStyle()).isEqualTo(Typeface.BOLD_ITALIC);
findSpan(text, 0, 6, UnderlineSpan.class);
ForegroundColorSpan colorSpan = findSpan(text, 0, 6, ForegroundColorSpan.class);
assertThat(colorSpan.getForegroundColor()).isEqualTo(Color.GREEN);
assertFractionalLinePosition(subtitle.getCues(0).get(0), 0.85f);
}
private static <T> T findSpan(SpannedString testObject, int expectedStart, int expectedEnd,
Class<T> expectedType) {
T[] spans = testObject.getSpans(0, testObject.length(), expectedType);
for (T span : spans) {
if (testObject.getSpanStart(span) == expectedStart
&& testObject.getSpanEnd(span) == expectedEnd) {
return span;
}
}
fail("Span not found.");
return null;
}
private static void assertFractionalLinePosition(Cue cue, float expectedFraction) {
assertThat(cue.lineType).isEqualTo(Cue.LINE_TYPE_FRACTION);
assertThat(cue.lineAnchor).isEqualTo(Cue.ANCHOR_TYPE_START);
assertThat(Math.abs(expectedFraction - cue.line) < 1e-6).isTrue();
}
}
| Java |
# .lagoon.yml
The `.lagoon.yml` file is the central file to set up your project. It contains configuration in order to do the following:
* [Define routes for accessing your sites](#routes).
* [Define pre-rollout tasks](#pre-rollout-tasks-pre_rolloutirun).
* [Define post-rollout tasks](#post-rollout-tasks-post_rolloutirun).
* [Set up SSL certificates](#ssl-configuration-tls-acme).
* [Add cron jobs for environments](#cron-jobs-environmentsnamecronjobs)
The `.lagoon.yml` file must be placed at the root of your Git repository.
## Example `.lagoon.yml`
This is an example `.lagoon.yml` which showcases all settings that are possible. You will need to adapt it to your needs.
```
docker-compose-yaml: docker-compose.yml
environment_variables:
git_sha: 'true'
tasks:
pre-rollout:
- run:
name: drush sql-dump
command: mkdir -p /app/web/sites/default/files/private/ && drush sql-dump --ordered-dump --gzip --result-file=/app/web/sites/default/files/private/pre-deploy-dump.sql.gz
service: cli
post-rollout:
- run:
name: drush cim
command: drush -y cim
service: cli
shell: bash
- run:
name: drush cr
command: drush -y cr
service: cli
routes:
autogenerate:
insecure: Redirect
backup-retention:
production:
monthly: 1
weekly: 6
daily: 7
environments:
master:
monitoring_urls:
- "https://www.example.com"
- "https://www.example.com/special_page"
routes:
- nginx:
- example.com
- example.net
- "www.example.com":
tls-acme: 'true'
insecure: Redirect
hsts: max-age=31536000
- "example.ch":
annotations:
nginx.ingress.kubernetes.io/permanent-redirect: https://www.example.ch$request_uri
- www.example.ch
types:
mariadb: mariadb
templates:
mariadb: mariadb.master.deployment.yml
rollouts:
mariadb: statefulset
cronjobs:
- name: drush cron
schedule: "H * * * *" # This will run the cron once per hour.
command: drush cron
service: cli
staging:
cronjobs:
- name: drush cron
schedule: "H * * * *" # This will run the cron once per hour.
command: drush cron
service: cli
```
## General Settings
### `docker-compose-yaml`
Tells the build script which docker-compose YAML file should be used, in order to learn which services and containers should be deployed. This defaults to `docker-compose.yml`, but could be used for a specific Lagoon docker-compose YAML file if you need something like that.
### `environment_variables.git_sha`
This setting allows you to enable injecting the deployed Git SHA into your project as an environment variable. By default this is disabled. Setting the value to`true` sets the SHA as the environment variable `LAGOON_GIT_SHA`.
## Tasks
There are different type of tasks you can define, and they differ when exactly they are executed in a build flow:
### Pre-Rollout Tasks - `pre_rollout.[i].run`
The tasks defined as `pre_rollout` tasks will run against your project _after_ the new images have been built successfully, and _before_ the project gets altered in any way. This feature enables you, for example, to create a database dump before the rollout is running. This will make it easier to roll back in case of an issue with the rollout.
### Post-Rollout Tasks - `post_rollout.[i].run`
Here you can specify tasks which need to run against your project, _after_:
* All images have been successfully built.
* All containers are updated with the new images.
* All containers are running have passed their readiness checks.
Common uses for post-rollout tasks include running `drush updb`, `drush cim`, or clearing various caches.
* `name`
* The name is an arbitrary label for making it easier to identify each task in the logs.
* `command`
* Here you specify what command should run. These are run in the WORKDIR of each container, for Lagoon images this is `/app`, keep this in mind if you need to `cd` into a specific location to run your task.
* `service`
* The service which to run the task in. If following our drupal-example, this will be the CLI container, as it has all your site code, files, and a connection to the database. Typically you do not need to change this.
* `shell`
* Which shell should be used to run the task in. By default `sh` is used, but if the container also has other shells \(like `bash`, you can define it here\). This is useful if you want to run some small if/else bash scripts within the post-rollouts. \(see the example above how to write a script with multiple lines\).
Note: If you would like to temporarily disable pre/post-rollout tasks during a deployment, you can set either of the following environment variables in the API at the project or environment level \(see how on [Environment Variables](environment_variables.md)\).
* `LAGOON_PREROLLOUT_DISABLED=true`
* `LAGOON_POSTROLLOUT_DISABLED=true`
## Backup Retention
### `backup-retention.production.monthly`
Specify the number of monthly backups our system should retain for your project's production environment(s). The default is `1` if this value is not specified.
### `backup-retention.production.weekly`
Specify the number of weekly backups our system should retain for your project's production environment(s). The default is `6` if this value is not specified.
### `backup-retention.production.daily`
Specify the number of daily backups our system should retain for your project's production environment(s). The default is `7` if this value is not specified.
## Routes
### `routes.autogenerate.enabled`
This allows for the disabling of the automatically created routes \(NOT the custom routes per environment, see below for them\) all together.
### `routes.autogenerate.allowPullrequests`
This allows pull request to get autogenerated routes when route autogeneration is disabled.
```
routes:
autogenerate:
enabled: false
allowPullrequests: true
```
### `routes.autogenerate.insecure`
This allows you to define the behavior of the automatic creates routes \(NOT the custom routes per environment, see below for more\). The following options are allowed:
* `Allow` simply sets up routes for both HTTP and HTTPS \(this is the default\).
* `Redirect` will redirect any HTTP requests to HTTPS.
* `None` will mean a route for HTTP will _not_ be created, and no redirect.
### `routes.autogenerate.prefixes`
This allows you to define an array of prefixes to be prepended to the autogenerated routes of each environment. This is useful for things like language prefix domains, or a multi-domain site using the Drupal `domain` module.
NOTE: This is only available for projects which deploy to a Kubernetes cluster.
```
routes:
autogenerate:
prefixes:
- www
- de
- fr
- it
```
## Environments
Environment names match your deployed branches or pull requests. This allows for each environment to have a different config. In our example it will apply to the `master` and `staging` environment.
#### `environments.[name].monitoring_urls`
!!!danger
This feature will be removed in an upcoming release of Lagoon. Please use the newer [`monitoring-path` method](lagoon_yml.md#monitoring-a-specific-path) on your specific route.
At the end of a deploy, Lagoon will check this field for any URLs which you have specified to add to the API for the purpose of monitoring. The default value for this field is the first route for a project. It is useful for adding specific paths of a project to the API, for consumption by a monitoring service.
#### `environments.[name].routes`
In the route section, we identify the domain names to which the environment will respond. It is typical to only have an environment with routes specified for your production environment. All environments receive a generated route, but sometimes there is a need for a non-production environment to have its own domain name. You can specify it here, and then add that domain with your DNS provider as a CNAME to the generated route name \(these routes publish in deploy messages\).
The first element after the environment is the target service, `Nginx` in our example. This is how we identify which service incoming requests will be sent to.
The simplest route is the `example.com` example in our sample `.lagoon.yml` above - you can see it has no additional configuration. This will assume that you want a Let's Encrypt certificate for your route and no redirect from HTTPS to HTTP.
In the `"www.example.com"` example repeated below, we see two more options \(also notice the `:` at the end of the route and that the route is wrapped in `"`, that's important!\):
#### SSL Configuration - `tls-acme`
* `tls-acme: 'true'` tells Lagoon to issue a Let's Encrypt certificate for that route. This is the default. If you don't want a Let's Encrypt, set this to `tls-acme: 'false'`
* `insecure` can be set to `None`, `Allow` or `Redirect`.
* `Allow` simply sets up both routes for HTTP and HTTPS \(this is the default\).
* `Redirect` will redirect any HTTP requests to HTTPS.
* `None` will mean a route for HTTP will _not_ be created, and no redirect will take place.
* `hsts` can be set to a value of `max-age=31536000;includeSubDomains;preload`. Ensure there are no spaces and no other parameters included. Only `max-age` parameter is required. The required `max-age` parameter indicates the length of time, in seconds, the HSTS policy is in effect for.
!!!hint
If you plan to switch from a SSL certificate signed by a Certificate Authority \(CA\) to a Let's Encrypt certificate, it's best get in touch with your Lagoon administrator to oversee the transition. There are [known issues](https://github.com/tnozicka/openshift-acme/issues/68) during the transition. The workaround would be manually removing the CA certificate and then triggering the Let's Encrypt process.
```
- "www.example.com":
tls-acme: 'true'
insecure: Redirect
hsts: max-age=31536000
```
#### Monitoring a specific path
When [UptimeRobot](https://uptimerobot.com/) is configured for your cluster (OpenShift or Kubernetes), Lagoon will inject annotations to each route/ingress for use by the `stakater/IngressControllerMonitor`. The default action is to monitor the homepage of the route. If you have a specific route to be monitored, this can be overriden by adding a `monitoring-path` to your route specification. A common use is to set up a path for monitoring which bypasses caching to give a more real-time monitoring of your site.
```
- "www.example.com":
monitoring-path: "/bypass-cache"
```
#### Ingress annotations (Redirects)
!!!hint
Route/Ingress annotations are only supported by projects that deploy into clusters that run nginx-ingress controllers! Check with your Lagoon administrator if this is supported.
* `annotations` can be a yaml map of [annotations supported by the nginx-ingress controller](https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/annotations/), this is specifically usefull for easy redirects:
In this example any requests to `example.ch` will be redirected to `https://www.example.ch` with keeping folders or query parameters intact (`example.com/folder?query` -> `https://www.example.ch/folder?query`)
```
- "example.ch":
annotations:
nginx.ingress.kubernetes.io/permanent-redirect: https://www.example.ch$request_uri
- www.example.ch
```
You can of course also redirect to any other URL not hosted on Lagoon, this will direct requests to `example.de` to `https://www.google.com`
```
- "example.de":
annotations:
nginx.ingress.kubernetes.io/permanent-redirect: https://www.google.com
```
#### `environments.[name].types`
The Lagoon build process checks the `lagoon.type` label from the `docker-compose.yml` file in order to learn what type of service should be deployed \(read more about them in the [documentation of `docker-compose.yml`](docker-compose_yml.md)\).
Sometimes you might want to override the **type** just for a single environment, and not for all of them. For example, if you want a standalone MariaDB database (instead of letting the Service Broker/operator provision a shared one) for your non-production environment called `develop`:
`service-name: service-type`
* `service-name` is the name of the service from `docker-compose.yml` you would like to override.
* `service-type` the type of the service you would like to use in your override.
Example:
```
environments:
develop:
types:
mariadb: mariadb-single
```
#### `environments.[name].templates`
The Lagoon build process checks the `lagoon.template` label from the `docker-compose.yml` file in order to check if the service needs a custom template file \(read more about them in the [documentation of `docker-compose.yml`](docker-compose_yml.md)\).
Sometimes you might want to override the **template** just for a single environment, and not for all of them:
`service-name: template-file`
* `service-name` is the name of the service from `docker-compose.yml` you would like to override.
* `template-file` is the path and name of the template to use for this service in this environment.
Example:
```
environments:
master:
templates:
mariadb: mariadb.master.deployment.yml
```
#### `environments.[name].rollouts`
The Lagoon build process checks the `lagoon.rollout` label from the `docker-compose.yml` file in order to check if the service needs a special rollout type \(read more about them in the [documentation of `docker-compose.yml`](docker-compose_yml.md)\).
Sometimes you might want to override the **rollout type** just for a single environment, especially if you also overwrote the template type for the environment:
`service-name: rollout-type`
* `service-name` is the name of the service from `docker-compose.yml` you would like to override.
* `rollout-type` is the type of rollout. See [documentation of `docker-compose.yml`](docker-compose_yml.md#custom-rollout-monitor-types)\) for possible values.
Example:
```
environments:
master:
rollouts:
mariadb: statefulset
```
### `environments.[name].autogenerateRoutes`
This allows for any environments to get autogenerated routes when route autogeneration is disabled.
```
routes:
autogenerate:
enabled: false
environments:
develop:
autogenerateRoutes: true
```
#### Cron jobs - `environments.[name].cronjobs`
As most of the time it is not desirable to run the same cron jobs across all environments, you must explicitly define which jobs you want to run for each environment.
* `name:`
* Just a friendly name for identifying what the cron job will do.
* `schedule:`
* The schedule for executing the cron job. This follows the standard convention of cron. If you're not sure about the syntax, [Crontab Generator](https://crontab-generator.org/) can help.
* You can specify `M` for the minute, and your cron job will run once per hour at a random minute \(the same minute each hour\), or `M/15` to run it every 15 mins, but with a random offset from the hour \(like `6,21,36,51`\).
* You can specify `H` for the hour, and your cron job will run once per day at a random hour \(the same hour every day\), or `H(2-4)` to run it once per day within the hours of 2-4.
* `command:`
* The command to execute. Like the tasks, this executes in the WORKDIR of the service. For Lagoon images, this is `/app`.
* `service:`
* Which service of your project to run the command in. For most projects, this is the `CLI` service.
## Polysite
In Lagoon, the same Git repository can be added to multiple projects, creating what is called a Polysite. This allows you to run the same codebase, but allow for different, isolated, databases and persistent files. In `.lagoon.yml` , we currently only support specifying custom routes for a polysite project. The key difference from a standard project is that the `environments` becomes the second-level element, and the project name the top level.
Example:
```
example-project-name:
environments:
master:
routes:
- nginx:
- example.com
```
## Specials
#### `api`
!!!hint
If you run directly on amazee.io you will not need this key set.
With the key `api` you can define another URL that should be used by `lagu` and `drush` to connect to the Lagoon GraphQL `api`. This needs to be a full URL with a scheme, like: `http://localhost:3000` This usually does not need to be changed, but there might be situations where your Lagoon administrator tells you to do so.
#### `ssh`
!!!hint
If you run directly on amazee.io you will not need this key set.
With the key `ssh` you can define another SSH endpoint that should be used by `lagu` and `drush` to connect to the Lagoon remote shell service. This needs to be a hostname and a port separated by a colon, like: `localhost:2020` This usually does not need to be changed, but there might be situations where your Lagoon administrator tells you to do so.
#### `additional-yaml`
The `additional-yaml` has some super powers. Basically, it allows you to define any arbitrary YAML configuration file to be inserted before the build step \(it still needs to be valid Kubernetes/Openshift YAML , though☺\).
Example:
```
additional-yaml:
secrets:
path: .lagoon.secrets.yml
command: create
ignore_error: true
logs-db-secrets:
path: .lagoon.logs-db-secrets.yml
command: create
ignore_error: true
```
Each definition is keyed by a unique name \(`secrets` and `logs-db-secrets` in the example above\), and takes these keys:
* `path` - the path to the YAML file.
* `command` - can either be `create` or `apply`, depending on if you want to run `kubectl create -f [yamlfile]` or `kubectl apply -f [yamlfile].`
* `ignore_error` - either `true` or `false` \(default\). This allows you to instruct the Lagoon build script to ignore any errors that might be returned during running the command. \(This can be useful to handle the case where you want to run `create` during every build, so that new configurations are created, but don't fail if they already exist\).
#### `container-registries`
The `container-registries` block allows you to define your own private container registries to pull custom or private images. To use a private container registry, you will need a `username`, `password`, and optionally the `url` for your registry. If you don't specify a `url` in your YAML, it will default to using Docker Hub.
There are 2 ways to define the password used for your registry user.
* Create an environment variable in the Lagoon API \(see more on [Environment Variables](environment_variables.md)\). The name of the variable you create can then be set as the password:
```
container-registries:
my-custom-registry:
username: myownregistryuser
password: MY_OWN_REGISTRY_PASSWORD
url: my.own.registry.com
```
* Define it directly in the `.lagoon.yml` file in plain text:
```
container-registries:
docker-hub:
username: dockerhubuser
password: MySecretPassword
```
**Consuming a custom or private container registry image**
To consume a custom or private container registry image, you need to update the service inside your `docker-compose.yml` file to use a build context instead of defining an image:
```
services:
mariadb:
build:
context: .
dockerfile: Dockerfile.mariadb
```
Once the `docker-compose.yml` file has been updated to use a build, you need to create the `Dockerfile.<service>` and then set your private image as the `FROM <repo>/<name>:<tag>`
```text
FROM dockerhubuser/my-private-database:tag
```
| Java |
<?php
namespace Spann\Utils;
use Slim\App;
use Slim\Http\Environment;
use Slim\Http\Headers;
use Slim\Http\Request;
use Slim\Http\RequestBody;
use Slim\Http\Response;
use Slim\Http\Uri;
class WebTestClient
{
/** @var \Slim\App */
public $app;
/** @var \Slim\Http\Request */
public $request;
/** @var \Slim\Http\Response */
public $response;
private $cookies = array();
public function __construct(App $slim)
{
$this->app = $slim;
}
public function __call($method, $arguments)
{
throw new \BadMethodCallException(strtoupper($method) . ' is not supported');
}
public function get($path, $data = array(), $optionalHeaders = array())
{
return $this->request('get', $path, $data, $optionalHeaders);
}
public function post($path, $data = array(), $optionalHeaders = array())
{
return $this->request('post', $path, $data, $optionalHeaders);
}
public function patch($path, $data = array(), $optionalHeaders = array())
{
return $this->request('patch', $path, $data, $optionalHeaders);
}
public function put($path, $data = array(), $optionalHeaders = array())
{
return $this->request('put', $path, $data, $optionalHeaders);
}
public function delete($path, $data = array(), $optionalHeaders = array())
{
return $this->request('delete', $path, $data, $optionalHeaders);
}
public function head($path, $data = array(), $optionalHeaders = array())
{
return $this->request('head', $path, $data, $optionalHeaders);
}
public function options($path, $data = array(), $optionalHeaders = array())
{
return $this->request('options', $path, $data, $optionalHeaders);
}
// Abstract way to make a request to SlimPHP, this allows us to mock the
// slim environment
private function request($method, $path, $data = array(), $optionalHeaders = array())
{
//Make method uppercase
$method = strtoupper($method);
$options = array(
'REQUEST_METHOD' => $method,
'REQUEST_URI' => $path
);
if ($method === 'GET') {
$options['QUERY_STRING'] = http_build_query($data);
} else {
$params = json_encode($data);
}
// Prepare a mock environment
$env = Environment::mock(array_merge($options, $optionalHeaders));
$uri = Uri::createFromEnvironment($env);
$headers = Headers::createFromEnvironment($env);
$cookies = $this->cookies;
$serverParams = $env->all();
$body = new RequestBody();
// Attach JSON request
if (isset($params)) {
$headers->set('Content-Type', 'application/json;charset=utf8');
$body->write($params);
}
$this->request = new Request($method, $uri, $headers, $cookies, $serverParams, $body);
$response = new Response();
// Invoke request
$app = $this->app;
$this->response = $app($this->request, $response);
// Return the application output.
return $this->response;
}
public function setCookie($name, $value)
{
$this->cookies[$name] = $value;
}
}
| Java |
"""Support for monitoring OctoPrint sensors."""
from __future__ import annotations
from datetime import datetime, timedelta
import logging
from pyoctoprintapi import OctoprintJobInfo, OctoprintPrinterInfo
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorStateClass,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import PERCENTAGE, TEMP_CELSIUS
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from . import OctoprintDataUpdateCoordinator
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
JOB_PRINTING_STATES = ["Printing from SD", "Printing"]
def _is_printer_printing(printer: OctoprintPrinterInfo) -> bool:
return (
printer
and printer.state
and printer.state.flags
and printer.state.flags.printing
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up the available OctoPrint binary sensors."""
coordinator: OctoprintDataUpdateCoordinator = hass.data[DOMAIN][
config_entry.entry_id
]["coordinator"]
device_id = config_entry.unique_id
assert device_id is not None
entities: list[SensorEntity] = []
if coordinator.data["printer"]:
printer_info = coordinator.data["printer"]
types = ["actual", "target"]
for tool in printer_info.temperatures:
for temp_type in types:
entities.append(
OctoPrintTemperatureSensor(
coordinator,
tool.name,
temp_type,
device_id,
)
)
else:
_LOGGER.error("Printer appears to be offline, skipping temperature sensors")
entities.append(OctoPrintStatusSensor(coordinator, device_id))
entities.append(OctoPrintJobPercentageSensor(coordinator, device_id))
entities.append(OctoPrintEstimatedFinishTimeSensor(coordinator, device_id))
entities.append(OctoPrintStartTimeSensor(coordinator, device_id))
async_add_entities(entities)
class OctoPrintSensorBase(CoordinatorEntity, SensorEntity):
"""Representation of an OctoPrint sensor."""
coordinator: OctoprintDataUpdateCoordinator
def __init__(
self,
coordinator: OctoprintDataUpdateCoordinator,
sensor_type: str,
device_id: str,
) -> None:
"""Initialize a new OctoPrint sensor."""
super().__init__(coordinator)
self._device_id = device_id
self._attr_name = f"OctoPrint {sensor_type}"
self._attr_unique_id = f"{sensor_type}-{device_id}"
@property
def device_info(self):
"""Device info."""
return self.coordinator.device_info
class OctoPrintStatusSensor(OctoPrintSensorBase):
"""Representation of an OctoPrint sensor."""
_attr_icon = "mdi:printer-3d"
def __init__(
self, coordinator: OctoprintDataUpdateCoordinator, device_id: str
) -> None:
"""Initialize a new OctoPrint sensor."""
super().__init__(coordinator, "Current State", device_id)
@property
def native_value(self):
"""Return sensor state."""
printer: OctoprintPrinterInfo = self.coordinator.data["printer"]
if not printer:
return None
return printer.state.text
@property
def available(self) -> bool:
"""Return if entity is available."""
return self.coordinator.last_update_success and self.coordinator.data["printer"]
class OctoPrintJobPercentageSensor(OctoPrintSensorBase):
"""Representation of an OctoPrint sensor."""
_attr_native_unit_of_measurement = PERCENTAGE
_attr_icon = "mdi:file-percent"
def __init__(
self, coordinator: OctoprintDataUpdateCoordinator, device_id: str
) -> None:
"""Initialize a new OctoPrint sensor."""
super().__init__(coordinator, "Job Percentage", device_id)
@property
def native_value(self):
"""Return sensor state."""
job: OctoprintJobInfo = self.coordinator.data["job"]
if not job:
return None
if not (state := job.progress.completion):
return 0
return round(state, 2)
class OctoPrintEstimatedFinishTimeSensor(OctoPrintSensorBase):
"""Representation of an OctoPrint sensor."""
_attr_device_class = SensorDeviceClass.TIMESTAMP
def __init__(
self, coordinator: OctoprintDataUpdateCoordinator, device_id: str
) -> None:
"""Initialize a new OctoPrint sensor."""
super().__init__(coordinator, "Estimated Finish Time", device_id)
@property
def native_value(self) -> datetime | None:
"""Return sensor state."""
job: OctoprintJobInfo = self.coordinator.data["job"]
if (
not job
or not job.progress.print_time_left
or not _is_printer_printing(self.coordinator.data["printer"])
):
return None
read_time = self.coordinator.data["last_read_time"]
return read_time + timedelta(seconds=job.progress.print_time_left)
class OctoPrintStartTimeSensor(OctoPrintSensorBase):
"""Representation of an OctoPrint sensor."""
_attr_device_class = SensorDeviceClass.TIMESTAMP
def __init__(
self, coordinator: OctoprintDataUpdateCoordinator, device_id: str
) -> None:
"""Initialize a new OctoPrint sensor."""
super().__init__(coordinator, "Start Time", device_id)
@property
def native_value(self) -> datetime | None:
"""Return sensor state."""
job: OctoprintJobInfo = self.coordinator.data["job"]
if (
not job
or not job.progress.print_time
or not _is_printer_printing(self.coordinator.data["printer"])
):
return None
read_time = self.coordinator.data["last_read_time"]
return read_time - timedelta(seconds=job.progress.print_time)
class OctoPrintTemperatureSensor(OctoPrintSensorBase):
"""Representation of an OctoPrint sensor."""
_attr_native_unit_of_measurement = TEMP_CELSIUS
_attr_device_class = SensorDeviceClass.TEMPERATURE
_attr_state_class = SensorStateClass.MEASUREMENT
def __init__(
self,
coordinator: OctoprintDataUpdateCoordinator,
tool: str,
temp_type: str,
device_id: str,
) -> None:
"""Initialize a new OctoPrint sensor."""
super().__init__(coordinator, f"{temp_type} {tool} temp", device_id)
self._temp_type = temp_type
self._api_tool = tool
@property
def native_value(self):
"""Return sensor state."""
printer: OctoprintPrinterInfo = self.coordinator.data["printer"]
if not printer:
return None
for temp in printer.temperatures:
if temp.name == self._api_tool:
val = (
temp.actual_temp
if self._temp_type == "actual"
else temp.target_temp
)
if val is None:
return None
return round(val, 2)
return None
@property
def available(self) -> bool:
"""Return if entity is available."""
return self.coordinator.last_update_success and self.coordinator.data["printer"]
| Java |
/*
* Copyright 1999-2017 YaoTrue.
*
* 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.yaotrue.web.command;
import java.io.Serializable;
/**
* @author <a href="mailto:yaotrue@163.com">yaotrue</a>
* 2017年8月16日 下午9:15:05
*/
public class BaseCommand implements Serializable {
/**
* <code>{@value}</code>
*/
private static final long serialVersionUID = 6878114738264710696L;
}
| Java |
import jps
import json
import time
class MessageHolder(object):
def __init__(self):
self._saved_msg = []
def __call__(self, msg):
self._saved_msg.append(msg)
def get_msg(self):
return self._saved_msg
def test_multi_pubsub_once():
holder1 = MessageHolder()
holder2 = MessageHolder()
holder3 = MessageHolder()
sub1 = jps.Subscriber('test_utils1', holder1)
sub2 = jps.Subscriber('test_utils2', holder2)
sub3 = jps.Subscriber('test_utils3', holder3)
pub = jps.utils.JsonMultiplePublisher()
time.sleep(0.1)
pub.publish(
'{"test_utils1": "hoge", "test_utils2": {"x": 3}, "test_utils3": 5}')
time.sleep(0.1)
sub1.spin_once()
sub2.spin_once()
sub3.spin_once()
assert len(holder1.get_msg()) == 1
assert json.loads(holder1.get_msg()[0]) == 'hoge'
assert len(holder2.get_msg()) == 1
obj = json.loads(holder2.get_msg()[0])
assert obj['x'] == 3
assert len(holder3.get_msg()) == 1
assert json.loads(holder3.get_msg()[0]) == 5
def test_to_obj():
msg = '{"aa": 1, "bb": ["hoge", "hogi"], "cc": {"cc1" : 50}}'
converted = jps.utils.to_obj(msg)
assert converted.aa == 1
assert converted.bb[0] == 'hoge'
assert converted.bb[1] == 'hogi'
assert len(converted.bb) == 2
assert converted.cc.cc1 == 50
# todo: do
# json = converted.to_json()
# assert json == msg
# todo
def test_to_obj_list():
msg = '["hoge", "hogi", {"atr1": "val2", "atr2": 1.0}]'
bb = jps.utils.to_obj(msg)
assert len(bb) == 2
assert bb[0] == 'hoge'
assert bb[1] == 'hogi'
assert bb[2].atr1 == 'val2'
assert bb[2].atr2 == 1.0
# json = bb.to_json()
# assert json == msg
def test_to_obj_list():
msg = '[{"hoge": 1}, {"hogi": 2}]'
bb = jps.utils.to_obj(msg)
assert len(bb) == 2
assert bb[0].hoge == 1
assert bb[1].hogi == 2
# todo: list support
# json = bb.to_json()
# assert json == msg
def test_to_obj_simple():
msg = '{"aa": 1, "cc": 3, "bb": 2}'
converted = jps.utils.to_obj(msg)
assert converted.aa == 1
assert converted.bb == 2
assert converted.cc == 3
# works only super simple case
json1 = converted.to_json()
assert json1 == msg
| Java |
const uint16 kRuleIdTable[] = {
42, // Functional "^(助詞|助動詞|動詞,非自立|名詞,非自立|形容詞,非自立|動詞,接尾|名詞,接尾|形容詞,接尾)"
1934, // Unknown "名詞,サ変接続"
2009, // FirstName "名詞,固有名詞,人名,名"
2010, // LastName "名詞,固有名詞,人名,姓"
2047, // Number "名詞,数,アラビア数字"
2049, // KanjiNumber "名詞,数,漢数字"
2, // WeakCompoundPrefix "^(接頭詞,名詞接続|接頭詞,丁寧連用形接続|フィラー)"
287, // AcceptableParticleAtBeginOfSegment "^助詞,*,*,*,*,*,(が|で|と|に|にて|の|へ|より|も|と|から|は|や)$"
2705, // JapanesePunctuations "記号,(句点|読点)"
2707, // OpenBracket "記号,括弧開"
2706, // CloseBracket "記号,括弧閉"
2704, // GeneralSymbol "記号,一般,"
2722, // Zipcode "特殊,郵便番号"
2723, // IsolatedWord "特殊,短縮よみ"
2724, // SuggestOnlyWord "特殊,サジェストのみ"
719, // ContentWordWithConjugation "^(動詞,自立,*,*,五段|動詞,自立,*,*,一段|形容詞,自立)"
42, // SuffixWord "^(助詞|助動詞|動詞,非自立|動詞,接尾|形容詞,非自立|形容詞,接尾|動詞,自立,*,*,サ変・スル)"
2028, // CounterSuffixWord "名詞,接尾,助数詞"
2007, // UniqueNoun "^名詞,固有名詞"
1939, // GeneralNoun "^名詞,一般,*,*,*,*,*$"
1934, // ContentNoun "^名詞,(一般|固有名詞|副詞可能|サ変接続),"
2671, // NounPrefix "^接頭詞,名詞接続,"
2047, // EOSSymbol "^(記号,(句点|読点|アルファベット|一般|括弧開|括弧閉))|^(名詞,数,(アラビア数字|区切り文字))"
12, // Adverb "^副詞,"
287, // AdverbSegmentSuffix "^助詞,*,*,*,*,*,(から|で|と|に|にて|の|へ|を)$"
284, // ParallelMarker "^助詞,並立助詞"
165, // MasuSuffix "助動詞,*,*,*,特殊・(マス|タイ)"
159, // TeSuffix "(助詞,接続助詞,*,*,*,*,て|助動詞,*,*,*,特殊・タ,|動詞,非自立,*,*,一段,*,てる|動詞,非自立,*,*,五段・ワ行促音便,*,ちゃう)"
869, // KagyoTaConnectionVerb "^動詞,(非自立|自立),*,*,五段・カ行(促音便|イ音便),連用タ接続"
936, // WagyoRenyoConnectionVerb "^動詞,(非自立|自立),*,*,五段・ワ行促音便,連用形"
};
namespace {
// Functional "^(助詞|助動詞|動詞,非自立|名詞,非自立|形容詞,非自立|動詞,接尾|名詞,接尾|形容詞,接尾)"
const ::mozc::POSMatcher::Range kRangeTable_Functional[] = {
{ 42, 603 },
{ 1083, 1933 },
{ 2019, 2044 },
{ 2058, 2284 },
{ 2554, 2666 },
{ static_cast<uint16>(0xFFFF), static_cast<uint16>(0xFFFF) },
};
// Unknown "名詞,サ変接続"
const ::mozc::POSMatcher::Range kRangeTable_Unknown[] = {
{ 1934, 1937 },
{ static_cast<uint16>(0xFFFF), static_cast<uint16>(0xFFFF) },
};
// FirstName "名詞,固有名詞,人名,名"
const ::mozc::POSMatcher::Range kRangeTable_FirstName[] = {
{ 2009, 2009 },
{ static_cast<uint16>(0xFFFF), static_cast<uint16>(0xFFFF) },
};
// LastName "名詞,固有名詞,人名,姓"
const ::mozc::POSMatcher::Range kRangeTable_LastName[] = {
{ 2010, 2010 },
{ static_cast<uint16>(0xFFFF), static_cast<uint16>(0xFFFF) },
};
// Number "名詞,数,アラビア数字"
const ::mozc::POSMatcher::Range kRangeTable_Number[] = {
{ 2047, 2047 },
{ static_cast<uint16>(0xFFFF), static_cast<uint16>(0xFFFF) },
};
// KanjiNumber "名詞,数,漢数字"
const ::mozc::POSMatcher::Range kRangeTable_KanjiNumber[] = {
{ 2049, 2056 },
{ static_cast<uint16>(0xFFFF), static_cast<uint16>(0xFFFF) },
};
// WeakCompoundPrefix "^(接頭詞,名詞接続|接頭詞,丁寧連用形接続|フィラー)"
const ::mozc::POSMatcher::Range kRangeTable_WeakCompoundPrefix[] = {
{ 2, 11 },
{ 2669, 2669 },
{ 2671, 2700 },
{ static_cast<uint16>(0xFFFF), static_cast<uint16>(0xFFFF) },
};
// AcceptableParticleAtBeginOfSegment "^助詞,*,*,*,*,*,(が|で|と|に|にて|の|へ|より|も|と|から|は|や)$"
const ::mozc::POSMatcher::Range kRangeTable_AcceptableParticleAtBeginOfSegment[] = {
{ 287, 287 },
{ 290, 290 },
{ 299, 301 },
{ 342, 343 },
{ 346, 346 },
{ 348, 348 },
{ 362, 363 },
{ 376, 376 },
{ 380, 388 },
{ 391, 391 },
{ 400, 400 },
{ 402, 402 },
{ 412, 412 },
{ 431, 431 },
{ 447, 447 },
{ 453, 453 },
{ 469, 469 },
{ static_cast<uint16>(0xFFFF), static_cast<uint16>(0xFFFF) },
};
// JapanesePunctuations "記号,(句点|読点)"
const ::mozc::POSMatcher::Range kRangeTable_JapanesePunctuations[] = {
{ 2705, 2705 },
{ 2708, 2708 },
{ static_cast<uint16>(0xFFFF), static_cast<uint16>(0xFFFF) },
};
// OpenBracket "記号,括弧開"
const ::mozc::POSMatcher::Range kRangeTable_OpenBracket[] = {
{ 2707, 2707 },
{ static_cast<uint16>(0xFFFF), static_cast<uint16>(0xFFFF) },
};
// CloseBracket "記号,括弧閉"
const ::mozc::POSMatcher::Range kRangeTable_CloseBracket[] = {
{ 2706, 2706 },
{ static_cast<uint16>(0xFFFF), static_cast<uint16>(0xFFFF) },
};
// GeneralSymbol "記号,一般,"
const ::mozc::POSMatcher::Range kRangeTable_GeneralSymbol[] = {
{ 2704, 2704 },
{ static_cast<uint16>(0xFFFF), static_cast<uint16>(0xFFFF) },
};
// Zipcode "特殊,郵便番号"
const ::mozc::POSMatcher::Range kRangeTable_Zipcode[] = {
{ 2722, 2722 },
{ static_cast<uint16>(0xFFFF), static_cast<uint16>(0xFFFF) },
};
// IsolatedWord "特殊,短縮よみ"
const ::mozc::POSMatcher::Range kRangeTable_IsolatedWord[] = {
{ 2723, 2723 },
{ static_cast<uint16>(0xFFFF), static_cast<uint16>(0xFFFF) },
};
// SuggestOnlyWord "特殊,サジェストのみ"
const ::mozc::POSMatcher::Range kRangeTable_SuggestOnlyWord[] = {
{ 2724, 2724 },
{ static_cast<uint16>(0xFFFF), static_cast<uint16>(0xFFFF) },
};
// ContentWordWithConjugation "^(動詞,自立,*,*,五段|動詞,自立,*,*,一段|形容詞,自立)"
const ::mozc::POSMatcher::Range kRangeTable_ContentWordWithConjugation[] = {
{ 719, 1040 },
{ 2285, 2553 },
{ static_cast<uint16>(0xFFFF), static_cast<uint16>(0xFFFF) },
};
// SuffixWord "^(助詞|助動詞|動詞,非自立|動詞,接尾|形容詞,非自立|形容詞,接尾|動詞,自立,*,*,サ変・スル)"
const ::mozc::POSMatcher::Range kRangeTable_SuffixWord[] = {
{ 42, 603 },
{ 700, 712 },
{ 1083, 1933 },
{ 2198, 2284 },
{ 2554, 2666 },
{ static_cast<uint16>(0xFFFF), static_cast<uint16>(0xFFFF) },
};
// CounterSuffixWord "名詞,接尾,助数詞"
const ::mozc::POSMatcher::Range kRangeTable_CounterSuffixWord[] = {
{ 2028, 2028 },
{ static_cast<uint16>(0xFFFF), static_cast<uint16>(0xFFFF) },
};
// UniqueNoun "^名詞,固有名詞"
const ::mozc::POSMatcher::Range kRangeTable_UniqueNoun[] = {
{ 2007, 2016 },
{ static_cast<uint16>(0xFFFF), static_cast<uint16>(0xFFFF) },
};
// GeneralNoun "^名詞,一般,*,*,*,*,*$"
const ::mozc::POSMatcher::Range kRangeTable_GeneralNoun[] = {
{ 1939, 1939 },
{ static_cast<uint16>(0xFFFF), static_cast<uint16>(0xFFFF) },
};
// ContentNoun "^名詞,(一般|固有名詞|副詞可能|サ変接続),"
const ::mozc::POSMatcher::Range kRangeTable_ContentNoun[] = {
{ 1934, 1937 },
{ 1939, 1986 },
{ 1996, 2005 },
{ 2007, 2016 },
{ static_cast<uint16>(0xFFFF), static_cast<uint16>(0xFFFF) },
};
// NounPrefix "^接頭詞,名詞接続,"
const ::mozc::POSMatcher::Range kRangeTable_NounPrefix[] = {
{ 2671, 2700 },
{ static_cast<uint16>(0xFFFF), static_cast<uint16>(0xFFFF) },
};
// EOSSymbol "^(記号,(句点|読点|アルファベット|一般|括弧開|括弧閉))|^(名詞,数,(アラビア数字|区切り文字))"
const ::mozc::POSMatcher::Range kRangeTable_EOSSymbol[] = {
{ 2047, 2048 },
{ 2703, 2708 },
{ static_cast<uint16>(0xFFFF), static_cast<uint16>(0xFFFF) },
};
// Adverb "^副詞,"
const ::mozc::POSMatcher::Range kRangeTable_Adverb[] = {
{ 12, 41 },
{ static_cast<uint16>(0xFFFF), static_cast<uint16>(0xFFFF) },
};
// AdverbSegmentSuffix "^助詞,*,*,*,*,*,(から|で|と|に|にて|の|へ|を)$"
const ::mozc::POSMatcher::Range kRangeTable_AdverbSegmentSuffix[] = {
{ 287, 287 },
{ 342, 343 },
{ 346, 346 },
{ 362, 363 },
{ 380, 381 },
{ 383, 388 },
{ 392, 392 },
{ 400, 400 },
{ 402, 402 },
{ 412, 412 },
{ 431, 431 },
{ 447, 447 },
{ 469, 469 },
{ static_cast<uint16>(0xFFFF), static_cast<uint16>(0xFFFF) },
};
// ParallelMarker "^助詞,並立助詞"
const ::mozc::POSMatcher::Range kRangeTable_ParallelMarker[] = {
{ 284, 292 },
{ static_cast<uint16>(0xFFFF), static_cast<uint16>(0xFFFF) },
};
// MasuSuffix "助動詞,*,*,*,特殊・(マス|タイ)"
const ::mozc::POSMatcher::Range kRangeTable_MasuSuffix[] = {
{ 165, 180 },
{ 237, 280 },
{ static_cast<uint16>(0xFFFF), static_cast<uint16>(0xFFFF) },
};
// TeSuffix "(助詞,接続助詞,*,*,*,*,て|助動詞,*,*,*,特殊・タ,|動詞,非自立,*,*,一段,*,てる|動詞,非自立,*,*,五段・ワ行促音便,*,ちゃう)"
const ::mozc::POSMatcher::Range kRangeTable_TeSuffix[] = {
{ 159, 164 },
{ 361, 361 },
{ 1117, 1117 },
{ 1148, 1148 },
{ 1179, 1179 },
{ 1210, 1210 },
{ 1241, 1241 },
{ 1272, 1272 },
{ 1303, 1303 },
{ 1334, 1334 },
{ 1364, 1364 },
{ 1857, 1857 },
{ 1867, 1867 },
{ 1878, 1878 },
{ 1890, 1890 },
{ 1901, 1901 },
{ 1912, 1912 },
{ 1924, 1924 },
{ static_cast<uint16>(0xFFFF), static_cast<uint16>(0xFFFF) },
};
// KagyoTaConnectionVerb "^動詞,(非自立|自立),*,*,五段・カ行(促音便|イ音便),連用タ接続"
const ::mozc::POSMatcher::Range kRangeTable_KagyoTaConnectionVerb[] = {
{ 869, 869 },
{ 1448, 1456 },
{ 1497, 1501 },
{ static_cast<uint16>(0xFFFF), static_cast<uint16>(0xFFFF) },
};
// WagyoRenyoConnectionVerb "^動詞,(非自立|自立),*,*,五段・ワ行促音便,連用形"
const ::mozc::POSMatcher::Range kRangeTable_WagyoRenyoConnectionVerb[] = {
{ 936, 939 },
{ 1918, 1928 },
{ static_cast<uint16>(0xFFFF), static_cast<uint16>(0xFFFF) },
};
} // namespace
const ::mozc::POSMatcher::Range *const kRangeTables[30] = {
kRangeTable_Functional,
kRangeTable_Unknown,
kRangeTable_FirstName,
kRangeTable_LastName,
kRangeTable_Number,
kRangeTable_KanjiNumber,
kRangeTable_WeakCompoundPrefix,
kRangeTable_AcceptableParticleAtBeginOfSegment,
kRangeTable_JapanesePunctuations,
kRangeTable_OpenBracket,
kRangeTable_CloseBracket,
kRangeTable_GeneralSymbol,
kRangeTable_Zipcode,
kRangeTable_IsolatedWord,
kRangeTable_SuggestOnlyWord,
kRangeTable_ContentWordWithConjugation,
kRangeTable_SuffixWord,
kRangeTable_CounterSuffixWord,
kRangeTable_UniqueNoun,
kRangeTable_GeneralNoun,
kRangeTable_ContentNoun,
kRangeTable_NounPrefix,
kRangeTable_EOSSymbol,
kRangeTable_Adverb,
kRangeTable_AdverbSegmentSuffix,
kRangeTable_ParallelMarker,
kRangeTable_MasuSuffix,
kRangeTable_TeSuffix,
kRangeTable_KagyoTaConnectionVerb,
kRangeTable_WagyoRenyoConnectionVerb,
};
| Java |
/**
* <pre>
* Project: cargo-itest Created on: 26 nov. 2014 File: fCommonDBConfiguration.java
* Package: nl.tranquilizedquality.itest.configuration
*
* Copyright (c) 2014 Tranquilized Quality www.tr-quality.com All rights
* reserved.
*
* This software is the confidential and proprietary information of Dizizid
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the license
* agreement you entered into with Tranquilized Quality.
* </pre>
*/
package nl.tranquilizedquality.itest.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.SingleConnectionDataSource;
/**
* @author Salomo Petrus (salomo.petrus@tr-quality.com)
* @since 26 nov. 2014
*
*/
@Configuration
public class CommonDBConfiguration extends DatasourceConfiguration {
@Bean(name = "transactionManager")
public DataSourceTransactionManager dataSourceTransactionManager(final SingleConnectionDataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}
| Java |
/*
* 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.glaf.j2cache;
public class CacheException extends RuntimeException {
private static final long serialVersionUID = 1L;
public CacheException(String s) {
super(s);
}
public CacheException(String s, Throwable e) {
super(s, e);
}
public CacheException(Throwable e) {
super(e);
}
}
| Java |
/*
* 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.facebook.presto.tpch;
import com.facebook.presto.spi.Index;
import com.facebook.presto.spi.RecordSet;
import com.google.common.base.Function;
import static com.facebook.presto.tpch.TpchIndexedData.IndexedTable;
import static com.google.common.base.Preconditions.checkNotNull;
public class TpchIndex
implements Index
{
private final Function<RecordSet, RecordSet> keyFormatter;
private final Function<RecordSet, RecordSet> outputFormatter;
private final IndexedTable indexedTable;
public TpchIndex(Function<RecordSet, RecordSet> keyFormatter, Function<RecordSet, RecordSet> outputFormatter, IndexedTable indexedTable)
{
this.keyFormatter = checkNotNull(keyFormatter, "keyFormatter is null");
this.outputFormatter = checkNotNull(outputFormatter, "outputFormatter is null");
this.indexedTable = checkNotNull(indexedTable, "indexedTable is null");
}
@Override
public RecordSet lookup(RecordSet rawInputRecordSet)
{
// convert the input record set from the column ordering in the query to
// match the column ordering of the index
RecordSet inputRecordSet = keyFormatter.apply(rawInputRecordSet);
// lookup the values in the index
RecordSet rawOutputRecordSet = indexedTable.lookupKeys(inputRecordSet);
// convert the output record set of the index into the column ordering
// expect by the query
return outputFormatter.apply(rawOutputRecordSet);
}
}
| Java |
/*
* Copyright 2018-present Open Networking 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.onosproject.net.pi.impl;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.testing.EqualsTester;
import org.junit.Test;
import org.onosproject.TestApplicationId;
import org.onosproject.core.ApplicationId;
import org.onosproject.core.GroupId;
import org.onosproject.net.DeviceId;
import org.onosproject.net.PortNumber;
import org.onosproject.net.flow.DefaultTrafficTreatment;
import org.onosproject.net.flow.TrafficTreatment;
import org.onosproject.net.group.DefaultGroup;
import org.onosproject.net.group.DefaultGroupBucket;
import org.onosproject.net.group.DefaultGroupDescription;
import org.onosproject.net.group.Group;
import org.onosproject.net.group.GroupBucket;
import org.onosproject.net.group.GroupBuckets;
import org.onosproject.net.group.GroupDescription;
import org.onosproject.net.pi.runtime.PiGroupKey;
import org.onosproject.net.pi.runtime.PiMulticastGroupEntry;
import org.onosproject.net.pi.runtime.PiPreReplica;
import java.util.List;
import java.util.Set;
import static org.onosproject.net.group.GroupDescription.Type.ALL;
import static org.onosproject.pipelines.basic.BasicConstants.INGRESS_WCMP_CONTROL_WCMP_SELECTOR;
import static org.onosproject.pipelines.basic.BasicConstants.INGRESS_WCMP_CONTROL_WCMP_TABLE;
/**
* Test for {@link PiMulticastGroupTranslatorImpl}.
*/
public class PiMulticastGroupTranslatorImplTest {
private static final DeviceId DEVICE_ID = DeviceId.deviceId("device:dummy:1");
private static final ApplicationId APP_ID = TestApplicationId.create("dummy");
private static final GroupId GROUP_ID = GroupId.valueOf(1);
private static final PiGroupKey GROUP_KEY = new PiGroupKey(
INGRESS_WCMP_CONTROL_WCMP_TABLE, INGRESS_WCMP_CONTROL_WCMP_SELECTOR, GROUP_ID.id());
private static final List<GroupBucket> BUCKET_LIST = ImmutableList.of(
allOutputBucket(1),
allOutputBucket(2),
allOutputBucket(3));
private static final List<GroupBucket> BUCKET_LIST_2 = ImmutableList.of(
allOutputBucket(1),
allOutputBucket(2),
allOutputBucket(2),
allOutputBucket(3),
allOutputBucket(3));
private static final Set<PiPreReplica> REPLICAS = ImmutableSet.of(
new PiPreReplica(PortNumber.portNumber(1), 1),
new PiPreReplica(PortNumber.portNumber(2), 1),
new PiPreReplica(PortNumber.portNumber(3), 1));
private static final Set<PiPreReplica> REPLICAS_2 = ImmutableSet.of(
new PiPreReplica(PortNumber.portNumber(1), 1),
new PiPreReplica(PortNumber.portNumber(2), 1),
new PiPreReplica(PortNumber.portNumber(2), 2),
new PiPreReplica(PortNumber.portNumber(3), 1),
new PiPreReplica(PortNumber.portNumber(3), 2));
private static final PiMulticastGroupEntry PI_MULTICAST_GROUP =
PiMulticastGroupEntry.builder()
.withGroupId(GROUP_ID.id())
.addReplicas(REPLICAS)
.build();
private static final PiMulticastGroupEntry PI_MULTICAST_GROUP_2 =
PiMulticastGroupEntry.builder()
.withGroupId(GROUP_ID.id())
.addReplicas(REPLICAS_2)
.build();
private static final GroupBuckets BUCKETS = new GroupBuckets(BUCKET_LIST);
private static final GroupBuckets BUCKETS_2 = new GroupBuckets(BUCKET_LIST_2);
private static final GroupDescription ALL_GROUP_DESC = new DefaultGroupDescription(
DEVICE_ID, ALL, BUCKETS, GROUP_KEY, GROUP_ID.id(), APP_ID);
private static final Group ALL_GROUP = new DefaultGroup(GROUP_ID, ALL_GROUP_DESC);
private static final GroupDescription ALL_GROUP_DESC_2 = new DefaultGroupDescription(
DEVICE_ID, ALL, BUCKETS_2, GROUP_KEY, GROUP_ID.id(), APP_ID);
private static final Group ALL_GROUP_2 = new DefaultGroup(GROUP_ID, ALL_GROUP_DESC_2);
private static GroupBucket allOutputBucket(int portNum) {
TrafficTreatment treatment = DefaultTrafficTreatment.builder()
.setOutput(PortNumber.portNumber(portNum))
.build();
return DefaultGroupBucket.createAllGroupBucket(treatment);
}
@Test
public void testTranslatePreGroups() throws Exception {
PiMulticastGroupEntry multicastGroup = PiMulticastGroupTranslatorImpl
.translate(ALL_GROUP, null, null);
PiMulticastGroupEntry multicastGroup2 = PiMulticastGroupTranslatorImpl
.translate(ALL_GROUP_2, null, null);
new EqualsTester()
.addEqualityGroup(multicastGroup, PI_MULTICAST_GROUP)
.addEqualityGroup(multicastGroup2, PI_MULTICAST_GROUP_2)
.testEquals();
}
}
| Java |
package models;
/**
* This class is for boxing the response sent back to slack by the bot.
* @author sabinapokhrel
*/
public class ResponseToClient {
public String status; // Status of the response sent back to slack. It can be either success or fail.
public String message; // The message sent back to the slack by the bot.\
public ResponseToClient(String status, String message) {
this.status = status;
this.message = message;
}
}
| Java |
#region Apache License Version 2.0
/*----------------------------------------------------------------
Copyright 2021 Jeffrey Su & Suzhou Senparc Network Technology Co.,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.
Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md
----------------------------------------------------------------*/
#endregion Apache License Version 2.0
/*----------------------------------------------------------------
Copyright (C) 2021 Senparc
文件名:RequestMessageEvent_GiftCard_Pay_Done.cs
文件功能描述:用户购买礼品卡付款成功
创建标识:Senparc - 20180906
----------------------------------------------------------------*/
namespace Senparc.Weixin.MP.Entities
{
/// <summary>
/// 用户购买礼品卡付款成功
/// </summary>
public class RequestMessageEvent_GiftCard_Pay_Done : RequestMessageEventBase, IRequestMessageEventBase
{
/// <summary>
/// 事件:用户购买礼品卡付款成功
/// </summary>
public override Event Event
{
get { return Event.giftcard_pay_done; }
}
/// <summary>
/// 货架的id
/// </summary>
public string PageId { get; set; }
/// <summary>
/// 订单号
/// </summary>
public string OrderId { get; set; }
}
}
| Java |
---
layout: v2_fluid/docs_base
category: platform
id: Network
title: Network | Ionic Native Plugins
header_title: Network
header_sub_title: Access network information
---
<h1 class="title">Network</h1>
<a class="improve-docs" href='https://github.com/driftyco/ionic-site/edit/ionic2/docs/v2/platform/network/index.md'>
Improve this doc
</a>
### Install the plugin
```bash
$ ionic plugin add cordova-plugin-network-information
```
```javascript
import {Network, Events} from 'ionic/ionic'
class MyPage {
constructor(events: Events) {
var isOnline = Network.isOnline();
// Respond to online/offline changes
events.subscribe('app:offline', () => {
// App is offline
})
events.subscribe('app:online', () => {
// App is online
})
}
}
```
| Java |
package com.sequenceiq.redbeams.converter.stack;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.security.cert.X509Certificate;
import java.time.Instant;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.Answers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.springframework.test.util.ReflectionTestUtils;
import com.sequenceiq.cloudbreak.api.endpoint.v4.common.DatabaseVendor;
import com.sequenceiq.cloudbreak.auth.CrnUser;
import com.sequenceiq.cloudbreak.auth.altus.EntitlementService;
import com.sequenceiq.cloudbreak.auth.crn.Crn;
import com.sequenceiq.cloudbreak.auth.crn.CrnTestUtil;
import com.sequenceiq.cloudbreak.auth.security.CrnUserDetailsService;
import com.sequenceiq.cloudbreak.cloud.model.CloudSubnet;
import com.sequenceiq.cloudbreak.cloud.model.StackTags;
import com.sequenceiq.cloudbreak.common.exception.BadRequestException;
import com.sequenceiq.cloudbreak.common.mappable.CloudPlatform;
import com.sequenceiq.cloudbreak.common.mappable.MappableBase;
import com.sequenceiq.cloudbreak.common.mappable.ProviderParameterCalculator;
import com.sequenceiq.cloudbreak.common.mappable.ProviderParametersBase;
import com.sequenceiq.cloudbreak.common.service.Clock;
import com.sequenceiq.cloudbreak.tag.CostTagging;
import com.sequenceiq.environment.api.v1.environment.model.response.DetailedEnvironmentResponse;
import com.sequenceiq.environment.api.v1.environment.model.response.EnvironmentNetworkResponse;
import com.sequenceiq.environment.api.v1.environment.model.response.LocationResponse;
import com.sequenceiq.environment.api.v1.environment.model.response.SecurityAccessResponse;
import com.sequenceiq.environment.api.v1.environment.model.response.TagResponse;
import com.sequenceiq.redbeams.api.endpoint.v4.databaseserver.requests.AllocateDatabaseServerV4Request;
import com.sequenceiq.redbeams.api.endpoint.v4.databaseserver.requests.SslConfigV4Request;
import com.sequenceiq.redbeams.api.endpoint.v4.databaseserver.requests.SslMode;
import com.sequenceiq.redbeams.api.endpoint.v4.databaseserver.responses.SslCertificateType;
import com.sequenceiq.redbeams.api.endpoint.v4.stacks.DatabaseServerV4StackRequest;
import com.sequenceiq.redbeams.api.endpoint.v4.stacks.NetworkV4StackRequest;
import com.sequenceiq.redbeams.api.endpoint.v4.stacks.SecurityGroupV4StackRequest;
import com.sequenceiq.redbeams.api.endpoint.v4.stacks.aws.AwsNetworkV4Parameters;
import com.sequenceiq.redbeams.api.model.common.DetailedDBStackStatus;
import com.sequenceiq.redbeams.api.model.common.Status;
import com.sequenceiq.redbeams.configuration.DatabaseServerSslCertificateConfig;
import com.sequenceiq.redbeams.configuration.SslCertificateEntry;
import com.sequenceiq.redbeams.domain.stack.DBStack;
import com.sequenceiq.redbeams.domain.stack.SslConfig;
import com.sequenceiq.redbeams.service.AccountTagService;
import com.sequenceiq.redbeams.service.EnvironmentService;
import com.sequenceiq.redbeams.service.PasswordGeneratorService;
import com.sequenceiq.redbeams.service.UserGeneratorService;
import com.sequenceiq.redbeams.service.UuidGeneratorService;
import com.sequenceiq.redbeams.service.crn.CrnService;
import com.sequenceiq.redbeams.service.network.NetworkParameterAdder;
import com.sequenceiq.redbeams.service.network.SubnetChooserService;
import com.sequenceiq.redbeams.service.network.SubnetListerService;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class AllocateDatabaseServerV4RequestToDBStackConverterTest {
private static final String OWNER_CRN = "crn:cdp:iam:us-west-1:cloudera:user:external/bob@cloudera.com";
private static final String ENVIRONMENT_CRN = "myenv";
private static final String CLUSTER_CRN = "crn:cdp:datahub:us-west-1:cloudera:stack:id";
private static final String ENVIRONMENT_NAME = "myenv-amazing-env";
private static final Instant NOW = Instant.now();
private static final Map<String, Object> ALLOCATE_REQUEST_PARAMETERS = Map.of("key", "value");
private static final Map<String, Object> SUBNET_ID_REQUEST_PARAMETERS = Map.of("netkey", "netvalue");
private static final String PASSWORD = "password";
private static final String USERNAME = "username";
private static final String DEFAULT_SECURITY_GROUP_ID = "defaultSecurityGroupId";
private static final String UNKNOWN_CLOUD_PLATFORM = "UnknownCloudPlatform";
private static final String USER_EMAIL = "userEmail";
private static final CloudPlatform AWS_CLOUD_PLATFORM = CloudPlatform.AWS;
private static final CloudPlatform AZURE_CLOUD_PLATFORM = CloudPlatform.AZURE;
private static final String CLOUD_PROVIDER_IDENTIFIER_V2 = "cert-id-2";
private static final String CLOUD_PROVIDER_IDENTIFIER_V3 = "cert-id-3";
private static final String CERT_PEM_V2 = "super-cert-2";
private static final String CERT_PEM_V3 = "super-cert-3";
private static final String REGION = "myRegion";
private static final String DATABASE_VENDOR = "postgres";
private static final String REDBEAMS_DB_MAJOR_VERSION = "10";
private static final String FIELD_DB_SERVICE_SUPPORTED_PLATFORMS = "dbServiceSupportedPlatforms";
private static final String FIELD_REDBEAMS_DB_MAJOR_VERSION = "redbeamsDbMajorVersion";
private static final String FIELD_SSL_ENABLED = "sslEnabled";
private static final int MAX_VERSION = 3;
private static final int VERSION_1 = 1;
private static final int VERSION_2 = 2;
private static final int VERSION_3 = 3;
private static final int NO_CERTS = 0;
private static final int SINGLE_CERT = 1;
private static final int TWO_CERTS = 2;
private static final int THREE_CERTS = 3;
@Mock
private EnvironmentService environmentService;
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private ProviderParameterCalculator providerParameterCalculator;
@Mock
private Clock clock;
@Mock
private SubnetListerService subnetListerService;
@Mock
private SubnetChooserService subnetChooserService;
@Mock
private UserGeneratorService userGeneratorService;
@Mock
private PasswordGeneratorService passwordGeneratorService;
@Mock
private NetworkParameterAdder networkParameterAdder;
@Mock
private UuidGeneratorService uuidGeneratorService;
@Mock
private CrnUserDetailsService crnUserDetailsService;
@Mock
private CostTagging costTagging;
@Mock
private CrnService crnService;
@Mock
private EntitlementService entitlementService;
@Mock
private AccountTagService accountTagService;
@Mock
private DatabaseServerSslCertificateConfig databaseServerSslCertificateConfig;
@Mock
private X509Certificate x509Certificate;
@InjectMocks
private AllocateDatabaseServerV4RequestToDBStackConverter underTest;
private AllocateDatabaseServerV4Request allocateRequest;
private NetworkV4StackRequest networkRequest;
private DatabaseServerV4StackRequest databaseServerRequest;
private SecurityGroupV4StackRequest securityGroupRequest;
private SslCertificateEntry sslCertificateEntryV2;
private SslCertificateEntry sslCertificateEntryV3;
@BeforeEach
public void setUp() {
ReflectionTestUtils.setField(underTest, FIELD_DB_SERVICE_SUPPORTED_PLATFORMS, Set.of("AWS", "AZURE"));
ReflectionTestUtils.setField(underTest, FIELD_REDBEAMS_DB_MAJOR_VERSION, REDBEAMS_DB_MAJOR_VERSION);
ReflectionTestUtils.setField(underTest, FIELD_SSL_ENABLED, true);
allocateRequest = new AllocateDatabaseServerV4Request();
networkRequest = new NetworkV4StackRequest();
allocateRequest.setNetwork(networkRequest);
databaseServerRequest = new DatabaseServerV4StackRequest();
allocateRequest.setDatabaseServer(databaseServerRequest);
securityGroupRequest = new SecurityGroupV4StackRequest();
databaseServerRequest.setSecurityGroup(securityGroupRequest);
when(crnUserDetailsService.loadUserByUsername(OWNER_CRN)).thenReturn(getCrnUser());
when(uuidGeneratorService.randomUuid()).thenReturn("uuid");
when(accountTagService.list()).thenReturn(new HashMap<>());
when(uuidGeneratorService.uuidVariableParts(anyInt())).thenReturn("parts");
when(entitlementService.internalTenant(anyString())).thenReturn(true);
sslCertificateEntryV2 = new SslCertificateEntry(VERSION_2, CLOUD_PROVIDER_IDENTIFIER_V2, CERT_PEM_V2, x509Certificate);
sslCertificateEntryV3 = new SslCertificateEntry(VERSION_3, CLOUD_PROVIDER_IDENTIFIER_V3, CERT_PEM_V3, x509Certificate);
when(databaseServerSslCertificateConfig.getMaxVersionByCloudPlatformAndRegion(anyString(), eq(REGION))).thenReturn(MAX_VERSION);
when(clock.getCurrentInstant()).thenReturn(NOW);
when(crnService.createCrn(any(DBStack.class))).thenReturn(CrnTestUtil.getDatabaseServerCrnBuilder()
.setAccountId("accountid")
.setResource("1")
.build());
}
@Test
void conversionTestWhenOptionalElementsAreProvided() throws IOException {
setupAllocateRequest(true);
when(databaseServerSslCertificateConfig.getNumberOfCertsByCloudPlatformAndRegion(AWS_CLOUD_PLATFORM.name(), REGION)).thenReturn(SINGLE_CERT);
when(databaseServerSslCertificateConfig.getCertByCloudPlatformAndRegionAndVersion(AWS_CLOUD_PLATFORM.name(), REGION, VERSION_3))
.thenReturn(sslCertificateEntryV3);
DetailedEnvironmentResponse environment = DetailedEnvironmentResponse.builder()
.withCloudPlatform(AWS_CLOUD_PLATFORM.name())
.withCrn(ENVIRONMENT_CRN)
.withLocation(LocationResponse.LocationResponseBuilder.aLocationResponse().withName(REGION).build())
.withName(ENVIRONMENT_NAME)
.withTag(new TagResponse())
.build();
when(environmentService.getByCrn(ENVIRONMENT_CRN)).thenReturn(environment);
DBStack dbStack = underTest.convert(allocateRequest, OWNER_CRN);
assertEquals(allocateRequest.getName(), dbStack.getName());
assertEquals(allocateRequest.getEnvironmentCrn(), dbStack.getEnvironmentId());
assertEquals(REGION, dbStack.getRegion());
assertEquals(AWS_CLOUD_PLATFORM.name(), dbStack.getCloudPlatform());
assertEquals(AWS_CLOUD_PLATFORM.name(), dbStack.getPlatformVariant());
assertEquals(1, dbStack.getParameters().size());
assertEquals("value", dbStack.getParameters().get("key"));
assertEquals(Crn.safeFromString(OWNER_CRN), dbStack.getOwnerCrn());
assertEquals(USER_EMAIL, dbStack.getUserName());
assertEquals(Status.REQUESTED, dbStack.getStatus());
assertEquals(DetailedDBStackStatus.PROVISION_REQUESTED, dbStack.getDbStackStatus().getDetailedDBStackStatus());
assertEquals(NOW.toEpochMilli(), dbStack.getDbStackStatus().getCreated().longValue());
assertEquals("n-uuid", dbStack.getNetwork().getName());
assertEquals(1, dbStack.getNetwork().getAttributes().getMap().size());
assertEquals("netvalue", dbStack.getNetwork().getAttributes().getMap().get("netkey"));
assertEquals("dbsvr-uuid", dbStack.getDatabaseServer().getName());
assertEquals(databaseServerRequest.getInstanceType(), dbStack.getDatabaseServer().getInstanceType());
assertEquals(DatabaseVendor.fromValue(databaseServerRequest.getDatabaseVendor()), dbStack.getDatabaseServer().getDatabaseVendor());
assertEquals("org.postgresql.Driver", dbStack.getDatabaseServer().getConnectionDriver());
assertEquals(databaseServerRequest.getStorageSize(), dbStack.getDatabaseServer().getStorageSize());
assertEquals(databaseServerRequest.getRootUserName(), dbStack.getDatabaseServer().getRootUserName());
assertEquals(databaseServerRequest.getRootUserPassword(), dbStack.getDatabaseServer().getRootPassword());
assertEquals(2, dbStack.getDatabaseServer().getAttributes().getMap().size());
assertEquals("dbvalue", dbStack.getDatabaseServer().getAttributes().getMap().get("dbkey"));
assertEquals(REDBEAMS_DB_MAJOR_VERSION, dbStack.getDatabaseServer().getAttributes().getMap().get("engineVersion"));
assertEquals(securityGroupRequest.getSecurityGroupIds(), dbStack.getDatabaseServer().getSecurityGroup().getSecurityGroupIds());
assertEquals(dbStack.getTags().get(StackTags.class).getUserDefinedTags().get("DistroXKey1"), "DistroXValue1");
verifySsl(dbStack, Set.of(CERT_PEM_V3), CLOUD_PROVIDER_IDENTIFIER_V3);
verify(databaseServerSslCertificateConfig, never()).getCertsByCloudPlatformAndRegionAndVersions(anyString(), anyString(), any());
verify(providerParameterCalculator).get(allocateRequest);
verify(providerParameterCalculator).get(networkRequest);
verify(subnetListerService, never()).listSubnets(any(), any());
verify(subnetChooserService, never()).chooseSubnets(anyList(), any(), any());
verify(networkParameterAdder, never()).addSubnetIds(any(), any(), any(), any());
verify(userGeneratorService, never()).generateUserName();
verify(passwordGeneratorService, never()).generatePassword(any());
}
private CrnUser getCrnUser() {
return new CrnUser("", "", "", USER_EMAIL, "", "");
}
@Test
void conversionTestWhenOptionalElementsGenerated() throws IOException {
setupAllocateRequest(false);
when(databaseServerSslCertificateConfig.getNumberOfCertsByCloudPlatformAndRegion(AWS_CLOUD_PLATFORM.name(), REGION)).thenReturn(SINGLE_CERT);
when(databaseServerSslCertificateConfig.getCertByCloudPlatformAndRegionAndVersion(AWS_CLOUD_PLATFORM.name(), REGION, VERSION_3))
.thenReturn(sslCertificateEntryV3);
List<CloudSubnet> cloudSubnets = List.of(
new CloudSubnet("subnet-1", "", "az-a", ""),
new CloudSubnet("subnet-2", "", "az-b", "")
);
DetailedEnvironmentResponse environment = DetailedEnvironmentResponse.builder()
.withCloudPlatform(AWS_CLOUD_PLATFORM.name())
.withName(ENVIRONMENT_NAME)
.withCrn(ENVIRONMENT_CRN)
.withTag(new TagResponse())
.withLocation(LocationResponse.LocationResponseBuilder.aLocationResponse().withName(REGION).build())
.withSecurityAccess(SecurityAccessResponse.builder().withDefaultSecurityGroupId(DEFAULT_SECURITY_GROUP_ID).build())
.withNetwork(EnvironmentNetworkResponse.builder()
.withSubnetMetas(
Map.of(
"subnet-1", cloudSubnets.get(0),
"subnet-2", cloudSubnets.get(1)
)
)
.build())
.build();
when(environmentService.getByCrn(ENVIRONMENT_CRN)).thenReturn(environment);
when(subnetListerService.listSubnets(any(), any())).thenReturn(cloudSubnets);
when(subnetChooserService.chooseSubnets(any(), any(), any())).thenReturn(cloudSubnets);
when(networkParameterAdder.addSubnetIds(any(), any(), any(), any())).thenReturn(SUBNET_ID_REQUEST_PARAMETERS);
when(userGeneratorService.generateUserName()).thenReturn(USERNAME);
when(passwordGeneratorService.generatePassword(any())).thenReturn(PASSWORD);
DBStack dbStack = underTest.convert(allocateRequest, OWNER_CRN);
assertEquals(ENVIRONMENT_NAME + "-dbstck-parts", dbStack.getName());
assertEquals(PASSWORD, dbStack.getDatabaseServer().getRootPassword());
assertEquals(USERNAME, dbStack.getDatabaseServer().getRootUserName());
assertEquals("n-uuid", dbStack.getNetwork().getName());
assertEquals(1, dbStack.getNetwork().getAttributes().getMap().size());
assertEquals("netvalue", dbStack.getNetwork().getAttributes().getMap().get("netkey"));
assertThat(dbStack.getDatabaseServer().getSecurityGroup().getSecurityGroupIds()).hasSize(1);
assertEquals(dbStack.getDatabaseServer().getSecurityGroup().getSecurityGroupIds().iterator().next(), DEFAULT_SECURITY_GROUP_ID);
assertEquals(dbStack.getTags().get(StackTags.class).getUserDefinedTags().get("DistroXKey1"), "DistroXValue1");
verifySsl(dbStack, Set.of(CERT_PEM_V3), CLOUD_PROVIDER_IDENTIFIER_V3);
verify(databaseServerSslCertificateConfig, never()).getCertsByCloudPlatformAndRegionAndVersions(anyString(), anyString(), any());
verify(providerParameterCalculator).get(allocateRequest);
verify(providerParameterCalculator, never()).get(networkRequest);
verify(subnetListerService).listSubnets(any(), any());
verify(subnetChooserService).chooseSubnets(anyList(), any(), any());
verify(networkParameterAdder).addSubnetIds(any(), any(), any(), any());
verify(userGeneratorService).generateUserName();
verify(passwordGeneratorService).generatePassword(any());
}
@Test
void conversionTestWhenRequestAndEnvironmentCloudPlatformsDiffer() {
allocateRequest.setCloudPlatform(AWS_CLOUD_PLATFORM);
allocateRequest.setTags(new HashMap<>());
allocateRequest.setEnvironmentCrn(ENVIRONMENT_CRN);
DetailedEnvironmentResponse environment = DetailedEnvironmentResponse.builder()
.withCloudPlatform(UNKNOWN_CLOUD_PLATFORM)
.build();
when(environmentService.getByCrn(ENVIRONMENT_CRN)).thenReturn(environment);
BadRequestException badRequestException = assertThrows(BadRequestException.class, () -> underTest.convert(allocateRequest, OWNER_CRN));
assertThat(badRequestException).hasMessage("Cloud platform of the request AWS and the environment " + UNKNOWN_CLOUD_PLATFORM + " do not match.");
}
@Test
void conversionTestWhenUnsupportedCloudPlatform() {
allocateRequest.setCloudPlatform(CloudPlatform.YARN);
allocateRequest.setTags(new HashMap<>());
allocateRequest.setEnvironmentCrn(ENVIRONMENT_CRN);
DetailedEnvironmentResponse environment = DetailedEnvironmentResponse.builder()
.withCloudPlatform(CloudPlatform.YARN.name())
.build();
when(environmentService.getByCrn(ENVIRONMENT_CRN)).thenReturn(environment);
BadRequestException badRequestException = assertThrows(BadRequestException.class, () -> underTest.convert(allocateRequest, OWNER_CRN));
assertThat(badRequestException).hasMessage("Cloud platform YARN not supported yet.");
}
static Object[][] conversionTestWhenSslDisabledDataProvider() {
return new Object[][]{
// testCaseName fieldSslEnabled sslConfigV4Request
{"false, null", false, null},
{"true, null", true, null},
{"false, request with sslMode=null", false, new SslConfigV4Request()},
{"true, request with sslMode=null", true, new SslConfigV4Request()},
{"false, request with sslMode=DISABLED", false, createSslConfigV4Request(SslMode.DISABLED)},
{"true, request with sslMode=DISABLED", true, createSslConfigV4Request(SslMode.DISABLED)},
{"false, request with sslMode=ENABLED", false, createSslConfigV4Request(SslMode.ENABLED)},
};
}
@ParameterizedTest(name = "{0}")
@MethodSource("conversionTestWhenSslDisabledDataProvider")
void conversionTestWhenSslDisabled(String testCaseName, boolean fieldSslEnabled, SslConfigV4Request sslConfigV4Request) {
setupMinimalValid(sslConfigV4Request, AWS_CLOUD_PLATFORM);
ReflectionTestUtils.setField(underTest, FIELD_SSL_ENABLED, fieldSslEnabled);
DBStack dbStack = underTest.convert(allocateRequest, OWNER_CRN);
SslConfig sslConfig = dbStack.getSslConfig();
assertThat(sslConfig).isNotNull();
Set<String> sslCertificates = sslConfig.getSslCertificates();
assertThat(sslCertificates).isNotNull();
assertThat(sslCertificates).isEmpty();
assertThat(sslConfig.getSslCertificateType()).isEqualTo(SslCertificateType.NONE);
}
private void setupMinimalValid(SslConfigV4Request sslConfigV4Request, CloudPlatform cloudPlatform) {
allocateRequest.setEnvironmentCrn(ENVIRONMENT_CRN);
allocateRequest.setTags(new HashMap<>());
allocateRequest.setClusterCrn(CLUSTER_CRN);
allocateRequest.setSslConfig(sslConfigV4Request);
DetailedEnvironmentResponse environment = DetailedEnvironmentResponse.builder()
.withCloudPlatform(cloudPlatform.name())
.withCrn(ENVIRONMENT_CRN)
.withLocation(LocationResponse.LocationResponseBuilder.aLocationResponse().withName(REGION).build())
.withName(ENVIRONMENT_NAME)
.withTag(new TagResponse())
.build();
when(environmentService.getByCrn(ENVIRONMENT_CRN)).thenReturn(environment);
databaseServerRequest.setDatabaseVendor(DATABASE_VENDOR);
}
@Test
void conversionTestWhenSslEnabledAndAwsAndNoCerts() {
setupMinimalValid(createSslConfigV4Request(SslMode.ENABLED), AWS_CLOUD_PLATFORM);
when(databaseServerSslCertificateConfig.getNumberOfCertsByCloudPlatformAndRegion(AWS_CLOUD_PLATFORM.name(), REGION)).thenReturn(NO_CERTS);
DBStack dbStack = underTest.convert(allocateRequest, OWNER_CRN);
verifySsl(dbStack, Set.of(), null);
verify(databaseServerSslCertificateConfig, never()).getCertByCloudPlatformAndRegionAndVersion(anyString(), anyString(), anyInt());
verify(databaseServerSslCertificateConfig, never()).getCertsByCloudPlatformAndRegionAndVersions(anyString(), anyString(), any());
}
@Test
void conversionTestWhenSslEnabledAndAwsAndSingleCert() {
setupMinimalValid(createSslConfigV4Request(SslMode.ENABLED), AWS_CLOUD_PLATFORM);
conversionTestWhenSslEnabledAndSingleCertReturnedInternal(AWS_CLOUD_PLATFORM.name(), SINGLE_CERT);
}
private void conversionTestWhenSslEnabledAndSingleCertReturnedInternal(String cloudPlatform, int numOfCerts) {
when(databaseServerSslCertificateConfig.getNumberOfCertsByCloudPlatformAndRegion(cloudPlatform, REGION)).thenReturn(numOfCerts);
when(databaseServerSslCertificateConfig.getCertByCloudPlatformAndRegionAndVersion(cloudPlatform, REGION, VERSION_3)).thenReturn(sslCertificateEntryV3);
DBStack dbStack = underTest.convert(allocateRequest, OWNER_CRN);
verifySsl(dbStack, Set.of(CERT_PEM_V3), CLOUD_PROVIDER_IDENTIFIER_V3);
verify(databaseServerSslCertificateConfig, never()).getCertsByCloudPlatformAndRegionAndVersions(anyString(), anyString(), any());
}
@Test
void conversionTestWhenSslEnabledAndAwsAndSingleCertErrorNullCert() {
setupMinimalValid(createSslConfigV4Request(SslMode.ENABLED), AWS_CLOUD_PLATFORM);
when(databaseServerSslCertificateConfig.getNumberOfCertsByCloudPlatformAndRegion(AWS_CLOUD_PLATFORM.name(), REGION)).thenReturn(SINGLE_CERT);
when(databaseServerSslCertificateConfig.getCertByCloudPlatformAndRegionAndVersion(AWS_CLOUD_PLATFORM.name(), REGION, VERSION_3)).thenReturn(null);
IllegalStateException illegalStateException = assertThrows(IllegalStateException.class, () -> underTest.convert(allocateRequest, OWNER_CRN));
assertThat(illegalStateException).hasMessage("Could not find SSL certificate version 3 for cloud platform \"AWS\"");
verify(databaseServerSslCertificateConfig, never()).getCertsByCloudPlatformAndRegionAndVersions(anyString(), anyString(), any());
}
@Test
void conversionTestWhenSslEnabledAndAwsAndSingleCertErrorVersionMismatch() {
setupMinimalValid(createSslConfigV4Request(SslMode.ENABLED), AWS_CLOUD_PLATFORM);
when(databaseServerSslCertificateConfig.getNumberOfCertsByCloudPlatformAndRegion(AWS_CLOUD_PLATFORM.name(), REGION)).thenReturn(SINGLE_CERT);
when(databaseServerSslCertificateConfig.getCertByCloudPlatformAndRegionAndVersion(AWS_CLOUD_PLATFORM.name(), REGION, VERSION_3))
.thenReturn(sslCertificateEntryV2);
IllegalStateException illegalStateException = assertThrows(IllegalStateException.class, () -> underTest.convert(allocateRequest, OWNER_CRN));
assertThat(illegalStateException).hasMessage("SSL certificate version mismatch for cloud platform \"AWS\": expected=3, actual=2");
verify(databaseServerSslCertificateConfig, never()).getCertsByCloudPlatformAndRegionAndVersions(anyString(), anyString(), any());
}
@Test
void conversionTestWhenSslEnabledAndAwsAndSingleCertErrorBlankCloudProviderIdentifier() {
setupMinimalValid(createSslConfigV4Request(SslMode.ENABLED), AWS_CLOUD_PLATFORM);
when(databaseServerSslCertificateConfig.getNumberOfCertsByCloudPlatformAndRegion(AWS_CLOUD_PLATFORM.name(), REGION)).thenReturn(SINGLE_CERT);
SslCertificateEntry sslCertificateEntryV3Broken = new SslCertificateEntry(VERSION_3, "", CERT_PEM_V3, x509Certificate);
when(databaseServerSslCertificateConfig.getCertByCloudPlatformAndRegionAndVersion(AWS_CLOUD_PLATFORM.name(), REGION, VERSION_3))
.thenReturn(sslCertificateEntryV3Broken);
IllegalStateException illegalStateException = assertThrows(IllegalStateException.class, () -> underTest.convert(allocateRequest, OWNER_CRN));
assertThat(illegalStateException).hasMessage("Blank CloudProviderIdentifier in SSL certificate version 3 for cloud platform \"AWS\"");
verify(databaseServerSslCertificateConfig, never()).getCertsByCloudPlatformAndRegionAndVersions(anyString(), anyString(), any());
}
@Test
void conversionTestWhenSslEnabledAndAwsAndSingleCertErrorBlankPem() {
setupMinimalValid(createSslConfigV4Request(SslMode.ENABLED), AWS_CLOUD_PLATFORM);
when(databaseServerSslCertificateConfig.getNumberOfCertsByCloudPlatformAndRegion(AWS_CLOUD_PLATFORM.name(), REGION)).thenReturn(SINGLE_CERT);
SslCertificateEntry sslCertificateEntryV3Broken = new SslCertificateEntry(VERSION_3, CLOUD_PROVIDER_IDENTIFIER_V3, "", x509Certificate);
when(databaseServerSslCertificateConfig.getCertByCloudPlatformAndRegionAndVersion(AWS_CLOUD_PLATFORM.name(), REGION, VERSION_3))
.thenReturn(sslCertificateEntryV3Broken);
IllegalStateException illegalStateException = assertThrows(IllegalStateException.class, () -> underTest.convert(allocateRequest, OWNER_CRN));
assertThat(illegalStateException).hasMessage("Blank PEM in SSL certificate version 3 for cloud platform \"AWS\"");
verify(databaseServerSslCertificateConfig, never()).getCertsByCloudPlatformAndRegionAndVersions(anyString(), anyString(), any());
}
@Test
void conversionTestWhenSslEnabledAndAzureAndSingleCert() {
setupMinimalValid(createSslConfigV4Request(SslMode.ENABLED), AZURE_CLOUD_PLATFORM);
conversionTestWhenSslEnabledAndSingleCertReturnedInternal(AZURE_CLOUD_PLATFORM.name(), SINGLE_CERT);
}
@Test
void conversionTestWhenSslEnabledAndAwsAndTwoCerts() {
setupMinimalValid(createSslConfigV4Request(SslMode.ENABLED), AWS_CLOUD_PLATFORM);
conversionTestWhenSslEnabledAndSingleCertReturnedInternal(AWS_CLOUD_PLATFORM.name(), TWO_CERTS);
}
@Test
void conversionTestWhenSslEnabledAndAwsAndThreeCerts() {
setupMinimalValid(createSslConfigV4Request(SslMode.ENABLED), AWS_CLOUD_PLATFORM);
conversionTestWhenSslEnabledAndSingleCertReturnedInternal(AWS_CLOUD_PLATFORM.name(), THREE_CERTS);
}
@Test
void conversionTestWhenSslEnabledAndAzureAndTwoCerts() {
setupMinimalValid(createSslConfigV4Request(SslMode.ENABLED), AZURE_CLOUD_PLATFORM);
conversionTestWhenSslEnabledAndTwoCertsReturnedInternal(AZURE_CLOUD_PLATFORM.name(), TWO_CERTS);
}
private void conversionTestWhenSslEnabledAndTwoCertsReturnedInternal(String cloudPlatform, int numOfCerts) {
when(databaseServerSslCertificateConfig.getNumberOfCertsByCloudPlatformAndRegion(cloudPlatform, REGION)).thenReturn(numOfCerts);
when(databaseServerSslCertificateConfig.getCertsByCloudPlatformAndRegionAndVersions(cloudPlatform, REGION, VERSION_2, VERSION_3))
.thenReturn(Set.of(sslCertificateEntryV2, sslCertificateEntryV3));
DBStack dbStack = underTest.convert(allocateRequest, OWNER_CRN);
verifySsl(dbStack, Set.of(CERT_PEM_V2, CERT_PEM_V3), CLOUD_PROVIDER_IDENTIFIER_V3);
verify(databaseServerSslCertificateConfig, never()).getCertByCloudPlatformAndRegionAndVersion(anyString(), anyString(), anyInt());
}
@Test
void conversionTestWhenSslEnabledAndAzureAndTwoCertsErrorNullCert() {
setupMinimalValid(createSslConfigV4Request(SslMode.ENABLED), AZURE_CLOUD_PLATFORM);
when(databaseServerSslCertificateConfig.getNumberOfCertsByCloudPlatformAndRegion(AZURE_CLOUD_PLATFORM.name(), REGION)).thenReturn(TWO_CERTS);
Set<SslCertificateEntry> certs = new HashSet<>();
certs.add(sslCertificateEntryV3);
certs.add(null);
when(databaseServerSslCertificateConfig.getCertsByCloudPlatformAndRegionAndVersions(AZURE_CLOUD_PLATFORM.name(), REGION, VERSION_2, VERSION_3))
.thenReturn(certs);
IllegalStateException illegalStateException = assertThrows(IllegalStateException.class, () -> underTest.convert(allocateRequest, OWNER_CRN));
assertThat(illegalStateException)
.hasMessage("Could not find SSL certificate(s) when requesting versions [2, 3] for cloud platform \"AZURE\": expected 2 certificates, got 1");
verify(databaseServerSslCertificateConfig, never()).getCertByCloudPlatformAndRegionAndVersion(anyString(), anyString(), anyInt());
}
@Test
void conversionTestWhenSslEnabledAndAzureAndTwoCertsErrorFewerCerts() {
setupMinimalValid(createSslConfigV4Request(SslMode.ENABLED), AZURE_CLOUD_PLATFORM);
when(databaseServerSslCertificateConfig.getNumberOfCertsByCloudPlatformAndRegion(AZURE_CLOUD_PLATFORM.name(), REGION)).thenReturn(TWO_CERTS);
when(databaseServerSslCertificateConfig.getCertsByCloudPlatformAndRegionAndVersions(AZURE_CLOUD_PLATFORM.name(), REGION, VERSION_2, VERSION_3))
.thenReturn(Set.of(sslCertificateEntryV3));
IllegalStateException illegalStateException = assertThrows(IllegalStateException.class, () -> underTest.convert(allocateRequest, OWNER_CRN));
assertThat(illegalStateException)
.hasMessage("Could not find SSL certificate(s) when requesting versions [2, 3] for cloud platform \"AZURE\": expected 2 certificates, got 1");
verify(databaseServerSslCertificateConfig, never()).getCertByCloudPlatformAndRegionAndVersion(anyString(), anyString(), anyInt());
}
@Test
void conversionTestWhenSslEnabledAndAzureAndTwoCertsErrorDuplicatedCertPem() {
setupMinimalValid(createSslConfigV4Request(SslMode.ENABLED), AZURE_CLOUD_PLATFORM);
SslCertificateEntry sslCertificateEntryV2DuplicateOfV3 = new SslCertificateEntry(VERSION_2, CLOUD_PROVIDER_IDENTIFIER_V3, CERT_PEM_V3, x509Certificate);
when(databaseServerSslCertificateConfig.getNumberOfCertsByCloudPlatformAndRegion(AZURE_CLOUD_PLATFORM.name(), REGION)).thenReturn(TWO_CERTS);
when(databaseServerSslCertificateConfig.getCertsByCloudPlatformAndRegionAndVersions(AZURE_CLOUD_PLATFORM.name(), REGION, VERSION_2, VERSION_3))
.thenReturn(Set.of(sslCertificateEntryV2DuplicateOfV3, sslCertificateEntryV3));
IllegalStateException illegalStateException = assertThrows(IllegalStateException.class, () -> underTest.convert(allocateRequest, OWNER_CRN));
assertThat(illegalStateException)
.hasMessage("Received duplicated SSL certificate PEM when requesting versions [2, 3] for cloud platform \"AZURE\"");
verify(databaseServerSslCertificateConfig, never()).getCertByCloudPlatformAndRegionAndVersion(anyString(), anyString(), anyInt());
}
@Test
void conversionTestWhenSslEnabledAndAzureAndTwoCertsErrorVersionMismatch() {
setupMinimalValid(createSslConfigV4Request(SslMode.ENABLED), AZURE_CLOUD_PLATFORM);
SslCertificateEntry sslCertificateEntryV2Broken = new SslCertificateEntry(VERSION_1, CLOUD_PROVIDER_IDENTIFIER_V2, CERT_PEM_V2, x509Certificate);
when(databaseServerSslCertificateConfig.getNumberOfCertsByCloudPlatformAndRegion(AZURE_CLOUD_PLATFORM.name(), REGION)).thenReturn(TWO_CERTS);
when(databaseServerSslCertificateConfig.getCertsByCloudPlatformAndRegionAndVersions(AZURE_CLOUD_PLATFORM.name(), REGION, VERSION_2, VERSION_3))
.thenReturn(Set.of(sslCertificateEntryV2Broken, sslCertificateEntryV3));
IllegalStateException illegalStateException = assertThrows(IllegalStateException.class, () -> underTest.convert(allocateRequest, OWNER_CRN));
assertThat(illegalStateException)
.hasMessage("Could not find SSL certificate version 2 for cloud platform \"AZURE\"");
verify(databaseServerSslCertificateConfig, never()).getCertByCloudPlatformAndRegionAndVersion(anyString(), anyString(), anyInt());
}
@Test
void conversionTestWhenSslEnabledAndAzureAndThreeCerts() {
setupMinimalValid(createSslConfigV4Request(SslMode.ENABLED), AZURE_CLOUD_PLATFORM);
conversionTestWhenSslEnabledAndTwoCertsReturnedInternal(AZURE_CLOUD_PLATFORM.name(), THREE_CERTS);
}
private void verifySsl(DBStack dbStack, Set<String> sslCertificatesExpected, String cloudProviderIdentifierExpected) {
SslConfig sslConfig = dbStack.getSslConfig();
assertThat(sslConfig).isNotNull();
Set<String> sslCertificates = sslConfig.getSslCertificates();
assertThat(sslCertificates).isNotNull();
assertThat(sslCertificates).isEqualTo(sslCertificatesExpected);
assertThat(sslConfig.getSslCertificateType()).isEqualTo(SslCertificateType.CLOUD_PROVIDER_OWNED);
assertThat(sslConfig.getSslCertificateActiveVersion()).isEqualTo(MAX_VERSION);
assertThat(sslConfig.getSslCertificateActiveCloudProviderIdentifier()).isEqualTo(cloudProviderIdentifierExpected);
}
private void setupAllocateRequest(boolean provideOptionalFields) {
allocateRequest.setEnvironmentCrn(ENVIRONMENT_CRN);
allocateRequest.setTags(Map.of("DistroXKey1", "DistroXValue1"));
allocateRequest.setClusterCrn(CLUSTER_CRN);
if (provideOptionalFields) {
allocateRequest.setName("myallocation");
AwsNetworkV4Parameters awsNetworkV4Parameters = new AwsNetworkV4Parameters();
awsNetworkV4Parameters.setSubnetId("subnet-1,subnet-2");
allocateRequest.getNetwork().setAws(awsNetworkV4Parameters);
setupProviderCalculatorResponse(networkRequest, SUBNET_ID_REQUEST_PARAMETERS);
} else {
allocateRequest.setNetwork(null);
allocateRequest.getDatabaseServer().setSecurityGroup(null);
}
allocateRequest.setSslConfig(createSslConfigV4Request(SslMode.ENABLED));
databaseServerRequest.setInstanceType("db.m3.medium");
databaseServerRequest.setDatabaseVendor(DATABASE_VENDOR);
databaseServerRequest.setConnectionDriver("org.postgresql.Driver");
databaseServerRequest.setStorageSize(50L);
if (provideOptionalFields) {
databaseServerRequest.setRootUserName("root");
databaseServerRequest.setRootUserPassword("cloudera");
}
setupProviderCalculatorResponse(allocateRequest, ALLOCATE_REQUEST_PARAMETERS);
setupProviderCalculatorResponse(databaseServerRequest, new HashMap<>(Map.of("dbkey", "dbvalue")));
securityGroupRequest.setSecurityGroupIds(Set.of("sg-1234"));
}
private static SslConfigV4Request createSslConfigV4Request(SslMode sslMode) {
SslConfigV4Request sslConfigV4Request = new SslConfigV4Request();
sslConfigV4Request.setSslMode(sslMode);
return sslConfigV4Request;
}
private void setupProviderCalculatorResponse(ProviderParametersBase request, Map<String, Object> response) {
MappableBase providerCalculatorResponse = mock(MappableBase.class);
when(providerCalculatorResponse.asMap()).thenReturn(response);
when(providerParameterCalculator.get(request)).thenReturn(providerCalculatorResponse);
}
}
| Java |
// snippet-sourcedescription:[ ]
// snippet-service:[dynamodb]
// snippet-keyword:[dotNET]
// snippet-keyword:[Amazon DynamoDB]
// snippet-keyword:[Code Sample]
// snippet-keyword:[ ]
// snippet-sourcetype:[full-example]
// snippet-sourcedate:[ ]
// snippet-sourceauthor:[AWS]
// snippet-start:[dynamodb.dotNET.CodeExample.UpdateItem_B]
/**
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* This file is 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/
*
* 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Amazon;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;
using Amazon.DynamoDBv2.DocumentModel;
namespace DynamoDB_intro
{
class Program
{
static void Main(string[] args)
{
// Get an AmazonDynamoDBClient for the local database
AmazonDynamoDBClient client = GetLocalClient();
if (client == null)
{
PauseForDebugWindow();
return;
}
// Create an UpdateItemRequest to modify two existing nested attributes
// and add a new one
UpdateItemRequest updateRequest = new UpdateItemRequest()
{
TableName = "Movies",
Key = new Dictionary<string, AttributeValue>
{
{ "year", new AttributeValue {
N = "2015"
} },
{ "title", new AttributeValue {
S = "The Big New Movie"
}}
},
ExpressionAttributeValues = new Dictionary<string, AttributeValue>
{
{ ":inc", new AttributeValue {
N = "1"
} }
},
UpdateExpression = "SET info.rating = info.rating + :inc",
ReturnValues = "UPDATED_NEW"
};
// Use AmazonDynamoDBClient.UpdateItem to update the specified attributes
UpdateItemResponse uir = null;
try
{
uir = client.UpdateItem(updateRequest);
}
catch (Exception ex)
{
Console.WriteLine("\nError: UpdateItem failed, because " + ex.Message);
if (uir != null)
Console.WriteLine(" Status code was: " + uir.HttpStatusCode.ToString());
PauseForDebugWindow();
return;
}
// Get the item from the table and display it to validate that the update succeeded
DisplayMovieItem(client, "2015", "The Big New Movie");
}
public static AmazonDynamoDBClient GetLocalClient()
{
// First, set up a DynamoDB client for DynamoDB Local
AmazonDynamoDBConfig ddbConfig = new AmazonDynamoDBConfig();
ddbConfig.ServiceURL = "http://localhost:8000";
AmazonDynamoDBClient client;
try
{
client = new AmazonDynamoDBClient(ddbConfig);
}
catch (Exception ex)
{
Console.WriteLine("\n Error: failed to create a DynamoDB client; " + ex.Message);
return (null);
}
return (client);
}
public static void DisplayMovieItem(AmazonDynamoDBClient client, string year, string title)
{
// Create Primitives for the HASH and RANGE portions of the primary key
Primitive hash = new Primitive(year, true);
Primitive range = new Primitive(title, false);
Table table = null;
try
{
table = Table.LoadTable(client, "Movies");
}
catch (Exception ex)
{
Console.WriteLine("\n Error: failed to load the 'Movies' table; " + ex.Message);
return;
}
Document document = table.GetItem(hash, range);
Console.WriteLine("\n The movie record looks like this: \n" + document.ToJsonPretty());
}
public static void PauseForDebugWindow()
{
// Keep the console open if in Debug mode...
Console.Write("\n\n ...Press any key to continue");
Console.ReadKey();
Console.WriteLine();
}
}
}
// snippet-end:[dynamodb.dotNET.CodeExample.UpdateItem_B] | Java |
package padroesprojeto.criacional.abstractfactorymethod.outroexemplo.model;
/**
* Created by felansu on 03/06/2015.
*/
public interface Roupa {
void vestir();
}
| Java |
/***********************************************************************
* Copyright (c) 2013-2016 Commonwealth Computer Research, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Apache License, Version 2.0
* which accompanies this distribution and is available at
* http://www.opensource.org/licenses/apache2.0.php.
*************************************************************************/
package org.locationtech.geomesa.accumulo.index
import org.geotools.data.Query
import org.geotools.geometry.jts.ReferencedEnvelope
import org.locationtech.geomesa.accumulo.AccumuloQueryPlannerType
import org.locationtech.geomesa.accumulo.data._
import org.locationtech.geomesa.accumulo.iterators._
import org.locationtech.geomesa.filter._
import org.locationtech.geomesa.index.conf.QueryHints
import org.locationtech.geomesa.index.utils.KryoLazyDensityUtils
import org.locationtech.geomesa.utils.geotools.SimpleFeatureTypes
import org.opengis.feature.simple.SimpleFeatureType
import org.opengis.filter.Filter
import org.opengis.filter.spatial.BBOX
import org.opengis.geometry.BoundingBox
/**
* Executes a query against geomesa
*/
class AccumuloQueryPlanner(ds: AccumuloDataStore) extends AccumuloQueryPlannerType(ds) {
import org.locationtech.geomesa.index.conf.QueryHints.RichHints
override protected [geomesa] def configureQuery(original: Query, sft: SimpleFeatureType): Query = {
val query = super.configureQuery(original, sft)
// add the bbox from the density query to the filter
if (query.getHints.isDensityQuery) {
val env = query.getHints.getDensityEnvelope.get.asInstanceOf[ReferencedEnvelope]
val bbox = ff.bbox(ff.property(sft.getGeometryDescriptor.getLocalName), env)
if (query.getFilter == Filter.INCLUDE) {
query.setFilter(bbox)
} else {
// add the bbox - try to not duplicate an existing bbox
def compareDbls(d1: Double, d2: Double): Boolean = math.abs(d1 - d2) < 0.0001 // our precision
def compare(b1: BoundingBox, b2: BoundingBox): Boolean = {
compareDbls(b1.getMinX, b2.getMinX) && compareDbls(b1.getMaxX, b2.getMaxX) &&
compareDbls(b1.getMinY, b2.getMinY) && compareDbls(b1.getMaxY, b2.getMaxY)
}
val filters = decomposeAnd(query.getFilter).filter {
case b: BBOX if compare(b.getBounds, bbox.getBounds) => false
case _ => true
}
query.setFilter(andFilters(filters ++ Seq(bbox)))
}
}
query
}
// This function calculates the SimpleFeatureType of the returned SFs.
override protected def setReturnSft(query: Query, baseSft: SimpleFeatureType): Unit = {
val sft = if (query.getHints.isBinQuery) {
BinAggregatingIterator.BIN_SFT
} else if (query.getHints.isDensityQuery) {
KryoLazyDensityUtils.DENSITY_SFT
} else if (query.getHints.isStatsIteratorQuery) {
KryoLazyStatsIterator.StatsSft
} else if (query.getHints.isMapAggregatingQuery) {
val spec = KryoLazyMapAggregatingIterator.createMapSft(baseSft, query.getHints.getMapAggregatingAttribute)
SimpleFeatureTypes.createType(baseSft.getTypeName, spec)
} else {
query.getHints.getTransformSchema.getOrElse(baseSft)
}
query.getHints.put(QueryHints.Internal.RETURN_SFT, sft)
sft
}
}
| Java |
/*
* 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.accumulo.core.conf;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Function;
import java.util.function.Predicate;
import org.apache.accumulo.core.conf.PropertyType.PortRange;
import org.apache.accumulo.core.spi.scan.SimpleScanDispatcher;
import org.apache.accumulo.core.util.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
/**
* A configuration object.
*/
public abstract class AccumuloConfiguration implements Iterable<Entry<String,String>> {
private static class PrefixProps {
final long updateCount;
final Map<String,String> props;
PrefixProps(Map<String,String> props, long updateCount) {
this.updateCount = updateCount;
this.props = props;
}
}
private volatile EnumMap<Property,PrefixProps> cachedPrefixProps = new EnumMap<>(Property.class);
private Lock prefixCacheUpdateLock = new ReentrantLock();
private static final Logger log = LoggerFactory.getLogger(AccumuloConfiguration.class);
/**
* Gets a property value from this configuration.
*
* <p>
* Note: this is inefficient, but convenient on occasion. For retrieving multiple properties, use
* {@link #getProperties(Map, Predicate)} with a custom filter.
*
* @param property
* property to get
* @return property value
*/
public String get(String property) {
Map<String,String> propMap = new HashMap<>(1);
getProperties(propMap, key -> Objects.equals(property, key));
return propMap.get(property);
}
/**
* Gets a property value from this configuration.
*
* @param property
* property to get
* @return property value
*/
public abstract String get(Property property);
/**
* Given a property and a deprecated property determine which one to use base on which one is set.
*/
public Property resolve(Property property, Property deprecatedProperty) {
if (isPropertySet(property, true)) {
return property;
} else if (isPropertySet(deprecatedProperty, true)) {
return deprecatedProperty;
} else {
return property;
}
}
/**
* Returns property key/value pairs in this configuration. The pairs include those defined in this
* configuration which pass the given filter, and those supplied from the parent configuration
* which are not included from here.
*
* @param props
* properties object to populate
* @param filter
* filter for accepting properties from this configuration
*/
public abstract void getProperties(Map<String,String> props, Predicate<String> filter);
/**
* Returns an iterator over property key/value pairs in this configuration. Some implementations
* may elect to omit properties.
*
* @return iterator over properties
*/
@Override
public Iterator<Entry<String,String>> iterator() {
Predicate<String> all = x -> true;
TreeMap<String,String> entries = new TreeMap<>();
getProperties(entries, all);
return entries.entrySet().iterator();
}
private static void checkType(Property property, PropertyType type) {
if (!property.getType().equals(type)) {
String msg = "Configuration method intended for type " + type + " called with a "
+ property.getType() + " argument (" + property.getKey() + ")";
IllegalArgumentException err = new IllegalArgumentException(msg);
log.error(msg, err);
throw err;
}
}
/**
* Each time configuration changes, this counter should increase. Anything that caches information
* that is derived from configuration can use this method to know when to update.
*/
public long getUpdateCount() {
return 0;
}
/**
* Gets all properties under the given prefix in this configuration.
*
* @param property
* prefix property, must be of type PropertyType.PREFIX
* @return a map of property keys to values
* @throws IllegalArgumentException
* if property is not a prefix
*/
public Map<String,String> getAllPropertiesWithPrefix(Property property) {
checkType(property, PropertyType.PREFIX);
PrefixProps prefixProps = cachedPrefixProps.get(property);
if (prefixProps == null || prefixProps.updateCount != getUpdateCount()) {
prefixCacheUpdateLock.lock();
try {
// Very important that update count is read before getting properties. Also only read it
// once.
long updateCount = getUpdateCount();
prefixProps = cachedPrefixProps.get(property);
if (prefixProps == null || prefixProps.updateCount != updateCount) {
Map<String,String> propMap = new HashMap<>();
// The reason this caching exists is to avoid repeatedly making this expensive call.
getProperties(propMap, key -> key.startsWith(property.getKey()));
propMap = Map.copyOf(propMap);
// So that locking is not needed when reading from enum map, always create a new one.
// Construct and populate map using a local var so its not visible
// until ready.
EnumMap<Property,PrefixProps> localPrefixes = new EnumMap<>(Property.class);
// carry forward any other cached prefixes
localPrefixes.putAll(cachedPrefixProps);
// put the updates
prefixProps = new PrefixProps(propMap, updateCount);
localPrefixes.put(property, prefixProps);
// make the newly constructed map available
cachedPrefixProps = localPrefixes;
}
} finally {
prefixCacheUpdateLock.unlock();
}
}
return prefixProps.props;
}
/**
* Gets a property of type {@link PropertyType#BYTES} or {@link PropertyType#MEMORY}, interpreting
* the value properly.
*
* @param property
* Property to get
* @return property value
* @throws IllegalArgumentException
* if the property is of the wrong type
*/
public long getAsBytes(Property property) {
String memString = get(property);
if (property.getType() == PropertyType.MEMORY) {
return ConfigurationTypeHelper.getMemoryAsBytes(memString);
} else if (property.getType() == PropertyType.BYTES) {
return ConfigurationTypeHelper.getFixedMemoryAsBytes(memString);
} else {
throw new IllegalArgumentException(property.getKey() + " is not of BYTES or MEMORY type");
}
}
/**
* Gets a property of type {@link PropertyType#TIMEDURATION}, interpreting the value properly.
*
* @param property
* property to get
* @return property value
* @throws IllegalArgumentException
* if the property is of the wrong type
*/
public long getTimeInMillis(Property property) {
checkType(property, PropertyType.TIMEDURATION);
return ConfigurationTypeHelper.getTimeInMillis(get(property));
}
/**
* Gets a property of type {@link PropertyType#BOOLEAN}, interpreting the value properly (using
* <code>Boolean.parseBoolean()</code>).
*
* @param property
* property to get
* @return property value
* @throws IllegalArgumentException
* if the property is of the wrong type
*/
public boolean getBoolean(Property property) {
checkType(property, PropertyType.BOOLEAN);
return Boolean.parseBoolean(get(property));
}
/**
* Gets a property of type {@link PropertyType#FRACTION}, interpreting the value properly.
*
* @param property
* property to get
* @return property value
* @throws IllegalArgumentException
* if the property is of the wrong type
*/
public double getFraction(Property property) {
checkType(property, PropertyType.FRACTION);
return ConfigurationTypeHelper.getFraction(get(property));
}
/**
* Gets a property of type {@link PropertyType#PORT}, interpreting the value properly (as an
* integer within the range of non-privileged ports).
*
* @param property
* property to get
* @return property value
* @throws IllegalArgumentException
* if the property is of the wrong type
*/
public int[] getPort(Property property) {
checkType(property, PropertyType.PORT);
String portString = get(property);
int[] ports = null;
try {
Pair<Integer,Integer> portRange = PortRange.parse(portString);
int low = portRange.getFirst();
int high = portRange.getSecond();
ports = new int[high - low + 1];
for (int i = 0, j = low; j <= high; i++, j++) {
ports[i] = j;
}
} catch (IllegalArgumentException e) {
ports = new int[1];
try {
int port = Integer.parseInt(portString);
if (port == 0) {
ports[0] = port;
} else {
if (port < 1024 || port > 65535) {
log.error("Invalid port number {}; Using default {}", port, property.getDefaultValue());
ports[0] = Integer.parseInt(property.getDefaultValue());
} else {
ports[0] = port;
}
}
} catch (NumberFormatException e1) {
throw new IllegalArgumentException("Invalid port syntax. Must be a single positive "
+ "integers or a range (M-N) of positive integers");
}
}
return ports;
}
/**
* Gets a property of type {@link PropertyType#COUNT}, interpreting the value properly (as an
* integer).
*
* @param property
* property to get
* @return property value
* @throws IllegalArgumentException
* if the property is of the wrong type
*/
public int getCount(Property property) {
checkType(property, PropertyType.COUNT);
String countString = get(property);
return Integer.parseInt(countString);
}
/**
* Gets a property of type {@link PropertyType#PATH}.
*
* @param property
* property to get
* @return property value
* @throws IllegalArgumentException
* if the property is of the wrong type
*/
public String getPath(Property property) {
checkType(property, PropertyType.PATH);
String pathString = get(property);
if (pathString == null) {
return null;
}
if (pathString.contains("$ACCUMULO_")) {
throw new IllegalArgumentException("Environment variable interpolation not supported here. "
+ "Consider using '${env:ACCUMULO_HOME}' or similar in your configuration file.");
}
return pathString;
}
/**
* Gets the maximum number of files per tablet from this configuration.
*
* @return maximum number of files per tablet
* @see Property#TABLE_FILE_MAX
* @see Property#TSERV_SCAN_MAX_OPENFILES
*/
public int getMaxFilesPerTablet() {
int maxFilesPerTablet = getCount(Property.TABLE_FILE_MAX);
if (maxFilesPerTablet <= 0) {
maxFilesPerTablet = getCount(Property.TSERV_SCAN_MAX_OPENFILES) - 1;
log.debug("Max files per tablet {}", maxFilesPerTablet);
}
return maxFilesPerTablet;
}
public class ScanExecutorConfig {
public final String name;
public final int maxThreads;
public final OptionalInt priority;
public final Optional<String> prioritizerClass;
public final Map<String,String> prioritizerOpts;
public ScanExecutorConfig(String name, int maxThreads, OptionalInt priority,
Optional<String> comparatorFactory, Map<String,String> comparatorFactoryOpts) {
this.name = name;
this.maxThreads = maxThreads;
this.priority = priority;
this.prioritizerClass = comparatorFactory;
this.prioritizerOpts = comparatorFactoryOpts;
}
/**
* Re-reads the max threads from the configuration that created this class
*/
public int getCurrentMaxThreads() {
Integer depThreads = getDeprecatedScanThreads(name);
if (depThreads != null) {
return depThreads;
}
String prop = Property.TSERV_SCAN_EXECUTORS_PREFIX.getKey() + name + "." + SCAN_EXEC_THREADS;
String val = getAllPropertiesWithPrefix(Property.TSERV_SCAN_EXECUTORS_PREFIX).get(prop);
return Integer.parseInt(val);
}
}
public boolean isPropertySet(Property prop, boolean cacheAndWatch) {
throw new UnsupportedOperationException();
}
// deprecation property warning could get spammy in tserver so only warn once
boolean depPropWarned = false;
@SuppressWarnings("deprecation")
Integer getDeprecatedScanThreads(String name) {
Property prop;
Property deprecatedProp;
if (name.equals(SimpleScanDispatcher.DEFAULT_SCAN_EXECUTOR_NAME)) {
prop = Property.TSERV_SCAN_EXECUTORS_DEFAULT_THREADS;
deprecatedProp = Property.TSERV_READ_AHEAD_MAXCONCURRENT;
} else if (name.equals("meta")) {
prop = Property.TSERV_SCAN_EXECUTORS_META_THREADS;
deprecatedProp = Property.TSERV_METADATA_READ_AHEAD_MAXCONCURRENT;
} else {
return null;
}
if (!isPropertySet(prop, true) && isPropertySet(deprecatedProp, true)) {
if (!depPropWarned) {
depPropWarned = true;
log.warn("Property {} is deprecated, use {} instead.", deprecatedProp.getKey(),
prop.getKey());
}
return Integer.valueOf(get(deprecatedProp));
} else if (isPropertySet(prop, true) && isPropertySet(deprecatedProp, true) && !depPropWarned) {
depPropWarned = true;
log.warn("Deprecated property {} ignored because {} is set", deprecatedProp.getKey(),
prop.getKey());
}
return null;
}
private static class RefCount<T> {
T obj;
long count;
RefCount(long c, T r) {
this.count = c;
this.obj = r;
}
}
private class DeriverImpl<T> implements Deriver<T> {
private final AtomicReference<RefCount<T>> refref = new AtomicReference<>();
private final Function<AccumuloConfiguration,T> converter;
DeriverImpl(Function<AccumuloConfiguration,T> converter) {
this.converter = converter;
}
/**
* This method was written with the goal of avoiding thread contention and minimizing
* recomputation. Configuration can be accessed frequently by many threads. Ideally, threads
* working on unrelated task would not impeded each other because of accessing config.
*
* To avoid thread contention, synchronization and needless calls to compare and set were
* avoided. For example if 100 threads are all calling compare and set in a loop this could
* cause significant contention.
*/
@Override
public T derive() {
// very important to obtain this before possibly recomputing object
long uc = getUpdateCount();
RefCount<T> rc = refref.get();
if (rc == null || rc.count != uc) {
T newObj = converter.apply(AccumuloConfiguration.this);
// very important to record the update count that was obtained before recomputing.
RefCount<T> nrc = new RefCount<>(uc, newObj);
/*
* The return value of compare and set is intentionally ignored here. This code could loop
* calling compare and set inorder to avoid returning a stale object. However after this
* function returns, the object could immediately become stale. So in the big picture stale
* objects can not be prevented. Looping here could cause thread contention, but it would
* not solve the overall stale object problem. That is why the return value was ignored. The
* following line is a least effort attempt to make the result of this recomputation
* available to the next caller.
*/
refref.compareAndSet(rc, nrc);
return nrc.obj;
}
return rc.obj;
}
}
/**
* Automatically regenerates an object whenever configuration changes. When configuration is not
* changing, keeps returning the same object. Implementations should be thread safe and eventually
* consistent. See {@link AccumuloConfiguration#newDeriver(Function)}
*/
public interface Deriver<T> {
T derive();
}
/**
* Enables deriving an object from configuration and automatically deriving a new object any time
* configuration changes.
*
* @param converter
* This functions is used to create an object from configuration. A reference to this
* function will be kept and called by the returned deriver.
* @return The returned supplier will automatically re-derive the object any time this
* configuration changes. When configuration is not changing, the same object is returned.
*
*/
public <T> Deriver<T> newDeriver(Function<AccumuloConfiguration,T> converter) {
return new DeriverImpl<>(converter);
}
private static final String SCAN_EXEC_THREADS = "threads";
private static final String SCAN_EXEC_PRIORITY = "priority";
private static final String SCAN_EXEC_PRIORITIZER = "prioritizer";
private static final String SCAN_EXEC_PRIORITIZER_OPTS = "prioritizer.opts.";
public Collection<ScanExecutorConfig> getScanExecutors() {
Map<String,Map<String,String>> propsByName = new HashMap<>();
List<ScanExecutorConfig> scanResources = new ArrayList<>();
for (Entry<String,String> entry : getAllPropertiesWithPrefix(
Property.TSERV_SCAN_EXECUTORS_PREFIX).entrySet()) {
String suffix =
entry.getKey().substring(Property.TSERV_SCAN_EXECUTORS_PREFIX.getKey().length());
String[] tokens = suffix.split("\\.", 2);
String name = tokens[0];
propsByName.computeIfAbsent(name, k -> new HashMap<>()).put(tokens[1], entry.getValue());
}
for (Entry<String,Map<String,String>> entry : propsByName.entrySet()) {
String name = entry.getKey();
Integer threads = null;
Integer prio = null;
String prioritizerClass = null;
Map<String,String> prioritizerOpts = new HashMap<>();
for (Entry<String,String> subEntry : entry.getValue().entrySet()) {
String opt = subEntry.getKey();
String val = subEntry.getValue();
if (opt.equals(SCAN_EXEC_THREADS)) {
Integer depThreads = getDeprecatedScanThreads(name);
if (depThreads == null) {
threads = Integer.parseInt(val);
} else {
threads = depThreads;
}
} else if (opt.equals(SCAN_EXEC_PRIORITY)) {
prio = Integer.parseInt(val);
} else if (opt.equals(SCAN_EXEC_PRIORITIZER)) {
prioritizerClass = val;
} else if (opt.startsWith(SCAN_EXEC_PRIORITIZER_OPTS)) {
String key = opt.substring(SCAN_EXEC_PRIORITIZER_OPTS.length());
if (key.isEmpty()) {
throw new IllegalStateException("Invalid scan executor option : " + opt);
}
prioritizerOpts.put(key, val);
} else {
throw new IllegalStateException("Unkown scan executor option : " + opt);
}
}
Preconditions.checkArgument(threads != null && threads > 0,
"Scan resource %s incorrectly specified threads", name);
scanResources.add(new ScanExecutorConfig(name, threads,
prio == null ? OptionalInt.empty() : OptionalInt.of(prio),
Optional.ofNullable(prioritizerClass), prioritizerOpts));
}
return scanResources;
}
/**
* Invalidates the <code>ZooCache</code> used for storage and quick retrieval of properties for
* this configuration.
*/
public void invalidateCache() {}
}
| Java |
/**
* Copyright (c) 2011 Jonathan Leibiusky
*
* 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 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 com.navercorp.redis.cluster;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.navercorp.redis.cluster.pipeline.BuilderFactory;
import redis.clients.jedis.BinaryClient.LIST_POSITION;
import redis.clients.jedis.Tuple;
/**
* The Class RedisCluster.
*
* @author jaehong.kim
*/
public class RedisCluster extends BinaryRedisCluster implements
RedisClusterCommands {
/**
* Instantiates a new redis cluster.
*
* @param host the host
*/
public RedisCluster(final String host) {
super(host);
}
/**
* Instantiates a new redis cluster.
*
* @param host the host
* @param port the port
*/
public RedisCluster(final String host, final int port) {
super(host, port);
}
/**
* Instantiates a new redis cluster.
*
* @param host the host
* @param port the port
* @param timeout the timeout
*/
public RedisCluster(final String host, final int port, final int timeout) {
super(host, port, timeout);
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
// Keys
public Long del(final String... keys) {
client.del(keys);
return client.getIntegerReply();
}
public Boolean exists(final String key) {
client.exists(key);
return client.getIntegerReply() == 1;
}
public Long expire(final String key, final int seconds) {
client.expire(key, seconds);
return client.getIntegerReply();
}
public Long expireAt(final String key, final long secondsTimestamp) {
client.expireAt(key, secondsTimestamp);
return client.getIntegerReply();
}
public Long pexpire(final String key, final long milliseconds) {
client.pexpire(key, milliseconds);
return client.getIntegerReply();
}
public Long pexpireAt(final String key, final long millisecondsTimestamp) {
client.pexpireAt(key, millisecondsTimestamp);
return client.getIntegerReply();
}
public Long objectRefcount(String string) {
client.objectRefcount(string);
return client.getIntegerReply();
}
public String objectEncoding(String string) {
client.objectEncoding(string);
return client.getBulkReply();
}
public Long objectIdletime(String string) {
client.objectIdletime(string);
return client.getIntegerReply();
}
public Long ttl(final String key) {
client.ttl(key);
return client.getIntegerReply();
}
public Long pttl(final String key) {
client.pttl(key);
return client.getIntegerReply();
}
public String type(final String key) {
client.type(key);
return client.getStatusCodeReply();
}
public Long persist(final String key) {
client.persist(key);
return client.getIntegerReply();
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
// Strings
public Long append(final String key, final String value) {
client.append(key, value);
return client.getIntegerReply();
}
public Long decr(final String key) {
client.decr(key);
return client.getIntegerReply();
}
public Long decrBy(final String key, final long integer) {
client.decrBy(key, integer);
return client.getIntegerReply();
}
public String get(final String key) {
client.get(key);
return client.getBulkReply();
}
public Boolean getbit(String key, long offset) {
client.getbit(key, offset);
return client.getIntegerReply() == 1;
}
public String getrange(String key, long startOffset, long endOffset) {
client.getrange(key, startOffset, endOffset);
return client.getBulkReply();
}
public String substr(final String key, final int start, final int end) {
client.substr(key, start, end);
return client.getBulkReply();
}
public String getSet(final String key, final String value) {
client.getSet(key, value);
return client.getBulkReply();
}
public Long incr(final String key) {
client.incr(key);
return client.getIntegerReply();
}
public Long incrBy(final String key, final long integer) {
client.incrBy(key, integer);
return client.getIntegerReply();
}
public Double incrByFloat(final String key, final double increment) {
client.incrByFloat(key, increment);
String reply = client.getBulkReply();
return (reply != null ? new Double(reply) : null);
}
public String set(final String key, String value) {
client.set(key, value);
return client.getStatusCodeReply();
}
public Boolean setbit(String key, long offset, boolean value) {
client.setbit(key, offset, value);
return client.getIntegerReply() == 1;
}
public String setex(final String key, final int seconds, final String value) {
client.setex(key, seconds, value);
return client.getStatusCodeReply();
}
public Long setnx(final String key, final String value) {
client.setnx(key, value);
return client.getIntegerReply();
}
public Long setrange(String key, long offset, String value) {
client.setrange(key, offset, value);
return client.getIntegerReply();
}
public Long strlen(final String key) {
client.strlen(key);
return client.getIntegerReply();
}
public List<String> mget(final String... keys) {
client.mget(keys);
return client.getMultiBulkReply();
}
public String psetex(final String key, final long milliseconds,
final String value) {
client.psetex(key, milliseconds, value);
return client.getStatusCodeReply();
}
public String mset(String... keysvalues) {
client.mset(keysvalues);
return client.getStatusCodeReply();
}
public Long bitcount(final String key) {
client.bitcount(key);
return client.getIntegerReply();
}
public Long bitcount(final String key, long start, long end) {
client.bitcount(key, start, end);
return client.getIntegerReply();
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
// Hashes
public Long hdel(final String key, final String... fields) {
client.hdel(key, fields);
return client.getIntegerReply();
}
public Boolean hexists(final String key, final String field) {
client.hexists(key, field);
return client.getIntegerReply() == 1;
}
public String hget(final String key, final String field) {
client.hget(key, field);
return client.getBulkReply();
}
public Map<String, String> hgetAll(final String key) {
client.hgetAll(key);
return BuilderFactory.STRING_MAP
.build(client.getBinaryMultiBulkReply());
}
public Long hincrBy(final String key, final String field, final long value) {
client.hincrBy(key, field, value);
return client.getIntegerReply();
}
public Double hincrByFloat(final String key, final String field,
double increment) {
client.hincrByFloat(key, field, increment);
String reply = client.getBulkReply();
return (reply != null ? new Double(reply) : null);
}
public Set<String> hkeys(final String key) {
client.hkeys(key);
return BuilderFactory.STRING_SET
.build(client.getBinaryMultiBulkReply());
}
public Long hlen(final String key) {
client.hlen(key);
return client.getIntegerReply();
}
public List<String> hmget(final String key, final String... fields) {
client.hmget(key, fields);
return client.getMultiBulkReply();
}
public String hmset(final String key, final Map<String, String> hash) {
client.hmset(key, hash);
return client.getStatusCodeReply();
}
public Long hset(final String key, final String field, final String value) {
client.hset(key, field, value);
return client.getIntegerReply();
}
public Long hsetnx(final String key, final String field, final String value) {
client.hsetnx(key, field, value);
return client.getIntegerReply();
}
public List<String> hvals(final String key) {
client.hvals(key);
final List<String> lresult = client.getMultiBulkReply();
return lresult;
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
// Lists
public String lindex(final String key, final long index) {
client.lindex(key, index);
return client.getBulkReply();
}
public Long linsert(final String key, final LIST_POSITION where,
final String pivot, final String value) {
client.linsert(key, where, pivot, value);
return client.getIntegerReply();
}
public Long llen(final String key) {
client.llen(key);
return client.getIntegerReply();
}
public String lpop(final String key) {
client.lpop(key);
return client.getBulkReply();
}
public Long lpush(final String key, final String... strings) {
client.lpush(key, strings);
return client.getIntegerReply();
}
public Long lpushx(final String key, final String string) {
client.lpushx(key, string);
return client.getIntegerReply();
}
public List<String> lrange(final String key, final long start,
final long end) {
client.lrange(key, start, end);
return client.getMultiBulkReply();
}
public Long lrem(final String key, final long count, final String value) {
client.lrem(key, count, value);
return client.getIntegerReply();
}
public String lset(final String key, final long index, final String value) {
client.lset(key, index, value);
return client.getStatusCodeReply();
}
public String ltrim(final String key, final long start, final long end) {
client.ltrim(key, start, end);
return client.getStatusCodeReply();
}
public String rpop(final String key) {
client.rpop(key);
return client.getBulkReply();
}
public Long rpush(final String key, final String... strings) {
client.rpush(key, strings);
return client.getIntegerReply();
}
public Long rpushx(final String key, final String string) {
client.rpushx(key, string);
return client.getIntegerReply();
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
// Sets
public Long sadd(final String key, final String... members) {
client.sadd(key, members);
return client.getIntegerReply();
}
public Long scard(final String key) {
client.scard(key);
return client.getIntegerReply();
}
public Boolean sismember(final String key, final String member) {
client.sismember(key, member);
return client.getIntegerReply() == 1;
}
public Set<String> smembers(final String key) {
client.smembers(key);
final List<String> members = client.getMultiBulkReply();
return new HashSet<String>(members);
}
public String srandmember(final String key) {
client.srandmember(key);
return client.getBulkReply();
}
public List<String> srandmember(final String key, final int count) {
client.srandmember(key, count);
return client.getMultiBulkReply();
}
public Long srem(final String key, final String... members) {
client.srem(key, members);
return client.getIntegerReply();
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
// Sorted Sets
public Long zadd(final String key, final double score, final String member) {
client.zadd(key, score, member);
return client.getIntegerReply();
}
public Long zadd(final String key, final Map<Double, String> scoreMembers) {
client.zadd(key, scoreMembers);
return client.getIntegerReply();
}
public Long zadd2(final String key, final Map<String, Double> scoreMembers) {
client.zadd2(key, scoreMembers);
return client.getIntegerReply();
}
public Long zcard(final String key) {
client.zcard(key);
return client.getIntegerReply();
}
public Long zcount(final String key, final double min, final double max) {
client.zcount(key, min, max);
return client.getIntegerReply();
}
public Long zcount(final String key, final String min, final String max) {
client.zcount(key, min, max);
return client.getIntegerReply();
}
public Double zincrby(final String key, final double score,
final String member) {
client.zincrby(key, score, member);
String newscore = client.getBulkReply();
return Double.valueOf(newscore);
}
public Set<String> zrange(final String key, final long start, final long end) {
client.zrange(key, start, end);
final List<String> members = client.getMultiBulkReply();
return new LinkedHashSet<String>(members);
}
public Set<String> zrangeByScore(final String key, final double min,
final double max) {
client.zrangeByScore(key, min, max);
return new LinkedHashSet<String>(client.getMultiBulkReply());
}
public Set<String> zrangeByScore(final String key, final String min,
final String max) {
client.zrangeByScore(key, min, max);
return new LinkedHashSet<String>(client.getMultiBulkReply());
}
public Set<String> zrangeByScore(final String key, final double min,
final double max, final int offset, final int count) {
client.zrangeByScore(key, min, max, offset, count);
return new LinkedHashSet<String>(client.getMultiBulkReply());
}
public Set<String> zrangeByScore(final String key, final String min,
final String max, final int offset, final int count) {
client.zrangeByScore(key, min, max, offset, count);
return new LinkedHashSet<String>(client.getMultiBulkReply());
}
public Set<Tuple> zrangeWithScores(final String key, final long start,
final long end) {
client.zrangeWithScores(key, start, end);
Set<Tuple> set = getTupledSet();
return set;
}
public Set<Tuple> zrangeByScoreWithScores(final String key,
final double min, final double max) {
client.zrangeByScoreWithScores(key, min, max);
Set<Tuple> set = getTupledSet();
return set;
}
public Set<Tuple> zrangeByScoreWithScores(final String key,
final String min, final String max) {
client.zrangeByScoreWithScores(key, min, max);
Set<Tuple> set = getTupledSet();
return set;
}
public Set<Tuple> zrangeByScoreWithScores(final String key,
final double min, final double max, final int offset,
final int count) {
client.zrangeByScoreWithScores(key, min, max, offset, count);
Set<Tuple> set = getTupledSet();
return set;
}
public Set<Tuple> zrangeByScoreWithScores(final String key,
final String min, final String max, final int offset,
final int count) {
client.zrangeByScoreWithScores(key, min, max, offset, count);
Set<Tuple> set = getTupledSet();
return set;
}
public Long zrank(final String key, final String member) {
client.zrank(key, member);
return client.getIntegerReply();
}
public Long zrem(final String key, final String... members) {
client.zrem(key, members);
return client.getIntegerReply();
}
public Long zremrangeByRank(final String key, final long start,
final long end) {
client.zremrangeByRank(key, start, end);
return client.getIntegerReply();
}
public Long zremrangeByScore(final String key, final double start,
final double end) {
client.zremrangeByScore(key, start, end);
return client.getIntegerReply();
}
public Long zremrangeByScore(final String key, final String start,
final String end) {
client.zremrangeByScore(key, start, end);
return client.getIntegerReply();
}
public Set<String> zrevrange(final String key, final long start,
final long end) {
client.zrevrange(key, start, end);
final List<String> members = client.getMultiBulkReply();
return new LinkedHashSet<String>(members);
}
public Set<Tuple> zrevrangeWithScores(final String key, final long start,
final long end) {
client.zrevrangeWithScores(key, start, end);
Set<Tuple> set = getTupledSet();
return set;
}
public Set<String> zrevrangeByScore(final String key, final double max,
final double min) {
client.zrevrangeByScore(key, max, min);
return new LinkedHashSet<String>(client.getMultiBulkReply());
}
public Set<String> zrevrangeByScore(final String key, final String max,
final String min) {
client.zrevrangeByScore(key, max, min);
return new LinkedHashSet<String>(client.getMultiBulkReply());
}
public Set<String> zrevrangeByScore(final String key, final double max,
final double min, final int offset, final int count) {
client.zrevrangeByScore(key, max, min, offset, count);
return new LinkedHashSet<String>(client.getMultiBulkReply());
}
public Set<Tuple> zrevrangeByScoreWithScores(final String key,
final double max, final double min) {
client.zrevrangeByScoreWithScores(key, max, min);
Set<Tuple> set = getTupledSet();
return set;
}
public Set<Tuple> zrevrangeByScoreWithScores(final String key,
final double max, final double min, final int offset,
final int count) {
client.zrevrangeByScoreWithScores(key, max, min, offset, count);
Set<Tuple> set = getTupledSet();
return set;
}
public Set<Tuple> zrevrangeByScoreWithScores(final String key,
final String max, final String min, final int offset,
final int count) {
client.zrevrangeByScoreWithScores(key, max, min, offset, count);
Set<Tuple> set = getTupledSet();
return set;
}
public Set<String> zrevrangeByScore(final String key, final String max,
final String min, final int offset, final int count) {
client.zrevrangeByScore(key, max, min, offset, count);
return new LinkedHashSet<String>(client.getMultiBulkReply());
}
public Set<Tuple> zrevrangeByScoreWithScores(final String key,
final String max, final String min) {
client.zrevrangeByScoreWithScores(key, max, min);
Set<Tuple> set = getTupledSet();
return set;
}
public Long zrevrank(final String key, final String member) {
client.zrevrank(key, member);
return client.getIntegerReply();
}
public Double zscore(final String key, final String member) {
client.zscore(key, member);
final String score = client.getBulkReply();
return (score != null ? new Double(score) : null);
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
// Connection
public String ping() {
client.ping();
return client.getStatusCodeReply();
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
// Server
public String info() {
client.info();
return client.getBulkReply();
}
public String info(final String section) {
client.info(section);
return client.getBulkReply();
}
public Long dbSize() {
client.dbSize();
return client.getIntegerReply();
}
public byte[] dump(final String key) {
client.dump(key);
return client.getBinaryBulkReply();
}
public String restore(final String key, final long ttl,
final byte[] serializedValue) {
client.restore(key, ttl, serializedValue);
return client.getStatusCodeReply();
}
/**
* Quit.
*
* @return the string
*/
public String quit() {
client.quit();
return client.getStatusCodeReply();
}
/**
* Connect.
*/
public void connect() {
client.connect();
}
/**
* Disconnect.
*/
public void disconnect() {
client.disconnect();
}
/**
* Checks if is connected.
*
* @return true, if is connected
*/
public boolean isConnected() {
return client.isConnected();
}
/**
* Gets the tupled set.
*
* @return the tupled set
*/
private Set<Tuple> getTupledSet() {
List<String> membersWithScores = client.getMultiBulkReply();
Set<Tuple> set = new LinkedHashSet<Tuple>();
Iterator<String> iterator = membersWithScores.iterator();
while (iterator.hasNext()) {
set.add(new Tuple(iterator.next(), Double.valueOf(iterator.next())));
}
return set;
}
} | Java |
/*
* Copyright 2017-2022 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.chime.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.chime.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* GetMediaCapturePipelineRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class GetMediaCapturePipelineRequestProtocolMarshaller implements Marshaller<Request<GetMediaCapturePipelineRequest>, GetMediaCapturePipelineRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON)
.requestUri("/media-capture-pipelines/{mediaPipelineId}").httpMethodName(HttpMethodName.GET).hasExplicitPayloadMember(false)
.hasPayloadMembers(false).serviceName("AmazonChime").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public GetMediaCapturePipelineRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<GetMediaCapturePipelineRequest> marshall(GetMediaCapturePipelineRequest getMediaCapturePipelineRequest) {
if (getMediaCapturePipelineRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<GetMediaCapturePipelineRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(
SDK_OPERATION_BINDING, getMediaCapturePipelineRequest);
protocolMarshaller.startMarshalling();
GetMediaCapturePipelineRequestMarshaller.getInstance().marshall(getMediaCapturePipelineRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| Java |
/**
* @file stomp_planner_manager.cpp
* @brief This defines the stomp planning manager for MoveIt
*
* @author Jorge Nicho
* @date April 5, 2016
* @version TODO
* @bug No known bugs
*
* @copyright Copyright (c) 2016, Southwest Research Institute
*
* @par License
* Software License Agreement (Apache License)
* @par
* 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
* @par
* 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.
*/
#include <class_loader/class_loader.h>
#include <stomp_moveit/stomp_planner_manager.h>
#include <stomp_moveit/stomp_planner.h>
namespace stomp_moveit
{
StompPlannerManager::StompPlannerManager():
planning_interface::PlannerManager(),
nh_("~")
{
}
StompPlannerManager::~StompPlannerManager()
{
}
bool StompPlannerManager::initialize(const robot_model::RobotModelConstPtr &model, const std::string &ns)
{
if (!ns.empty())
{
nh_ = ros::NodeHandle(ns);
}
robot_model_ = model;
// each element under 'stomp' should be a group name
std::map<std::string, XmlRpc::XmlRpcValue> group_config;
if (!StompPlanner::getConfigData(nh_, group_config))
{
return false;
}
for(std::map<std::string, XmlRpc::XmlRpcValue>::iterator v = group_config.begin(); v != group_config.end(); v++)
{
if(!model->hasJointModelGroup(v->first))
{
ROS_WARN("The robot model does not support the planning group '%s' in the STOMP configuration, skipping STOMP setup for this group",
v->first.c_str());
continue;
}
std::shared_ptr<StompPlanner> planner(new StompPlanner(v->first, v->second, robot_model_));
planners_.insert(std::make_pair(v->first, planner));
}
if(planners_.empty())
{
ROS_ERROR("All planning groups are invalid, STOMP could not be configured");
return false;
}
return true;
}
bool StompPlannerManager::canServiceRequest(const moveit_msgs::MotionPlanRequest &req) const
{
if(planners_.count(req.group_name) == 0)
{
return false;
}
// Get planner
std::shared_ptr<StompPlanner> planner = std::static_pointer_cast<StompPlanner>(planners_.at(req.group_name));
return planner->canServiceRequest(req);
}
void StompPlannerManager::getPlanningAlgorithms(std::vector<std::string> &algs) const
{
algs.clear();
if(!planners_.empty())
{
algs.push_back(planners_.begin()->second->getName());
}
}
void StompPlannerManager::setPlannerConfigurations(const planning_interface::PlannerConfigurationMap &pcs)
{
ROS_WARN_STREAM("The "<<__FUNCTION__<<" method is not applicable");
}
planning_interface::PlanningContextPtr StompPlannerManager::getPlanningContext(const planning_scene::PlanningSceneConstPtr &planning_scene,
const planning_interface::MotionPlanRequest &req,
moveit_msgs::MoveItErrorCodes &error_code) const
{
error_code.val = moveit_msgs::MoveItErrorCodes::SUCCESS;
if (req.group_name.empty())
{
ROS_ERROR("No group specified to plan for");
error_code.val = moveit_msgs::MoveItErrorCodes::INVALID_GROUP_NAME;
return planning_interface::PlanningContextPtr();
}
if (!planning_scene)
{
ROS_ERROR("No planning scene supplied as input");
error_code.val = moveit_msgs::MoveItErrorCodes::FAILURE;
return planning_interface::PlanningContextPtr();
}
if(planners_.count(req.group_name) <=0)
{
ROS_ERROR("STOMP does not have a planning context for group %s",req.group_name.c_str());
error_code.val = moveit_msgs::MoveItErrorCodes::FAILURE;
return planning_interface::PlanningContextPtr();
}
// Get planner
std::shared_ptr<StompPlanner> planner = std::static_pointer_cast<StompPlanner>(planners_.at(req.group_name));
if(!planner->canServiceRequest(req))
{
error_code.val = moveit_msgs::MoveItErrorCodes::FAILURE;
return planning_interface::PlanningContextPtr();
}
// Setup Planner
planner->clear();
planner->setPlanningScene(planning_scene);
planner->setMotionPlanRequest(req);
// Return Planner
return planner;
}
} /* namespace stomp_moveit_interface */
CLASS_LOADER_REGISTER_CLASS(stomp_moveit::StompPlannerManager, planning_interface::PlannerManager)
| Java |
/**
* Copyright (c) 2013, Redsolution LTD. All rights reserved.
*
* This file is part of Xabber project; you can redistribute it and/or
* modify it under the terms of the GNU General Public License, Version 3.
*
* Xabber is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package com.itracker.android.data.roster;
import android.text.TextUtils;
import com.itracker.android.data.account.StatusMode;
import org.jivesoftware.smack.roster.RosterEntry;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Contact in roster.
* <p/>
* {@link #getUser()} always will be bare jid.
*
* @author alexander.ivanov
*/
public class RosterContact extends AbstractContact {
/**
* Contact's name.
*/
protected String name;
/**
* Used groups with its names.
*/
protected final Map<String, RosterGroupReference> groupReferences;
/**
* Whether there is subscription of type "both" or "to".
*/
protected boolean subscribed;
/**
* Whether contact`s account is connected.
*/
protected boolean connected;
/**
* Whether contact`s account is enabled.
*/
protected boolean enabled;
/**
* Data id to view contact information from system contact list.
* <p/>
* Warning: not implemented yet.
*/
private Long viewId;
public RosterContact(String account, RosterEntry rosterEntry) {
this(account, rosterEntry.getUser(), rosterEntry.getName());
}
public RosterContact(String account, String user, String name) {
super(account, user);
if (name == null) {
this.name = null;
} else {
this.name = name.trim();
}
groupReferences = new HashMap<>();
subscribed = true;
connected = true;
enabled = true;
viewId = null;
}
void setName(String name) {
this.name = name;
}
@Override
public Collection<RosterGroupReference> getGroups() {
return Collections.unmodifiableCollection(groupReferences.values());
}
Collection<String> getGroupNames() {
return Collections.unmodifiableCollection(groupReferences.keySet());
}
void addGroupReference(RosterGroupReference groupReference) {
groupReferences.put(groupReference.getName(), groupReference);
}
void setSubscribed(boolean subscribed) {
this.subscribed = subscribed;
}
@Override
public StatusMode getStatusMode() {
return PresenceManager.getInstance().getStatusMode(account, user);
}
@Override
public String getName() {
if (TextUtils.isEmpty(name)) {
return super.getName();
} else {
return name;
}
}
@Override
public boolean isConnected() {
return connected;
}
void setConnected(boolean connected) {
this.connected = connected;
}
public boolean isEnabled() {
return enabled;
}
void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Long getViewId() {
return viewId;
}
}
| Java |
/* Copyright (c) 2016 PaddlePaddle Authors. 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. */
#include "paddle/fluid/operators/transpose_op.h"
#include <string>
#include <vector>
#ifdef PADDLE_WITH_MKLDNN
#include "paddle/fluid/platform/mkldnn_helper.h"
#endif
namespace paddle {
namespace operators {
using framework::Tensor;
class TransposeOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext *ctx) const override {
PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) should not be null");
PADDLE_ENFORCE(ctx->HasOutput("Out"), "Output(Out) should not be null");
auto x_dims = ctx->GetInputDim("X");
std::vector<int> axis = ctx->Attrs().Get<std::vector<int>>("axis");
size_t x_rank = x_dims.size();
size_t axis_size = axis.size();
PADDLE_ENFORCE_EQ(x_rank, axis_size,
"The input tensor's rank(%d) "
"should be equal to the axis's size(%d)",
x_rank, axis_size);
std::vector<int> count(axis_size, 0);
for (size_t i = 0; i < axis_size; i++) {
PADDLE_ENFORCE(
axis[i] < static_cast<int>(axis_size) && ++count[axis[i]] == 1,
"Each element of Attribute axis should be a unique value "
"range from 0 to (dims - 1), "
"where the dims is the axis's size");
}
framework::DDim out_dims(x_dims);
for (size_t i = 0; i < axis_size; i++) {
out_dims[i] = x_dims[axis[i]];
}
ctx->SetOutputDim("Out", out_dims);
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext &ctx) const override {
framework::LibraryType library_{framework::LibraryType::kPlain};
std::string data_format = ctx.Attr<std::string>("data_format");
framework::DataLayout layout_ = framework::StringToDataLayout(data_format);
#ifdef PADDLE_WITH_MKLDNN
if (library_ == framework::LibraryType::kPlain &&
platform::CanMKLDNNBeUsed(ctx)) {
library_ = framework::LibraryType::kMKLDNN;
layout_ = framework::DataLayout::kMKLDNN;
}
#endif
return framework::OpKernelType(ctx.Input<Tensor>("X")->type(),
ctx.GetPlace(), layout_, library_);
}
};
class TransposeOpMaker : public framework::OpProtoAndCheckerMaker {
public:
void Make() override {
AddInput(
"X",
"(Tensor) The input tensor, tensors with rank up to 6 are supported.");
AddOutput("Out", "(Tensor)The output tensor.");
AddAttr<std::vector<int>>(
"axis",
"(vector<int>) A list of values, and the size of the list should be "
"the same with the input tensor rank. This operator permutes the input "
"tensor's axes according to the values given.");
AddAttr<bool>("use_mkldnn",
"(bool, default false) Only used in mkldnn kernel")
.SetDefault(false);
AddAttr<std::string>(
"data_format",
"(string, default NCHW) Only used in "
"An optional string from: \"NHWC\", \"NCHW\". "
"Defaults to \"NHWC\". Specify the data format of the output data, "
"the input will be transformed automatically. ")
.SetDefault("AnyLayout");
AddComment(R"DOC(
Transpose Operator.
The input tensor will be permuted according to the axes given.
The behavior of this operator is similar to how `numpy.transpose` works.
- suppose the input `X` is a 2-D tensor:
$$
X = \begin{pmatrix}
0 &1 &2 \\
3 &4 &5
\end{pmatrix}$$
the given `axes` is: $[1, 0]$, and $Y$ = transpose($X$, axis)
then the output $Y$ is:
$$
Y = \begin{pmatrix}
0 &3 \\
1 &4 \\
2 &5
\end{pmatrix}$$
- Given a input tensor with shape $(N, C, H, W)$ and the `axes` is
$[0, 2, 3, 1]$, then shape of the output tensor will be: $(N, H, W, C)$.
)DOC");
}
};
class TransposeOpGrad : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext *ctx) const override {
PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) should not be null");
PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Out")),
"Input(Out@GRAD) should not be null");
auto x_dims = ctx->GetInputDim("X");
ctx->SetOutputDim(framework::GradVarName("X"), x_dims);
if (ctx->HasOutput(framework::GradVarName("X"))) {
ctx->SetOutputDim(framework::GradVarName("X"), x_dims);
}
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext &ctx) const override {
framework::LibraryType library_{framework::LibraryType::kPlain};
std::string data_format = ctx.Attr<std::string>("data_format");
framework::DataLayout layout_ = framework::StringToDataLayout(data_format);
#ifdef PADDLE_WITH_MKLDNN
if (library_ == framework::LibraryType::kPlain &&
platform::CanMKLDNNBeUsed(ctx)) {
library_ = framework::LibraryType::kMKLDNN;
layout_ = framework::DataLayout::kMKLDNN;
}
#endif
return framework::OpKernelType(
ctx.Input<framework::LoDTensor>(framework::GradVarName("Out"))->type(),
ctx.GetPlace(), layout_, library_);
}
};
// FIXME(zcd): transpose2 adds an intermediate output(XShape) based on
// transpose, the XShape is used to carry the shape and lod of X which
// will be used in transpose_grad, in this way, the framework can reuse
// the memory of X immediately the transpose2_op is finished.
// Considering compatibility issues, we could not fix transpose2_op
class Transpose2Op : public TransposeOp {
public:
Transpose2Op(const std::string &type,
const framework::VariableNameMap &inputs,
const framework::VariableNameMap &outputs,
const framework::AttributeMap &attrs)
: TransposeOp(type, inputs, outputs, attrs) {}
void InferShape(framework::InferShapeContext *ctx) const override {
TransposeOp::InferShape(ctx);
PADDLE_ENFORCE(ctx->HasOutput("XShape"),
"Output(XShape) should not be null");
const auto &in_dims = ctx->GetInputDim("X");
std::vector<int64_t> x_shape_dim(in_dims.size() + 1);
x_shape_dim[0] = 0;
for (int i = 0; i < in_dims.size(); ++i) {
x_shape_dim[i + 1] = in_dims[i];
}
ctx->SetOutputDim("XShape", framework::make_ddim(x_shape_dim));
ctx->ShareLoD("X", /*->*/ "XShape");
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext &ctx) const override {
framework::LibraryType library_{framework::LibraryType::kPlain};
std::string data_format = ctx.Attr<std::string>("data_format");
framework::DataLayout layout_ = framework::StringToDataLayout(data_format);
#ifdef PADDLE_WITH_MKLDNN
if (library_ == framework::LibraryType::kPlain &&
platform::CanMKLDNNBeUsed(ctx)) {
library_ = framework::LibraryType::kMKLDNN;
layout_ = framework::DataLayout::kMKLDNN;
}
#endif
return framework::OpKernelType(ctx.Input<Tensor>("X")->type(),
ctx.GetPlace(), layout_, library_);
}
};
class Transpose2OpMaker : public TransposeOpMaker {
public:
void Make() override {
TransposeOpMaker::Make();
AddOutput("XShape", "(Tensor)The output tensor.").AsIntermediate();
}
};
class Transpose2GradMaker : public framework::SingleGradOpDescMaker {
public:
using framework::SingleGradOpDescMaker::SingleGradOpDescMaker;
std::unique_ptr<framework::OpDesc> Apply() const override {
auto *grad_op = new framework::OpDesc();
grad_op->SetType("transpose2_grad");
grad_op->SetInput("XShape", Output("XShape"));
grad_op->SetInput(framework::GradVarName("Out"), OutputGrad("Out"));
grad_op->SetOutput(framework::GradVarName("X"), InputGrad("X"));
grad_op->SetAttrMap(Attrs());
return std::unique_ptr<framework::OpDesc>(grad_op);
}
};
class Transpose2OpGrad : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext *ctx) const override {
PADDLE_ENFORCE(ctx->HasInput("XShape"), "Input(XShape) should not be null");
PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Out")),
"Input(Out@GRAD) should not be null");
if (ctx->HasOutput(framework::GradVarName("X"))) {
auto xshape_dim = ctx->GetInputDim("XShape");
auto x_shape_dim =
framework::slice_ddim(xshape_dim, 1, xshape_dim.size());
ctx->SetOutputDim(framework::GradVarName("X"), x_shape_dim);
ctx->ShareLoD("XShape", framework::GradVarName("X"));
}
}
protected:
framework::OpKernelType GetExpectedKernelType(
const framework::ExecutionContext &ctx) const override {
framework::LibraryType library_{framework::LibraryType::kPlain};
std::string data_format = ctx.Attr<std::string>("data_format");
framework::DataLayout layout_ = framework::StringToDataLayout(data_format);
#ifdef PADDLE_WITH_MKLDNN
if (library_ == framework::LibraryType::kPlain &&
platform::CanMKLDNNBeUsed(ctx)) {
library_ = framework::LibraryType::kMKLDNN;
layout_ = framework::DataLayout::kMKLDNN;
}
#endif
return framework::OpKernelType(
ctx.Input<framework::LoDTensor>(framework::GradVarName("Out"))->type(),
ctx.GetPlace(), layout_, library_);
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OPERATOR(transpose, ops::TransposeOp, ops::TransposeOpMaker,
paddle::framework::DefaultGradOpDescMaker<true>);
REGISTER_OPERATOR(transpose_grad, ops::TransposeOpGrad);
REGISTER_OP_CPU_KERNEL(
transpose, ops::TransposeKernel<paddle::platform::CPUDeviceContext, float>,
ops::TransposeKernel<paddle::platform::CPUDeviceContext, double>);
REGISTER_OP_CPU_KERNEL(
transpose_grad,
ops::TransposeGradKernel<paddle::platform::CPUDeviceContext, float>,
ops::TransposeGradKernel<paddle::platform::CPUDeviceContext, double>);
REGISTER_OPERATOR(transpose2, ops::Transpose2Op, ops::Transpose2OpMaker,
ops::Transpose2GradMaker);
REGISTER_OPERATOR(transpose2_grad, ops::Transpose2OpGrad);
REGISTER_OP_CPU_KERNEL(
transpose2, ops::TransposeKernel<paddle::platform::CPUDeviceContext, float>,
ops::TransposeKernel<paddle::platform::CPUDeviceContext, double>);
REGISTER_OP_CPU_KERNEL(
transpose2_grad,
ops::TransposeGradKernel<paddle::platform::CPUDeviceContext, float>,
ops::TransposeGradKernel<paddle::platform::CPUDeviceContext, double>);
| Java |
#region License Header
/*
* QUANTLER.COM - Quant Fund Development Platform
* Quantler Core Trading Engine. Copyright 2018 Quantler B.V.
*
* 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.
*/
#endregion License Header
using Quantler.Exchanges;
using System;
using System.Linq;
namespace Quantler.Scheduler
{
/// <summary>
/// Date composition
/// </summary>
/// <seealso cref="DateComposite" />
public class DateFunc : DateComposite
{
#region Private Fields
/// <summary>
/// The next date function
/// </summary>
private readonly Func<DateTime, DateTime> _nextDateFunc;
/// <summary>
/// The previous date, in case we need to remember this
/// </summary>
private DateTime _previousDate = DateTime.MinValue;
#endregion Private Fields
#region Public Constructors
/// <summary>
/// Initializes a new instance of the <see cref="DateFunc"/> class.
/// </summary>
public DateFunc()
{
}
#endregion Public Constructors
#region Private Constructors
/// <summary>
/// Initializes a new instance of the <see cref="DateFunc"/> class.
/// </summary>
/// <param name="nextdatefunc">The next date function.</param>
/// <param name="name"></param>
private DateFunc(Func<DateTime, DateTime> nextdatefunc, string name)
{
_nextDateFunc = nextdatefunc;
Name = name;
}
#endregion Private Constructors
#region Public Properties
/// <summary>
/// Name of the composite, for easier logging
/// </summary>
public string Name { get; }
#endregion Public Properties
#region Public Methods
/// <summary>
/// Last trading day of each month
/// </summary>
/// <param name="exchangeModel">The exchangeModel.</param>
/// <returns></returns>
public DateComposite EndOfMonth(ExchangeModel exchangeModel) =>
new DateFunc(x =>
{
//Derive the next date
var derived = x.ConvertTo(TimeZone.Utc, exchangeModel.TimeZone).AddMonths(2).DoWhile(n => n.AddDays(-1),
i => !exchangeModel.IsOpenOnDate(i) && x.Month != i.Month + 1);
//return
return derived.ConvertTo(exchangeModel.TimeZone, TimeZone.Utc);
}, "End-Of-Every-Month");
/// <summary>
/// Last trading day of specified month
/// </summary>
/// <param name="exchangeModel">The exchangeModel.</param>
/// <param name="month">The month.</param>
/// <returns></returns>
public DateComposite EndOfMonth(ExchangeModel exchangeModel, int month) =>
new DateFunc(x =>
{
//Get the correct timezone for this exchange (input is utc)
x = x.ConvertTo(TimeZone.Utc, exchangeModel.TimeZone);
//Derive next date
var derived = new DateTime(
x.Month > month || (!exchangeModel.IsOpenOnDate(x) && x.Month == month) ? x.Year + 1 : x.Year,
12, 31)
.DoWhile(n => n.AddDays(-1), i => !exchangeModel.IsOpenOnDate(i) && i.Month != month);
//return
return derived.ConvertTo(exchangeModel.TimeZone, TimeZone.Utc);
}, $"End-Of-Month-{month}");
/// <summary>
/// Last trading day of each week
/// </summary>
/// <param name="exchangeModel">The exchangeModel.</param>
/// <returns></returns>
public DateComposite EndOfWeek(ExchangeModel exchangeModel) =>
new DateFunc(x =>
{
//Get the correct timezone for this exchange (input is utc)
x = x.ConvertTo(TimeZone.Utc, exchangeModel.TimeZone);
//Derive next date
var derived = x.AddDays(7 - ((int) x.DayOfWeek + 1 > 0 ? (int) x.DayOfWeek + 2 : 0))
.DoWhile(n => n.AddDays(-1), n => !exchangeModel.IsOpenOnDate(n));
//return
return derived.ConvertTo(exchangeModel.TimeZone, TimeZone.Utc);
}, "End-Of-Week");
/// <summary>
/// Every day.
/// </summary>
/// <returns></returns>
public DateComposite EveryDay() =>
new DateFunc(x =>
{
//Set previous date
if (_previousDate.Date != x.Date)
{
_previousDate = x.Date.AddDays(1);
return _previousDate;
}
else
return x;
}, "Every-Day");
/// <summary>
/// Every day.
/// </summary>
/// <returns></returns>
public DateComposite EveryTradingDay(ExchangeModel exchangeModel) =>
new DateFunc(x =>
{
//Get the correct timezone for this exchange (input is utc)
x = x.ConvertTo(TimeZone.Utc, exchangeModel.TimeZone);
//Set previous date
var derived = x;
if (_previousDate.Date != x.Date)
{
_previousDate = _previousDate.DoWhile(n => n.AddDays(1), n => !exchangeModel.IsOpenOnDate(n));
derived = _previousDate;
}
//return
return derived.ConvertTo(exchangeModel.TimeZone, TimeZone.Utc);
}, "Every-TradingDay");
/// <summary>
/// Get the next date and time to execute this event
/// </summary>
/// <param name="dateutc">Current date in utc.</param>
/// <returns></returns>
public DateTime NextDate(DateTime dateutc) =>
_nextDateFunc(dateutc);
/// <summary>
/// On a specific year, month and day
/// </summary>
/// <param name="year">The year.</param>
/// <param name="month">The month.</param>
/// <param name="day">The day.</param>
/// <returns></returns>
public DateComposite On(int year, int month, int day) =>
new DateFunc(x => new DateTime(year, month, day), $"At-Date-{year}-{month}-{day}");
/// <summary>
/// On specified days
/// </summary>
/// <param name="dates">The dates.</param>
/// <returns></returns>
public DateComposite On(params DateTime[] dates) =>
new DateFunc(x => x.DoWhile(n => n.AddDays(1), n => dates.Count(i => i.Day == n.Day && i.Month == n.Month) == 0), $"On-Dates-{string.Join("-", dates)}");
/// <summary>
/// On the specified days of the week
/// </summary>
/// <param name="days">The days.</param>
/// <returns></returns>
public DateComposite On(params DayOfWeek[] days) =>
new DateFunc(x => x.DoWhile(n => n.AddDays(1), n => !days.Contains(n.DayOfWeek)), $"On-Day-Of-Week-{string.Join("-", days)}");
/// <summary>
/// On the first trading day of the month
/// </summary>
/// <param name="exchangeModel">The exchangeModel.</param>
/// <returns></returns>
public DateComposite StartOfMonth(ExchangeModel exchangeModel) =>
new DateFunc(x =>
{
//Get the correct timezone for this exchange (input is utc)
x = x.ConvertTo(TimeZone.Utc, exchangeModel.TimeZone);
//Derive next date
var derived = new DateTime(x.Year, x.Month, 1).AddMonths(1)
.DoWhile(n => n.AddDays(1), i => !exchangeModel.IsOpenOnDate(i));
//return
return derived.ConvertTo(exchangeModel.TimeZone, TimeZone.Utc);
}, "Start-Of-Every-Month");
/// <summary>
/// On the first trading day of the specified month
/// </summary>
/// <param name="exchangeModel">The exchangeModel.</param>
/// <param name="month">The month.</param>
/// <returns></returns>
public DateComposite StartOfMonth(ExchangeModel exchangeModel, int month) =>
new DateFunc(x =>
{
//Get the correct timezone for this exchange (input is utc)
x = x.ConvertTo(TimeZone.Utc, exchangeModel.TimeZone);
//Derive next date
var derived = new DateTime(x.Month >= month ? x.Year + 1 : x.Year, 1, 1)
.DoWhile(n => n.AddDays(1), i => !exchangeModel.IsOpenOnDate(i) && i.Month != month);
//return
return derived.ConvertTo(exchangeModel.TimeZone, TimeZone.Utc);
}, $"Start-Of-{month}-Month");
/// <summary>
/// On the first trading day of the week
/// </summary>
/// <param name="exchangeModel">The exchangeModel.</param>
/// <returns></returns>
public DateComposite StartOfWeek(ExchangeModel exchangeModel) =>
new DateFunc(x =>
{
//Get the correct timezone for this exchange (input is utc)
x = x.ConvertTo(TimeZone.Utc, exchangeModel.TimeZone);
//Derive next date
var derived = x.AddDays(7).AddDays(DayOfWeek.Monday - x.DayOfWeek)
.DoWhile(n => n.AddDays(1), n => !exchangeModel.IsOpenOnDate(n));
//return
return derived.ConvertTo(exchangeModel.TimeZone, TimeZone.Utc);
}, "Start-Of-Every-Week");
#endregion Public Methods
}
} | Java |
/*
* Copyright 2011-2015 The Trustees of the University of Pennsylvania
*
* 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 edu.upenn.library.xmlaminar.parallel;
import static edu.upenn.library.xmlaminar.parallel.JoiningXMLFilter.GROUP_BY_SYSTEMID_FEATURE_NAME;
import edu.upenn.library.xmlaminar.parallel.callback.OutputCallback;
import edu.upenn.library.xmlaminar.parallel.callback.StdoutCallback;
import edu.upenn.library.xmlaminar.parallel.callback.XMLReaderCallback;
import edu.upenn.library.xmlaminar.VolatileSAXSource;
import edu.upenn.library.xmlaminar.VolatileXMLFilterImpl;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.Iterator;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import javax.xml.transform.sax.SAXSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.helpers.XMLFilterImpl;
/**
*
* @author Michael Gibney
*/
public class SplittingXMLFilter extends QueueSourceXMLFilter implements OutputCallback {
private static final Logger LOG = LoggerFactory.getLogger(SplittingXMLFilter.class);
private final AtomicBoolean parsing = new AtomicBoolean(false);
private volatile Future<?> consumerTask;
private int level = -1;
private int startEventLevel = -1;
private final ArrayDeque<StructuralStartEvent> startEventStack = new ArrayDeque<StructuralStartEvent>();
public static void main(String[] args) throws Exception {
LevelSplittingXMLFilter sxf = new LevelSplittingXMLFilter();
sxf.setChunkSize(1);
sxf.setOutputCallback(new StdoutCallback());
sxf.setInputType(InputType.indirect);
sxf.parse(new InputSource("../cli/whole-indirect.txt"));
}
public void ensureCleanInitialState() {
if (level != -1) {
throw new IllegalStateException("level != -1: "+level);
}
if (startEventLevel != -1) {
throw new IllegalStateException("startEventLevel != -1: "+startEventLevel);
}
if (!startEventStack.isEmpty()) {
throw new IllegalStateException("startEventStack not empty: "+startEventStack.size());
}
if (parsing.get()) {
throw new IllegalStateException("already parsing");
}
if (consumerTask != null) {
throw new IllegalStateException("consumerTask not null");
}
if (producerThrowable != null || consumerThrowable != null) {
throw new IllegalStateException("throwable not null: "+producerThrowable+", "+consumerThrowable);
}
int arrived;
if ((arrived = parseBeginPhaser.getArrivedParties()) > 0) {
throw new IllegalStateException("parseBeginPhaser arrived count: "+arrived);
}
if ((arrived = parseEndPhaser.getArrivedParties()) > 0) {
throw new IllegalStateException("parseEndPhaser arrived count: "+arrived);
}
if ((arrived = parseChunkDonePhaser.getArrivedParties()) > 0) {
throw new IllegalStateException("parseChunkDonePhaser arrived count: "+arrived);
}
}
@Override
protected void initialParse(VolatileSAXSource in) {
synchronousParser.setParent(this);
setupParse(in.getInputSource());
}
@Override
protected void repeatParse(VolatileSAXSource in) {
reset(false);
setupParse(in.getInputSource());
}
private void setupParse(InputSource in) {
setContentHandler(synchronousParser);
if (!parsing.compareAndSet(false, true)) {
throw new IllegalStateException("failed setting parsing = true");
}
OutputLooper outputLoop = new OutputLooper(in, null, Thread.currentThread());
consumerTask = getExecutor().submit(outputLoop);
}
@Override
protected void finished() throws SAXException {
reset(false);
}
public void reset() {
try {
setFeature(RESET_PROPERTY_NAME, true);
} catch (SAXException ex) {
throw new AssertionError(ex);
}
}
protected void reset(boolean cancel) {
try {
if (consumerTask != null) {
if (cancel) {
consumerTask.cancel(true);
} else {
consumerTask.get();
}
}
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
} catch (ExecutionException ex) {
throw new RuntimeException(ex);
}
consumerTask = null;
consumerThrowable = null;
producerThrowable = null;
if (splitDirector != null) {
splitDirector.reset();
}
startEventStack.clear();
if (!parsing.compareAndSet(false, false) && !cancel) {
LOG.warn("at {}.reset(), parsing had been set to true", SplittingXMLFilter.class.getName(), new IllegalStateException());
}
}
@Override
public void setFeature(String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException {
if (RESET_PROPERTY_NAME.equals(name) && value) {
try {
super.setFeature(name, value);
} catch (SAXException ex) {
/*
* could run here if only want to run if deepest resettable parent.
* ... but I don't think that's the case here.
*/
}
/*
* reset(false) because the downstream consumer thread issued this
* reset request (initiated the interruption).
*/
reset(true);
} else {
super.setFeature(name, value);
}
}
@Override
public boolean getFeature(String name) throws SAXNotRecognizedException, SAXNotSupportedException {
if (RESET_PROPERTY_NAME.equals(name)) {
try {
return super.getFeature(name) && consumerTask == null;
} catch (SAXException ex) {
return consumerTask == null;
}
} else if (GROUP_BY_SYSTEMID_FEATURE_NAME.equals(name)) {
return false;
}else {
return super.getFeature(name);
}
}
private final SynchronousParser synchronousParser = new SynchronousParser();
@Override
public boolean allowOutputCallback() {
return true;
}
private class SynchronousParser extends VolatileXMLFilterImpl {
@Override
public void parse(InputSource input) throws SAXException, IOException {
parse();
}
@Override
public void parse(String systemId) throws SAXException, IOException {
parse();
}
private void parse() throws SAXException, IOException {
parseBeginPhaser.arrive();
try {
parseEndPhaser.awaitAdvanceInterruptibly(parseEndPhaser.arrive());
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
parseChunkDonePhaser.arrive();
}
}
private final Phaser parseBeginPhaser = new Phaser(2);
private final Phaser parseEndPhaser = new Phaser(2);
private final Phaser parseChunkDonePhaser = new Phaser(2);
private class OutputLooper implements Runnable {
private final InputSource input;
private final String systemId;
private final Thread producer;
private OutputLooper(InputSource in, String systemId, Thread producer) {
this.input = in;
this.systemId = systemId;
this.producer = producer;
}
private void parseLoop(InputSource input, String systemId) throws SAXException, IOException {
if (input != null) {
while (parsing.get()) {
outputCallback.callback(new VolatileSAXSource(synchronousParser, input));
try {
parseChunkDonePhaser.awaitAdvanceInterruptibly(parseChunkDonePhaser.arrive());
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
}
} else {
throw new NullPointerException("null InputSource");
}
}
@Override
public void run() {
try {
parseLoop(input, systemId);
} catch (Throwable t) {
if (producerThrowable == null) {
consumerThrowable = t;
producer.interrupt();
} else {
t = producerThrowable;
producerThrowable = null;
throw new RuntimeException(t);
}
}
}
}
@Override
public void parse(InputSource input) throws SAXException, IOException {
parse(input, null);
}
@Override
public void parse(String systemId) throws SAXException, IOException {
parse(null, systemId);
}
private void parse(InputSource input, String systemId) {
try {
if (input != null) {
super.parse(input);
} else {
super.parse(systemId);
}
} catch (Throwable t) {
try {
if (consumerThrowable == null) {
producerThrowable = t;
reset(true);
} else {
t = consumerThrowable;
consumerThrowable = null;
}
} finally {
if (outputCallback != null) {
outputCallback.finished(t);
}
throw new RuntimeException(t);
}
}
outputCallback.finished(null);
}
@Override
public XMLReaderCallback getOutputCallback() {
return outputCallback;
}
@Override
public void setOutputCallback(XMLReaderCallback xmlReaderCallback) {
this.outputCallback = xmlReaderCallback;
}
private volatile XMLReaderCallback outputCallback;
private volatile Throwable consumerThrowable;
private volatile Throwable producerThrowable;
@Override
public void startDocument() throws SAXException {
try {
parseBeginPhaser.awaitAdvanceInterruptibly(parseBeginPhaser.arrive());
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
startEventStack.push(new StructuralStartEvent());
super.startDocument();
level++;
startEventLevel++;
}
@Override
public void endDocument() throws SAXException {
startEventLevel--;
level--;
super.endDocument();
startEventStack.pop();
if (!parsing.compareAndSet(true, false)) {
throw new IllegalStateException("failed at endDocument setting parsing = false");
}
parseEndPhaser.arrive();
}
private int bypassLevel = Integer.MAX_VALUE;
private int bypassStartEventLevel = Integer.MAX_VALUE;
protected final void split() throws SAXException {
writeSyntheticEndEvents();
parseEndPhaser.arrive();
try {
parseBeginPhaser.awaitAdvanceInterruptibly(parseBeginPhaser.arrive());
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
writeSyntheticStartEvents();
}
private void writeSyntheticEndEvents() throws SAXException {
Iterator<StructuralStartEvent> iter = startEventStack.iterator();
while (iter.hasNext()) {
StructuralStartEvent next = iter.next();
switch (next.type) {
case DOCUMENT:
super.endDocument();
break;
case PREFIX_MAPPING:
super.endPrefixMapping(next.one);
break;
case ELEMENT:
super.endElement(next.one, next.two, next.three);
}
}
}
private void writeSyntheticStartEvents() throws SAXException {
Iterator<StructuralStartEvent> iter = startEventStack.descendingIterator();
while (iter.hasNext()) {
StructuralStartEvent next = iter.next();
switch (next.type) {
case DOCUMENT:
super.startDocument();
break;
case PREFIX_MAPPING:
super.startPrefixMapping(next.one, next.two);
break;
case ELEMENT:
super.startElement(next.one, next.two, next.three, next.atts);
}
}
}
private SplitDirector splitDirector = new SplitDirector();
public SplitDirector getSplitDirector() {
return splitDirector;
}
public void setSplitDirector(SplitDirector splitDirector) {
this.splitDirector = splitDirector;
}
@Override
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
if (level < bypassLevel && handleDirective(splitDirector.startElement(uri, localName, qName, atts, level))) {
startEventStack.push(new StructuralStartEvent(uri, localName, qName, atts));
}
super.startElement(uri, localName, qName, atts);
level++;
startEventLevel++;
}
@Override
public void startPrefixMapping(String prefix, String uri) throws SAXException {
if (level < bypassLevel && handleDirective(splitDirector.startPrefixMapping(prefix, uri, level))) {
startEventStack.push(new StructuralStartEvent(prefix, uri));
}
super.startPrefixMapping(prefix, uri);
startEventLevel++;
}
/**
* Returns true if the generating event should be added to
* the startEvent stack
* @param directive
* @return
* @throws SAXException
*/
private boolean handleDirective(SplitDirective directive) throws SAXException {
switch (directive) {
case SPLIT:
bypassLevel = level;
bypassStartEventLevel = startEventLevel;
split();
return false;
case SPLIT_NO_BYPASS:
split();
return true;
case NO_SPLIT_BYPASS:
bypassLevel = level;
bypassStartEventLevel = startEventLevel;
return false;
case NO_SPLIT:
return true;
default:
throw new AssertionError();
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
startEventLevel--;
level--;
super.endElement(uri, localName, qName);
if (handleStructuralEndEvent()) {
handleDirective(splitDirector.endElement(uri, localName, qName, level));
}
}
private boolean handleStructuralEndEvent() {
if (level > bypassLevel) {
return false;
} else if (level < bypassLevel) {
startEventStack.pop();
return true;
} else {
if (startEventLevel == bypassStartEventLevel) {
bypassEnd();
return true;
} else if (startEventLevel < bypassStartEventLevel) {
startEventStack.pop();
return true;
} else {
return false;
}
}
}
@Override
public void endPrefixMapping(String prefix) throws SAXException {
startEventLevel--;
super.endPrefixMapping(prefix);
if (handleStructuralEndEvent()) {
handleDirective(splitDirector.endPrefixMapping(prefix, level));
}
}
private void bypassEnd() {
bypassLevel = Integer.MAX_VALUE;
bypassStartEventLevel = Integer.MAX_VALUE;
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (level <= bypassLevel) {
handleDirective(splitDirector.characters(ch, start, length, level));
}
super.characters(ch, start, length);
}
@Override
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
if (level <= bypassLevel) {
handleDirective(splitDirector.ignorableWhitespace(ch, start, length, level));
}
super.ignorableWhitespace(ch, start, length);
}
@Override
public void skippedEntity(String name) throws SAXException {
if (level <= bypassLevel) {
handleDirective(splitDirector.skippedEntity(name, level));
}
super.skippedEntity(name);
}
public static enum SplitDirective { SPLIT, NO_SPLIT, SPLIT_NO_BYPASS, NO_SPLIT_BYPASS }
public static class SplitDirector {
public void reset() {
// default NOOP implementation
}
public SplitDirective startPrefixMapping(String prefix, String uri, int level) throws SAXException {
return SplitDirective.NO_SPLIT;
}
public SplitDirective endPrefixMapping(String prefix, int level) throws SAXException {
return SplitDirective.NO_SPLIT;
}
public SplitDirective startElement(String uri, String localName, String qName, Attributes atts, int level) throws SAXException {
return SplitDirective.NO_SPLIT;
}
public SplitDirective endElement(String uri, String localName, String qName, int level) throws SAXException {
return SplitDirective.NO_SPLIT;
}
public SplitDirective characters(char[] ch, int start, int length, int level) throws SAXException {
return SplitDirective.NO_SPLIT;
}
public SplitDirective ignorableWhitespace(char[] ch, int start, int length, int level) throws SAXException {
return SplitDirective.NO_SPLIT;
}
public SplitDirective skippedEntity(String name, int level) throws SAXException {
return SplitDirective.NO_SPLIT;
}
}
}
| Java |
---
title: True Contentment
subblog: yhwh
tags: the good life
---
Contentment is fairly universally agreed to be a virtue. We aspire to the ideal that regardless of our circumstances we are happy, and we understand that without a measure of this virtue there is no set of circumstances that will satisfy us.
But what does contentment look like? I find if I'm not careful, what seems like contentment is dangerously near to disillusionment and existential despair.
<!-- MORE -->
I had a brush with death about a year ago. I woke up in the hospital one day with a frightening litany of injuries. As it happened I was fine within a couple of weeks, but it's easy to imagine rolling those dice again and being maimed or killed.
This experience drove home to me a few beliefs about life I already held in theory, but perhaps not to my core. First, sure as Saturday, death is coming, and we are powerless to ferry our souls across that mortal gap. Second, the Resurrection is coming, and in Jesus we look forward to eternal life that will dwarf our lives on Earth just as they dwarf the time we spent in the womb.
<pre class="prose">
Who shall separate us from the love of Christ? Shall tribulation, or distress, or persecution, or famine, or nakedness, or danger, or sword? As it is written,
“For your sake we are being killed all the day long;
we are regarded as sheep to be slaughtered.”
No, in all these things we are more than conquerors through him who loved us. For I am sure that neither death nor life, nor angels nor rulers, nor things present nor things to come, nor powers, nor height nor depth, nor anything else in all creation, will be able to separate us from the love of God in Christ Jesus our Lord.
Romans 8:35-39
</pre>
There's the source of contentment for you. Nothing can keep us from so great a salvation, so no lack ought bring us fear. Moreover, what could add to these riches? Naked we came into this world and naked we shall depart, but even if we could bring all with us it would amount to nothing in comparison to what we have already been guaranteed.
But this raises a question: Now what? How then shall we live? Well, our lives are to be a living sacrifice offered in thanksgiving to our adopted Father. But for the recipients of so great a salvation, this is way harder than you might think!
Where I have recently fallen short in this regard actually approximates a Buddhist idea more than a Christian one. This is the elimination of desire. Nothing can happen to me, so nothing matters, right? If I lost my life, ultimately it wouldn't matter, so certainly if I lost my job, it wouldn't matter. Whatever happens, I am secure. I lack nothing, so I desire nothing, so I care about nothing. Really, I might as well die and do away with this wearisome waiting.
This outlook lends itself to a life of poverty and withdrawal. We'll get by on what the Lord provides and make music to him, patiently awaiting his day. Some outsiders will come and see our peace and want it for themselves. We'll invite them, too, to renounce all that ensnares and to join us in our contentment. Most people just won't notice, but we won't mind.
Maybe some Christians are called to live that way, but here's the thing: it's not up to us how we live. Our lives are not our own. They've been bought at great price. If we are content to take the guarantee of our eternal security and to sit on it until it comes, we ought to seriously question whether indeed we have received it.
Salvation comes through faith. Faith leads to repentance and the surrender of our whole selves. These are returned to us animated by the Holy Spirit of God, for good works to the praise of his glory, until he returns or calls us home. There's a reason Paul mentions "tribulation, or distress, or persecution, or famine, or nakedness, or danger, or sword." These are what we ought to expect the Spirit will lead us into! Knowing this, we are content to follow him, though we know not what will come.
Lord, may I internalize this, too. Fill me with your Spirit, that in my days I will be more than the drifting dude!
| Java |
// <copyright file="BatchModeBuffer.cs" company="ClrCoder project">
// Copyright (c) ClrCoder project. All rights reserved.
// Licensed under the Apache 2.0 license. See LICENSE file in the project root for full license information.
// </copyright>
#if !NETSTANDARD1_0 && !NETSTANDARD1_1
namespace ClrCoder.Threading.Channels
{
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using JetBrains.Annotations;
/// <summary>
/// TODO: Implement and test me.
/// </summary>
/// <typeparam name="T"></typeparam>
public partial class BatchModeBuffer<T> : IDataFlowConsumer<T>, IDataFlowProducer<T>
{
private static readonly T[] EmptyBuffer = new T[0];
[CanBeNull]
private readonly object _syncRoot;
private readonly int _maxBufferLength;
private readonly int _minReadSize;
private readonly TimeSpan _maxReadAccumulationDelay;
private readonly Dictionary<int, LinkedListNode<SliceEntry>> _idToSliceEntries =
new Dictionary<int, LinkedListNode<SliceEntry>>();
private readonly LinkedList<SliceEntry> _sliceEntries = new LinkedList<SliceEntry>();
private readonly int _maxSliceLength;
private int _nextId = 0;
/// <summary>
/// </summary>
/// <param name="maxBufferLength"></param>
/// <param name="minReadSize"></param>
public BatchModeBuffer(
int maxBufferLength,
int minReadSize,
TimeSpan maxReadAccumulationDelay,
object syncRoot = null)
{
_maxBufferLength = maxBufferLength;
_minReadSize = minReadSize;
_maxReadAccumulationDelay = maxReadAccumulationDelay;
_syncRoot = syncRoot;
_maxSliceLength = Math.Max(512, _minReadSize);
}
private enum SliceEntryStatus
{
AllocatedForWrite,
Data,
AllocatedForRead
}
/// <inheritdoc/>
public IChannelReader<T> OpenReader()
{
throw new NotImplementedException();
}
/// <inheritdoc/>
public IChannelWriter<T> OpenWriter()
{
if (_syncRoot == null)
{
return new BatchModeBufferWriter<SyncFreeObject>(this, default);
}
return new BatchModeBufferWriter<MonitorSyncObject>(this, new MonitorSyncObject(_syncRoot));
}
private SliceEntry AllocateEmptyEntryAfter(LinkedListNode<SliceEntry> node)
{
var newEntry = new SliceEntry
{
Id = _nextId++
};
_sliceEntries.AddAfter(node, newEntry);
return newEntry;
}
private SliceEntry AllocateNewEntry()
{
var result = new SliceEntry
{
Buffer = new T[_maxSliceLength],
Status = SliceEntryStatus.Data,
Id = _nextId++
};
_idToSliceEntries.Add(result.Id, _sliceEntries.AddLast(result));
return result;
}
private void RemoveNode(LinkedListNode<SliceEntry> sliceEntryNode)
{
_idToSliceEntries.Remove(sliceEntryNode.Value.Id);
_sliceEntries.Remove(sliceEntryNode);
}
private Span<T> TryAllocateUnsafe(int amount)
{
// We don't check logical amount.
SliceEntry lastEntry = _sliceEntries.Last?.Value;
Span<T> result;
if ((lastEntry != null)
&& (lastEntry.Status == SliceEntryStatus.Data))
{
result = lastEntry.AllocateForWrite(amount);
if (result.Length != 0)
{
return result;
}
}
lastEntry = AllocateNewEntry();
return lastEntry.AllocateForWrite(amount);
}
private class SliceEntry
{
public int Id;
public T[] Buffer;
public int Start;
public int Length;
public SliceEntryStatus Status;
public int SpaceLeft => Buffer.Length - Start - Length;
public Span<T> AllocateForWrite(int maxAmount)
{
int writePosition = Start + Length;
int amount = Math.Min(Buffer.Length - writePosition, maxAmount);
Length += amount;
return new Span<T>(Buffer, writePosition, amount);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool TryWriteLast(T item)
{
bool result = false;
int writePosition = Start + Length;
if (writePosition < Buffer.Length)
{
Buffer[writePosition] = item;
Length++;
result = true;
}
return result;
}
}
}
}
#endif | Java |
package bamboo.crawl;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class RecordStats {
private static final Date MAX_TIME = new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(900));
private static final Date MIN_TIME = new Date(631152000000L);
private long records;
private long recordBytes;
private Date startTime = null;
private Date endTime = null;
public void update(long recordLength, Date time) {
records += 1;
recordBytes += recordLength;
if (time.after(MIN_TIME) && time.before(MAX_TIME)) {
if (startTime == null || time.before(startTime)) {
startTime = time;
}
if (endTime == null || time.after(endTime)) {
endTime = time;
}
}
}
public long getRecords() {
return records;
}
public long getRecordBytes() {
return recordBytes;
}
public Date getStartTime() {
return startTime;
}
public Date getEndTime() {
return endTime;
}
@Override
public String toString() {
return "RecordStats{" +
"records=" + records +
", recordBytes=" + recordBytes +
", startTime=" + startTime +
", endTime=" + endTime +
'}';
}
}
| Java |
---
layout: page
title: Think in java interview
subtitle: <span class="mega-octicon octicon-clippy"></span> Take notes about everything new
menu: interview
css: ['blog-page.css']
---
{% include interview.html %}
| Java |
package com.example.nm_gql_go_link_example;
import io.flutter.embedding.android.FlutterActivity;
public class MainActivity extends FlutterActivity {
}
| Java |
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014-2020 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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.
*/
(function () {
'use strict';
var module = angular.module('pnc.common.restclient', [
'ngResource',
'pnc.common.util',
]);
// TODO: Remove this unnecessary layer of indirection.
module.factory('REST_BASE_URL', [
'restConfig',
function(restConfig) {
return restConfig.getPncUrl();
}
]);
module.factory('REST_BASE_REST_URL', [
'restConfig',
function(restConfig) {
return restConfig.getPncRestUrl();
}
]);
})();
| Java |
/*
* 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.hyracks.storage.am.lsm.invertedindex.util;
import java.util.List;
import org.apache.hyracks.api.comm.IFrameTupleAccessor;
import org.apache.hyracks.api.dataflow.value.IBinaryComparatorFactory;
import org.apache.hyracks.api.dataflow.value.ITypeTraits;
import org.apache.hyracks.api.exceptions.ErrorCode;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.api.io.FileReference;
import org.apache.hyracks.api.io.IIOManager;
import org.apache.hyracks.storage.am.bloomfilter.impls.BloomFilterFactory;
import org.apache.hyracks.storage.am.btree.frames.BTreeLeafFrameType;
import org.apache.hyracks.storage.am.btree.frames.BTreeNSMInteriorFrameFactory;
import org.apache.hyracks.storage.am.btree.tuples.BTreeTypeAwareTupleWriterFactory;
import org.apache.hyracks.storage.am.btree.util.BTreeUtils;
import org.apache.hyracks.storage.am.common.api.IMetadataPageManagerFactory;
import org.apache.hyracks.storage.am.common.api.IPageManager;
import org.apache.hyracks.storage.am.common.api.IPageManagerFactory;
import org.apache.hyracks.storage.am.common.api.ITreeIndexFrameFactory;
import org.apache.hyracks.storage.am.common.tuples.TypeAwareTupleWriterFactory;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMDiskComponentFactory;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMIOOperationCallbackFactory;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMIOOperationScheduler;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMMergePolicy;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMOperationTracker;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMPageWriteCallbackFactory;
import org.apache.hyracks.storage.am.lsm.common.api.IVirtualBufferCache;
import org.apache.hyracks.storage.am.lsm.common.frames.LSMComponentFilterFrameFactory;
import org.apache.hyracks.storage.am.lsm.common.impls.BTreeFactory;
import org.apache.hyracks.storage.am.lsm.common.impls.ComponentFilterHelper;
import org.apache.hyracks.storage.am.lsm.common.impls.LSMComponentFilterManager;
import org.apache.hyracks.storage.am.lsm.invertedindex.api.IInvertedListBuilder;
import org.apache.hyracks.storage.am.lsm.invertedindex.api.IInvertedListBuilderFactory;
import org.apache.hyracks.storage.am.lsm.invertedindex.api.IInvertedListTupleReference;
import org.apache.hyracks.storage.am.lsm.invertedindex.fulltext.IFullTextConfigEvaluatorFactory;
import org.apache.hyracks.storage.am.lsm.invertedindex.impls.LSMInvertedIndex;
import org.apache.hyracks.storage.am.lsm.invertedindex.impls.LSMInvertedIndexDiskComponentFactory;
import org.apache.hyracks.storage.am.lsm.invertedindex.impls.LSMInvertedIndexFileManager;
import org.apache.hyracks.storage.am.lsm.invertedindex.impls.PartitionedLSMInvertedIndex;
import org.apache.hyracks.storage.am.lsm.invertedindex.inmemory.InMemoryInvertedIndex;
import org.apache.hyracks.storage.am.lsm.invertedindex.inmemory.PartitionedInMemoryInvertedIndex;
import org.apache.hyracks.storage.am.lsm.invertedindex.ondisk.InvertedListBuilderFactory;
import org.apache.hyracks.storage.am.lsm.invertedindex.ondisk.OnDiskInvertedIndex;
import org.apache.hyracks.storage.am.lsm.invertedindex.ondisk.OnDiskInvertedIndexFactory;
import org.apache.hyracks.storage.am.lsm.invertedindex.ondisk.PartitionedOnDiskInvertedIndex;
import org.apache.hyracks.storage.am.lsm.invertedindex.ondisk.PartitionedOnDiskInvertedIndexFactory;
import org.apache.hyracks.storage.am.lsm.invertedindex.ondisk.fixedsize.FixedSizeElementInvertedListBuilder;
import org.apache.hyracks.storage.am.lsm.invertedindex.ondisk.fixedsize.FixedSizeInvertedListSearchResultFrameTupleAccessor;
import org.apache.hyracks.storage.am.lsm.invertedindex.ondisk.fixedsize.FixedSizeInvertedListTupleReference;
import org.apache.hyracks.storage.am.lsm.invertedindex.ondisk.variablesize.VariableSizeInvertedListSearchResultFrameTupleAccessor;
import org.apache.hyracks.storage.am.lsm.invertedindex.ondisk.variablesize.VariableSizeInvertedListTupleReference;
import org.apache.hyracks.storage.am.lsm.invertedindex.tokenizers.IBinaryTokenizerFactory;
import org.apache.hyracks.storage.common.buffercache.IBufferCache;
import org.apache.hyracks.util.trace.ITracer;
public class InvertedIndexUtils {
public static final String EXPECT_ALL_FIX_GET_VAR_SIZE =
"expecting all type traits to be fixed-size while getting at least one variable-length one";
public static final String EXPECT_VAR_GET_ALL_FIX_SIZE =
"expecting at least one variable-size type trait while all are fixed-size";
public static InMemoryInvertedIndex createInMemoryBTreeInvertedindex(IBufferCache memBufferCache,
IPageManager virtualFreePageManager, ITypeTraits[] invListTypeTraits,
IBinaryComparatorFactory[] invListCmpFactories, ITypeTraits[] tokenTypeTraits,
IBinaryComparatorFactory[] tokenCmpFactories, IBinaryTokenizerFactory tokenizerFactory,
IFullTextConfigEvaluatorFactory fullTextConfigEvaluatorFactory, FileReference btreeFileRef)
throws HyracksDataException {
return new InMemoryInvertedIndex(memBufferCache, virtualFreePageManager, invListTypeTraits, invListCmpFactories,
tokenTypeTraits, tokenCmpFactories, tokenizerFactory, fullTextConfigEvaluatorFactory, btreeFileRef);
}
public static InMemoryInvertedIndex createPartitionedInMemoryBTreeInvertedindex(IBufferCache memBufferCache,
IPageManager virtualFreePageManager, ITypeTraits[] invListTypeTraits,
IBinaryComparatorFactory[] invListCmpFactories, ITypeTraits[] tokenTypeTraits,
IBinaryComparatorFactory[] tokenCmpFactories, IBinaryTokenizerFactory tokenizerFactory,
IFullTextConfigEvaluatorFactory fullTextConfigEvaluatorFactory, FileReference btreeFileRef)
throws HyracksDataException {
return new PartitionedInMemoryInvertedIndex(memBufferCache, virtualFreePageManager, invListTypeTraits,
invListCmpFactories, tokenTypeTraits, tokenCmpFactories, tokenizerFactory,
fullTextConfigEvaluatorFactory, btreeFileRef);
}
public static OnDiskInvertedIndex createOnDiskInvertedIndex(IIOManager ioManager, IBufferCache bufferCache,
ITypeTraits[] invListTypeTraits, IBinaryComparatorFactory[] invListCmpFactories,
ITypeTraits[] tokenTypeTraits, IBinaryComparatorFactory[] tokenCmpFactories, FileReference invListsFile,
IPageManagerFactory pageManagerFactory) throws HyracksDataException {
IInvertedListBuilder builder = new FixedSizeElementInvertedListBuilder(invListTypeTraits);
FileReference btreeFile = getBTreeFile(ioManager, invListsFile);
return new OnDiskInvertedIndex(bufferCache, builder, invListTypeTraits, invListCmpFactories, tokenTypeTraits,
tokenCmpFactories, btreeFile, invListsFile, pageManagerFactory);
}
public static PartitionedOnDiskInvertedIndex createPartitionedOnDiskInvertedIndex(IIOManager ioManager,
IBufferCache bufferCache, ITypeTraits[] invListTypeTraits, IBinaryComparatorFactory[] invListCmpFactories,
ITypeTraits[] tokenTypeTraits, IBinaryComparatorFactory[] tokenCmpFactories, FileReference invListsFile,
IPageManagerFactory pageManagerFactory) throws HyracksDataException {
IInvertedListBuilder builder = new FixedSizeElementInvertedListBuilder(invListTypeTraits);
FileReference btreeFile = getBTreeFile(ioManager, invListsFile);
return new PartitionedOnDiskInvertedIndex(bufferCache, builder, invListTypeTraits, invListCmpFactories,
tokenTypeTraits, tokenCmpFactories, btreeFile, invListsFile, pageManagerFactory);
}
public static FileReference getBTreeFile(IIOManager ioManager, FileReference invListsFile)
throws HyracksDataException {
return ioManager.resolveAbsolutePath(invListsFile.getFile().getPath() + "_btree");
}
public static BTreeFactory createDeletedKeysBTreeFactory(IIOManager ioManager, ITypeTraits[] invListTypeTraits,
IBinaryComparatorFactory[] invListCmpFactories, IBufferCache diskBufferCache,
IPageManagerFactory freePageManagerFactory) throws HyracksDataException {
BTreeTypeAwareTupleWriterFactory tupleWriterFactory =
new BTreeTypeAwareTupleWriterFactory(invListTypeTraits, false);
ITreeIndexFrameFactory leafFrameFactory =
BTreeUtils.getLeafFrameFactory(tupleWriterFactory, BTreeLeafFrameType.REGULAR_NSM);
ITreeIndexFrameFactory interiorFrameFactory = new BTreeNSMInteriorFrameFactory(tupleWriterFactory);
return new BTreeFactory(ioManager, diskBufferCache, freePageManagerFactory, interiorFrameFactory,
leafFrameFactory, invListCmpFactories, invListCmpFactories.length);
}
public static LSMInvertedIndex createLSMInvertedIndex(IIOManager ioManager,
List<IVirtualBufferCache> virtualBufferCaches, ITypeTraits[] invListTypeTraits,
IBinaryComparatorFactory[] invListCmpFactories, ITypeTraits[] tokenTypeTraits,
IBinaryComparatorFactory[] tokenCmpFactories, IBinaryTokenizerFactory tokenizerFactory,
IFullTextConfigEvaluatorFactory fullTextConfigEvaluatorFactory, IBufferCache diskBufferCache,
String absoluteOnDiskDir, double bloomFilterFalsePositiveRate, ILSMMergePolicy mergePolicy,
ILSMOperationTracker opTracker, ILSMIOOperationScheduler ioScheduler,
ILSMIOOperationCallbackFactory ioOpCallbackFactory, ILSMPageWriteCallbackFactory pageWriteCallbackFactory,
int[] invertedIndexFields, ITypeTraits[] filterTypeTraits, IBinaryComparatorFactory[] filterCmpFactories,
int[] filterFields, int[] filterFieldsForNonBulkLoadOps, int[] invertedIndexFieldsForNonBulkLoadOps,
boolean durable, IMetadataPageManagerFactory pageManagerFactory, ITracer tracer)
throws HyracksDataException {
BTreeFactory deletedKeysBTreeFactory = createDeletedKeysBTreeFactory(ioManager, invListTypeTraits,
invListCmpFactories, diskBufferCache, pageManagerFactory);
int[] bloomFilterKeyFields = new int[invListCmpFactories.length];
for (int i = 0; i < invListCmpFactories.length; i++) {
bloomFilterKeyFields[i] = i;
}
BloomFilterFactory bloomFilterFactory = new BloomFilterFactory(diskBufferCache, bloomFilterKeyFields);
FileReference onDiskDirFileRef = ioManager.resolveAbsolutePath(absoluteOnDiskDir);
LSMInvertedIndexFileManager fileManager =
new LSMInvertedIndexFileManager(ioManager, onDiskDirFileRef, deletedKeysBTreeFactory);
IInvertedListBuilderFactory invListBuilderFactory =
new InvertedListBuilderFactory(tokenTypeTraits, invListTypeTraits);
OnDiskInvertedIndexFactory invIndexFactory =
new OnDiskInvertedIndexFactory(ioManager, diskBufferCache, invListBuilderFactory, invListTypeTraits,
invListCmpFactories, tokenTypeTraits, tokenCmpFactories, fileManager, pageManagerFactory);
ComponentFilterHelper filterHelper = null;
LSMComponentFilterFrameFactory filterFrameFactory = null;
LSMComponentFilterManager filterManager = null;
if (filterCmpFactories != null) {
TypeAwareTupleWriterFactory filterTupleWriterFactory = new TypeAwareTupleWriterFactory(filterTypeTraits);
filterHelper = new ComponentFilterHelper(filterTupleWriterFactory, filterCmpFactories);
filterFrameFactory = new LSMComponentFilterFrameFactory(filterTupleWriterFactory);
filterManager = new LSMComponentFilterManager(filterFrameFactory);
}
ILSMDiskComponentFactory componentFactory = new LSMInvertedIndexDiskComponentFactory(invIndexFactory,
deletedKeysBTreeFactory, bloomFilterFactory, filterHelper);
return new LSMInvertedIndex(ioManager, virtualBufferCaches, componentFactory, filterHelper, filterFrameFactory,
filterManager, bloomFilterFalsePositiveRate, diskBufferCache, fileManager, invListTypeTraits,
invListCmpFactories, tokenTypeTraits, tokenCmpFactories, tokenizerFactory,
fullTextConfigEvaluatorFactory, mergePolicy, opTracker, ioScheduler, ioOpCallbackFactory,
pageWriteCallbackFactory, invertedIndexFields, filterFields, filterFieldsForNonBulkLoadOps,
invertedIndexFieldsForNonBulkLoadOps, durable, tracer);
}
public static PartitionedLSMInvertedIndex createPartitionedLSMInvertedIndex(IIOManager ioManager,
List<IVirtualBufferCache> virtualBufferCaches, ITypeTraits[] invListTypeTraits,
IBinaryComparatorFactory[] invListCmpFactories, ITypeTraits[] tokenTypeTraits,
IBinaryComparatorFactory[] tokenCmpFactories, IBinaryTokenizerFactory tokenizerFactory,
IFullTextConfigEvaluatorFactory fullTextConfigEvaluatorFactory, IBufferCache diskBufferCache,
String absoluteOnDiskDir, double bloomFilterFalsePositiveRate, ILSMMergePolicy mergePolicy,
ILSMOperationTracker opTracker, ILSMIOOperationScheduler ioScheduler,
ILSMIOOperationCallbackFactory ioOpCallbackFactory, ILSMPageWriteCallbackFactory pageWriteCallbackFactory,
int[] invertedIndexFields, ITypeTraits[] filterTypeTraits, IBinaryComparatorFactory[] filterCmpFactories,
int[] filterFields, int[] filterFieldsForNonBulkLoadOps, int[] invertedIndexFieldsForNonBulkLoadOps,
boolean durable, IPageManagerFactory pageManagerFactory, ITracer tracer) throws HyracksDataException {
BTreeFactory deletedKeysBTreeFactory = createDeletedKeysBTreeFactory(ioManager, invListTypeTraits,
invListCmpFactories, diskBufferCache, pageManagerFactory);
int[] bloomFilterKeyFields = new int[invListCmpFactories.length];
for (int i = 0; i < invListCmpFactories.length; i++) {
bloomFilterKeyFields[i] = i;
}
BloomFilterFactory bloomFilterFactory = new BloomFilterFactory(diskBufferCache, bloomFilterKeyFields);
FileReference onDiskDirFileRef = ioManager.resolveAbsolutePath(absoluteOnDiskDir);
LSMInvertedIndexFileManager fileManager =
new LSMInvertedIndexFileManager(ioManager, onDiskDirFileRef, deletedKeysBTreeFactory);
IInvertedListBuilderFactory invListBuilderFactory =
new InvertedListBuilderFactory(tokenTypeTraits, invListTypeTraits);
PartitionedOnDiskInvertedIndexFactory invIndexFactory = new PartitionedOnDiskInvertedIndexFactory(ioManager,
diskBufferCache, invListBuilderFactory, invListTypeTraits, invListCmpFactories, tokenTypeTraits,
tokenCmpFactories, fileManager, pageManagerFactory);
ComponentFilterHelper filterHelper = null;
LSMComponentFilterFrameFactory filterFrameFactory = null;
LSMComponentFilterManager filterManager = null;
if (filterCmpFactories != null) {
TypeAwareTupleWriterFactory filterTupleWriterFactory = new TypeAwareTupleWriterFactory(filterTypeTraits);
filterHelper = new ComponentFilterHelper(filterTupleWriterFactory, filterCmpFactories);
filterFrameFactory = new LSMComponentFilterFrameFactory(filterTupleWriterFactory);
filterManager = new LSMComponentFilterManager(filterFrameFactory);
}
ILSMDiskComponentFactory componentFactory = new LSMInvertedIndexDiskComponentFactory(invIndexFactory,
deletedKeysBTreeFactory, bloomFilterFactory, filterHelper);
return new PartitionedLSMInvertedIndex(ioManager, virtualBufferCaches, componentFactory, filterHelper,
filterFrameFactory, filterManager, bloomFilterFalsePositiveRate, diskBufferCache, fileManager,
invListTypeTraits, invListCmpFactories, tokenTypeTraits, tokenCmpFactories, tokenizerFactory,
fullTextConfigEvaluatorFactory, mergePolicy, opTracker, ioScheduler, ioOpCallbackFactory,
pageWriteCallbackFactory, invertedIndexFields, filterFields, filterFieldsForNonBulkLoadOps,
invertedIndexFieldsForNonBulkLoadOps, durable, tracer);
}
public static boolean checkTypeTraitsAllFixed(ITypeTraits[] typeTraits) {
for (int i = 0; i < typeTraits.length; i++) {
if (!typeTraits[i].isFixedLength()) {
return false;
}
}
return true;
}
public static void verifyAllFixedSizeTypeTrait(ITypeTraits[] typeTraits) throws HyracksDataException {
if (InvertedIndexUtils.checkTypeTraitsAllFixed(typeTraits) == false) {
throw HyracksDataException.create(ErrorCode.INVALID_INVERTED_LIST_TYPE_TRAITS,
InvertedIndexUtils.EXPECT_ALL_FIX_GET_VAR_SIZE);
}
}
public static void verifyHasVarSizeTypeTrait(ITypeTraits[] typeTraits) throws HyracksDataException {
if (InvertedIndexUtils.checkTypeTraitsAllFixed(typeTraits) == true) {
throw HyracksDataException.create(ErrorCode.INVALID_INVERTED_LIST_TYPE_TRAITS,
InvertedIndexUtils.EXPECT_VAR_GET_ALL_FIX_SIZE);
}
}
public static IInvertedListTupleReference createInvertedListTupleReference(ITypeTraits[] typeTraits)
throws HyracksDataException {
if (checkTypeTraitsAllFixed(typeTraits)) {
return new FixedSizeInvertedListTupleReference(typeTraits);
} else {
return new VariableSizeInvertedListTupleReference(typeTraits);
}
}
public static IFrameTupleAccessor createInvertedListFrameTupleAccessor(int frameSize, ITypeTraits[] typeTraits)
throws HyracksDataException {
if (checkTypeTraitsAllFixed(typeTraits)) {
return new FixedSizeInvertedListSearchResultFrameTupleAccessor(frameSize, typeTraits);
} else {
return new VariableSizeInvertedListSearchResultFrameTupleAccessor(frameSize, typeTraits);
}
}
public static void setInvertedListFrameEndOffset(byte[] bytes, int pos) {
int off = bytes.length - 4;
bytes[off++] = (byte) (pos >> 24);
bytes[off++] = (byte) (pos >> 16);
bytes[off++] = (byte) (pos >> 8);
bytes[off] = (byte) (pos);
}
public static int getInvertedListFrameEndOffset(byte[] bytes) {
int p = bytes.length - 4;
int offsetFrameEnd = 0;
for (int i = 0; i < 4; i++) {
offsetFrameEnd = (offsetFrameEnd << 8) + (bytes[p++] & 0xFF);
}
return offsetFrameEnd;
}
}
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_45) on Tue Apr 22 01:43:54 UTC 2014 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class org.apache.hadoop.hbase.avro.generated.AColumnValue (HBase 0.94.19 API)
</TITLE>
<META NAME="date" CONTENT="2014-04-22">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.hadoop.hbase.avro.generated.AColumnValue (HBase 0.94.19 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/hadoop/hbase/avro/generated/AColumnValue.html" title="class in org.apache.hadoop.hbase.avro.generated"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../index.html?org/apache/hadoop/hbase/avro/generated//class-useAColumnValue.html" target="_top"><B>FRAMES</B></A>
<A HREF="AColumnValue.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.hadoop.hbase.avro.generated.AColumnValue</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../../../../org/apache/hadoop/hbase/avro/generated/AColumnValue.html" title="class in org.apache.hadoop.hbase.avro.generated">AColumnValue</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.apache.hadoop.hbase.avro.generated"><B>org.apache.hadoop.hbase.avro.generated</B></A></TD>
<TD> </TD>
</TR>
</TABLE>
<P>
<A NAME="org.apache.hadoop.hbase.avro.generated"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../../../org/apache/hadoop/hbase/avro/generated/AColumnValue.html" title="class in org.apache.hadoop.hbase.avro.generated">AColumnValue</A> in <A HREF="../../../../../../../org/apache/hadoop/hbase/avro/generated/package-summary.html">org.apache.hadoop.hbase.avro.generated</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Fields in <A HREF="../../../../../../../org/apache/hadoop/hbase/avro/generated/package-summary.html">org.apache.hadoop.hbase.avro.generated</A> with type parameters of type <A HREF="../../../../../../../org/apache/hadoop/hbase/avro/generated/AColumnValue.html" title="class in org.apache.hadoop.hbase.avro.generated">AColumnValue</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="http://java.sun.com/javase/6/docs/api/java/util/List.html?is-external=true" title="class or interface in java.util">List</A><<A HREF="../../../../../../../org/apache/hadoop/hbase/avro/generated/AColumnValue.html" title="class in org.apache.hadoop.hbase.avro.generated">AColumnValue</A>></CODE></FONT></TD>
<TD><CODE><B>APut.</B><B><A HREF="../../../../../../../org/apache/hadoop/hbase/avro/generated/APut.html#columnValues">columnValues</A></B></CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/hadoop/hbase/avro/generated/AColumnValue.html" title="class in org.apache.hadoop.hbase.avro.generated"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../index.html?org/apache/hadoop/hbase/avro/generated//class-useAColumnValue.html" target="_top"><B>FRAMES</B></A>
<A HREF="AColumnValue.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2014 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All Rights Reserved.
</BODY>
</HTML>
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.