code
stringlengths 4
1.01M
| language
stringclasses 2
values |
---|---|
/*
* Copyright 2013-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cloudfoundry.util;
import org.cloudfoundry.client.v2.ClientV2Exception;
import reactor.core.publisher.Mono;
import java.util.Arrays;
import java.util.function.Predicate;
/**
* Utilities for dealing with {@link Exception}s
*/
public final class ExceptionUtils {
private ExceptionUtils() {
}
/**
* Returns a {@link Mono} containing an {@link IllegalArgumentException} with the configured message
*
* @param format A <a href="../util/Formatter.html#syntax">format string</a>
* @param args Arguments referenced by the format specifiers in the format string. If there are more arguments than format specifiers, the extra arguments are ignored. The number of arguments
* is variable and may be zero. The maximum number of arguments is limited by the maximum dimension of a Java array as defined by <cite>The Java™ Virtual Machine
* Specification</cite>. The behaviour on a {@code null} argument depends on the <a href="../util/Formatter.html#syntax">conversion</a>.
* @param <T> the type of the {@link Mono} being converted
* @return a {@link Mono} containing the error
*/
public static <T> Mono<T> illegalArgument(String format, Object... args) {
String message = String.format(format, args);
return Mono.error(new IllegalArgumentException(message));
}
/**
* Returns a {@link Mono} containing an {@link IllegalStateException} with the configured message
*
* @param format A <a href="../util/Formatter.html#syntax">format string</a>
* @param args Arguments referenced by the format specifiers in the format string. If there are more arguments than format specifiers, the extra arguments are ignored. The number of arguments
* is variable and may be zero. The maximum number of arguments is limited by the maximum dimension of a Java array as defined by <cite>The Java™ Virtual Machine
* Specification</cite>. The behaviour on a {@code null} argument depends on the <a href="../util/Formatter.html#syntax">conversion</a>.
* @param <T> the type of the {@link Mono} being converted
* @return a {@link Mono} containing the error
*/
public static <T> Mono<T> illegalState(String format, Object... args) {
String message = String.format(format, args);
return Mono.error(new IllegalStateException(message));
}
/**
* A predicate that returns {@code true} if the exception is a {@link ClientV2Exception} and its code matches expectation
*
* @param codes the codes to match
* @return {@code true} if the exception is a {@link ClientV2Exception} and its code matches
*/
public static Predicate<? super Throwable> statusCode(int... codes) {
return t -> t instanceof ClientV2Exception &&
Arrays.stream(codes).anyMatch(candidate -> ((ClientV2Exception) t).getCode().equals(candidate));
}
}
| Java |
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2021 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Simon Grätzer
////////////////////////////////////////////////////////////////////////////////
#pragma once
#include <set>
#include <map>
#include <velocypack/velocypack-aliases.h>
#include <algorithm>
#include "Basics/Common.h"
#include "Cluster/ClusterInfo.h"
#include "Pregel/Graph.h"
struct TRI_vocbase_t;
namespace arangodb {
namespace pregel {
template <typename V, typename E, typename M>
class Worker;
////////////////////////////////////////////////////////////////////////////////
/// @brief carry common parameters
////////////////////////////////////////////////////////////////////////////////
class WorkerConfig {
template <typename V, typename E, typename M>
friend class Worker;
public:
WorkerConfig(TRI_vocbase_t* vocbase, VPackSlice params);
void updateConfig(VPackSlice updated);
inline uint64_t executionNumber() const { return _executionNumber; }
inline uint64_t globalSuperstep() const { return _globalSuperstep; }
inline uint64_t localSuperstep() const { return _localSuperstep; }
inline bool asynchronousMode() const { return _asynchronousMode; }
inline bool useMemoryMaps() const { return _useMemoryMaps; }
inline uint64_t parallelism() const { return _parallelism; }
inline std::string const& coordinatorId() const { return _coordinatorId; }
inline TRI_vocbase_t* vocbase() const { return _vocbase; }
inline std::string const& database() const { return _vocbase->name(); }
// collection shards on this worker
inline std::map<CollectionID, std::vector<ShardID>> const& vertexCollectionShards() const {
return _vertexCollectionShards;
}
// collection shards on this worker
inline std::map<CollectionID, std::vector<ShardID>> const& edgeCollectionShards() const {
return _edgeCollectionShards;
}
inline std::unordered_map<CollectionID, std::string> const& collectionPlanIdMap() const {
return _collectionPlanIdMap;
}
std::string const& shardIDToCollectionName(ShardID const& shard) const {
auto const& it = _shardToCollectionName.find(shard);
if (it != _shardToCollectionName.end()) {
return it->second;
}
return StaticStrings::Empty;
}
// same content on every worker, has to stay equal!!!!
inline std::vector<ShardID> const& globalShardIDs() const {
return _globalShardIDs;
}
// convenvience access without guaranteed order, same values as in
// vertexCollectionShards
inline std::vector<ShardID> const& localVertexShardIDs() const {
return _localVertexShardIDs;
}
// convenvience access without guaranteed order, same values as in
// edgeCollectionShards
inline std::vector<ShardID> const& localEdgeShardIDs() const {
return _localEdgeShardIDs;
}
/// Actual set of pregel shard id's located here
inline std::set<PregelShard> const& localPregelShardIDs() const {
return _localPregelShardIDs;
}
inline PregelShard shardId(ShardID const& responsibleShard) const {
auto const& it = _pregelShardIDs.find(responsibleShard);
return it != _pregelShardIDs.end() ? it->second : InvalidPregelShard;
}
// index in globalShardIDs
inline bool isLocalVertexShard(PregelShard shardIndex) const {
// TODO cache this? prob small
return _localPShardIDs_hash.find(shardIndex) != _localPShardIDs_hash.end();
}
std::vector<ShardID> const& edgeCollectionRestrictions(ShardID const& shard) const;
// convert an arangodb document id to a pregel id
PregelID documentIdToPregel(std::string const& documentID) const;
private:
uint64_t _executionNumber = 0;
uint64_t _globalSuperstep = 0;
uint64_t _localSuperstep = 0;
/// Let async
bool _asynchronousMode = false;
bool _useMemoryMaps = false; /// always use mmaps
size_t _parallelism = 1;
std::string _coordinatorId;
TRI_vocbase_t* _vocbase;
std::vector<ShardID> _globalShardIDs;
std::vector<ShardID> _localVertexShardIDs, _localEdgeShardIDs;
std::unordered_map<std::string, std::string> _collectionPlanIdMap;
std::map<ShardID, std::string> _shardToCollectionName;
// Map from edge collection to their shards, only iterated over keep sorted
std::map<CollectionID, std::vector<ShardID>> _vertexCollectionShards, _edgeCollectionShards;
std::unordered_map<CollectionID, std::vector<ShardID>> _edgeCollectionRestrictions;
/// cache these ids as much as possible, since we access them often
std::unordered_map<std::string, PregelShard> _pregelShardIDs;
std::set<PregelShard> _localPregelShardIDs;
std::unordered_set<PregelShard> _localPShardIDs_hash;
};
} // namespace pregel
} // namespace arangodb
| Java |
/*
* Copyright 2012-2014 MarkLogic 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.marklogic.samplestack.web.security;
import java.io.IOException;
import java.io.Writer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import com.marklogic.samplestack.web.JsonHttpResponse;
@Component
/**
* Class to customize the default Login handling. Rather than redirection
* to a login form, Samplestack simply denies access
* (where authentication is required)
*/
public class SamplestackAuthenticationEntryPoint implements
AuthenticationEntryPoint {
@Autowired
private JsonHttpResponse errors;
@Override
/**
* Override handler that returns 401 for any unauthenticated
* request to a secured endpoint.
*/
public void commence(HttpServletRequest request,
HttpServletResponse response, AuthenticationException authException)
throws IOException {
HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(
response);
responseWrapper.setStatus(HttpStatus.SC_UNAUTHORIZED);
Writer out = responseWrapper.getWriter();
errors.writeJsonResponse(out, HttpStatus.SC_UNAUTHORIZED, "Unauthorized");
out.close();
}
}
| Java |
function __processArg(obj, key) {
var arg = null;
if (obj) {
arg = obj[key] || null;
delete obj[key];
}
return arg;
}
function Controller() {
function goSlide(event) {
var index = event.source.mod;
var arrViews = $.scrollableView.getViews();
switch (index) {
case "0":
$.lbl1.backgroundColor = "#453363";
$.lbl1.color = "#AA9DB6";
$.lbl2.backgroundColor = "#E6E7E9";
$.lbl2.color = "#4CC4D2";
$.lbl3.backgroundColor = "#E6E7E9";
$.lbl3.color = "#4CC4D2";
break;
case "1":
$.lbl1.backgroundColor = "#E6E7E9";
$.lbl1.color = "#4CC4D2";
$.lbl2.backgroundColor = "#453363";
$.lbl2.color = "#AA9DB6";
$.lbl3.backgroundColor = "#E6E7E9";
$.lbl3.color = "#4CC4D2";
break;
case "2":
$.lbl1.backgroundColor = "#E6E7E9";
$.lbl1.color = "#4CC4D2";
$.lbl2.backgroundColor = "#E6E7E9";
$.lbl2.color = "#4CC4D2";
$.lbl3.backgroundColor = "#453363";
$.lbl3.color = "#AA9DB6";
}
$.scrollableView.scrollToView(arrViews[index]);
}
require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
this.__controllerPath = "contact";
if (arguments[0]) {
var __parentSymbol = __processArg(arguments[0], "__parentSymbol");
{
__processArg(arguments[0], "$model");
}
{
__processArg(arguments[0], "__itemTemplate");
}
}
var $ = this;
var exports = {};
var __defers = {};
$.__views.win = Ti.UI.createView({
layout: "vertical",
id: "win",
backgroundColor: "white"
});
$.__views.win && $.addTopLevelView($.__views.win);
$.__views.__alloyId87 = Alloy.createController("_header", {
id: "__alloyId87",
__parentSymbol: $.__views.win
});
$.__views.__alloyId87.setParent($.__views.win);
$.__views.__alloyId88 = Ti.UI.createView({
height: "20%",
backgroundColor: "#836EAF",
id: "__alloyId88"
});
$.__views.win.add($.__views.__alloyId88);
$.__views.__alloyId89 = Ti.UI.createLabel({
text: "Contact us",
left: "10",
top: "10",
color: "white",
id: "__alloyId89"
});
$.__views.__alloyId88.add($.__views.__alloyId89);
$.__views.menu = Ti.UI.createView({
id: "menu",
layout: "horizontal",
height: "50",
width: "100%"
});
$.__views.win.add($.__views.menu);
$.__views.lbl1 = Ti.UI.createLabel({
text: "Our Offices",
id: "lbl1",
mod: "0",
height: "100%",
width: "33%",
textAlign: "center",
backgroundColor: "#453363",
color: "#AA9DB6"
});
$.__views.menu.add($.__views.lbl1);
goSlide ? $.__views.lbl1.addEventListener("touchend", goSlide) : __defers["$.__views.lbl1!touchend!goSlide"] = true;
$.__views.__alloyId90 = Ti.UI.createView({
backgroundColor: "#4CC4D2",
height: "100%",
width: "0.45%",
id: "__alloyId90"
});
$.__views.menu.add($.__views.__alloyId90);
$.__views.lbl2 = Ti.UI.createLabel({
text: "Care Center",
id: "lbl2",
mod: "1",
height: "100%",
width: "33%",
textAlign: "center",
backgroundColor: "#E6E7E9",
color: "#4CC4D2"
});
$.__views.menu.add($.__views.lbl2);
goSlide ? $.__views.lbl2.addEventListener("touchend", goSlide) : __defers["$.__views.lbl2!touchend!goSlide"] = true;
$.__views.__alloyId91 = Ti.UI.createView({
backgroundColor: "#4CC4D2",
height: "100%",
width: "0.45%",
id: "__alloyId91"
});
$.__views.menu.add($.__views.__alloyId91);
$.__views.lbl3 = Ti.UI.createLabel({
text: "XOX Dealers",
id: "lbl3",
mod: "2",
height: "100%",
width: "33%",
textAlign: "center",
backgroundColor: "#E6E7E9",
color: "#4CC4D2"
});
$.__views.menu.add($.__views.lbl3);
goSlide ? $.__views.lbl3.addEventListener("touchend", goSlide) : __defers["$.__views.lbl3!touchend!goSlide"] = true;
var __alloyId92 = [];
$.__views.__alloyId93 = Alloy.createController("contact1", {
id: "__alloyId93",
__parentSymbol: __parentSymbol
});
__alloyId92.push($.__views.__alloyId93.getViewEx({
recurse: true
}));
$.__views.__alloyId94 = Alloy.createController("contact2", {
id: "__alloyId94",
__parentSymbol: __parentSymbol
});
__alloyId92.push($.__views.__alloyId94.getViewEx({
recurse: true
}));
$.__views.__alloyId95 = Alloy.createController("contact3", {
id: "__alloyId95",
__parentSymbol: __parentSymbol
});
__alloyId92.push($.__views.__alloyId95.getViewEx({
recurse: true
}));
$.__views.scrollableView = Ti.UI.createScrollableView({
views: __alloyId92,
id: "scrollableView",
showPagingControl: "false",
scrollingEnabled: "false"
});
$.__views.win.add($.__views.scrollableView);
exports.destroy = function() {};
_.extend($, $.__views);
var storeModel = Alloy.createCollection("storeLocator");
var details = storeModel.getStoreList();
console.log(details);
__defers["$.__views.lbl1!touchend!goSlide"] && $.__views.lbl1.addEventListener("touchend", goSlide);
__defers["$.__views.lbl2!touchend!goSlide"] && $.__views.lbl2.addEventListener("touchend", goSlide);
__defers["$.__views.lbl3!touchend!goSlide"] && $.__views.lbl3.addEventListener("touchend", goSlide);
_.extend($, exports);
}
var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;
module.exports = Controller; | Java |
/*
* Copyright 2016 LINE Corporation
*
* LINE Corporation 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:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.linecorp.armeria.common;
import static java.util.Objects.requireNonNull;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Formatter;
import java.util.Locale;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import it.unimi.dsi.fastutil.io.FastByteArrayInputStream;
/**
* HTTP/2 data. Helpers in this class create {@link HttpData} objects that leave the stream open.
* To create a {@link HttpData} that closes the stream, directly instantiate {@link DefaultHttpData}.
*
* <p>Implementations should generally extend {@link AbstractHttpData} to interact with other {@link HttpData}
* implementations.
*/
public interface HttpData extends HttpObject {
/**
* Empty HTTP/2 data.
*/
HttpData EMPTY_DATA = new DefaultHttpData(new byte[0], 0, 0, false);
/**
* Creates a new instance from the specified byte array. The array is not copied; any changes made in the
* array later will be visible to {@link HttpData}.
*
* @return a new {@link HttpData}. {@link #EMPTY_DATA} if the length of the specified array is 0.
*/
static HttpData of(byte[] data) {
requireNonNull(data, "data");
if (data.length == 0) {
return EMPTY_DATA;
}
return new DefaultHttpData(data, 0, data.length, false);
}
/**
* Creates a new instance from the specified byte array, {@code offset} and {@code length}.
* The array is not copied; any changes made in the array later will be visible to {@link HttpData}.
*
* @return a new {@link HttpData}. {@link #EMPTY_DATA} if {@code length} is 0.
*
* @throws ArrayIndexOutOfBoundsException if {@code offset} and {@code length} are out of bounds
*/
static HttpData of(byte[] data, int offset, int length) {
requireNonNull(data);
if (offset < 0 || length < 0 || offset > data.length - length) {
throw new ArrayIndexOutOfBoundsException(
"offset: " + offset + ", length: " + length + ", data.length: " + data.length);
}
if (length == 0) {
return EMPTY_DATA;
}
return new DefaultHttpData(data, offset, length, false);
}
/**
* Converts the specified {@code text} into an {@link HttpData}.
*
* @param charset the {@link Charset} to use for encoding {@code text}
* @param text the {@link String} to convert
*
* @return a new {@link HttpData}. {@link #EMPTY_DATA} if the length of {@code text} is 0.
*/
static HttpData of(Charset charset, String text) {
requireNonNull(charset, "charset");
requireNonNull(text, "text");
if (text.isEmpty()) {
return EMPTY_DATA;
}
return of(text.getBytes(charset));
}
/**
* Converts the specified Netty {@link ByteBuf} into an {@link HttpData}. Unlike {@link #of(byte[])}, this
* method makes a copy of the {@link ByteBuf}.
*
* @return a new {@link HttpData}. {@link #EMPTY_DATA} if the readable bytes of {@code buf} is 0.
*/
static HttpData of(ByteBuf buf) {
requireNonNull(buf, "buf");
if (!buf.isReadable()) {
return EMPTY_DATA;
}
return of(ByteBufUtil.getBytes(buf));
}
/**
* Converts the specified formatted string into an {@link HttpData}. The string is formatted by
* {@link String#format(Locale, String, Object...)} with {@linkplain Locale#ENGLISH English locale}.
*
* @param charset the {@link Charset} to use for encoding string
* @param format {@linkplain Formatter the format string} of the response content
* @param args the arguments referenced by the format specifiers in the format string
*
* @return a new {@link HttpData}. {@link #EMPTY_DATA} if {@code format} is empty.
*/
static HttpData of(Charset charset, String format, Object... args) {
requireNonNull(charset, "charset");
requireNonNull(format, "format");
requireNonNull(args, "args");
if (format.isEmpty()) {
return EMPTY_DATA;
}
return of(String.format(Locale.ENGLISH, format, args).getBytes(charset));
}
/**
* Converts the specified {@code text} into a UTF-8 {@link HttpData}.
*
* @param text the {@link String} to convert
*
* @return a new {@link HttpData}. {@link #EMPTY_DATA} if the length of {@code text} is 0.
*/
static HttpData ofUtf8(String text) {
return of(StandardCharsets.UTF_8, text);
}
/**
* Converts the specified formatted string into a UTF-8 {@link HttpData}. The string is formatted by
* {@link String#format(Locale, String, Object...)} with {@linkplain Locale#ENGLISH English locale}.
*
* @param format {@linkplain Formatter the format string} of the response content
* @param args the arguments referenced by the format specifiers in the format string
*
* @return a new {@link HttpData}. {@link #EMPTY_DATA} if {@code format} is empty.
*/
static HttpData ofUtf8(String format, Object... args) {
return of(StandardCharsets.UTF_8, format, args);
}
/**
* Converts the specified {@code text} into a US-ASCII {@link HttpData}.
*
* @param text the {@link String} to convert
*
* @return a new {@link HttpData}. {@link #EMPTY_DATA} if the length of {@code text} is 0.
*/
static HttpData ofAscii(String text) {
return of(StandardCharsets.US_ASCII, text);
}
/**
* Converts the specified formatted string into a US-ASCII {@link HttpData}. The string is formatted by
* {@link String#format(Locale, String, Object...)} with {@linkplain Locale#ENGLISH English locale}.
*
* @param format {@linkplain Formatter the format string} of the response content
* @param args the arguments referenced by the format specifiers in the format string
*
* @return a new {@link HttpData}. {@link #EMPTY_DATA} if {@code format} is empty.
*/
static HttpData ofAscii(String format, Object... args) {
return of(StandardCharsets.US_ASCII, format, args);
}
/**
* Returns the underlying byte array of this data.
*/
byte[] array();
/**
* Returns the start offset of the {@link #array()}.
*/
int offset();
/**
* Returns the length of this data.
*/
int length();
/**
* Returns whether the {@link #length()} is 0.
*/
default boolean isEmpty() {
return length() == 0;
}
/**
* Decodes this data into a {@link String}.
*
* @param charset the {@link Charset} to use for decoding this data
*
* @return the decoded {@link String}
*/
default String toString(Charset charset) {
requireNonNull(charset, "charset");
return new String(array(), offset(), length(), charset);
}
/**
* Decodes this data into a {@link String} using UTF-8 encoding.
*
* @return the decoded {@link String}
*/
default String toStringUtf8() {
return toString(StandardCharsets.UTF_8);
}
/**
* Decodes this data into a {@link String} using US-ASCII encoding.
*
* @return the decoded {@link String}
*/
default String toStringAscii() {
return toString(StandardCharsets.US_ASCII);
}
/**
* Returns a new {@link InputStream} that is sourced from this data.
*/
default InputStream toInputStream() {
return new FastByteArrayInputStream(array(), offset(), length());
}
/**
* Returns a new {@link Reader} that is sourced from this data and decoded using the specified
* {@link Charset}.
*/
default Reader toReader(Charset charset) {
requireNonNull(charset, "charset");
return new InputStreamReader(toInputStream(), charset);
}
/**
* Returns a new {@link Reader} that is sourced from this data and decoded using
* {@link StandardCharsets#UTF_8}.
*/
default Reader toReaderUtf8() {
return toReader(StandardCharsets.UTF_8);
}
/**
* Returns a new {@link Reader} that is sourced from this data and decoded using
* {@link StandardCharsets#US_ASCII}.
*/
default Reader toReaderAscii() {
return toReader(StandardCharsets.US_ASCII);
}
}
| Java |
extern alias SSmDsClient;
using System;
using System.Collections.Generic;
using System.Linq;
using OpenRiaServices.DomainServices.Client;
using Cities;
using Microsoft.Silverlight.Testing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using DataTests.Northwind.LTS;
using System.ComponentModel.DataAnnotations;
using OpenRiaServices.Silverlight.Testing;
namespace OpenRiaServices.DomainServices.Client.Test
{
using Resource = SSmDsClient::OpenRiaServices.DomainServices.Client.Resource;
using Resources = SSmDsClient::OpenRiaServices.DomainServices.Client.Resources;
#region Test Classes
public class TestOperation : OperationBase
{
private Action<TestOperation> _completeAction;
public TestOperation(Action<TestOperation> completeAction, object userState)
: base(userState)
{
this._completeAction = completeAction;
}
protected override bool SupportsCancellation
{
get
{
return true;
}
}
protected override void CancelCore()
{
base.CancelCore();
}
public new void Complete(Exception error)
{
base.Complete(error);
}
public new void Complete(object result)
{
base.Complete(result);
}
public new void Cancel()
{
base.Cancel();
}
/// <summary>
/// Invoke the completion callback.
/// </summary>
protected override void InvokeCompleteAction()
{
if (this._completeAction != null)
{
this._completeAction(this);
}
}
}
#endregion
/// <summary>
/// Targeted tests for OperationBase and derived classes
/// </summary>
[TestClass]
public class OperationTests : UnitTestBase
{
public void Operation_MarkAsHandled()
{
TestDataContext ctxt = new TestDataContext(new Uri(TestURIs.RootURI, "TestDomainServices-TestCatalog1.svc"));
var query = ctxt.CreateQuery<Product>("ThrowGeneralException", null, false, true);
LoadOperation lo = new LoadOperation<Product>(query, LoadBehavior.KeepCurrent, null, null, null);
EventHandler action = (o, e) =>
{
LoadOperation loadOperation = (LoadOperation)o;
if (loadOperation.HasError)
{
loadOperation.MarkErrorAsHandled();
}
};
lo.Completed += action;
DomainOperationException ex = new DomainOperationException("Operation Failed!", OperationErrorStatus.ServerError, 42, "StackTrace");
lo.Complete(ex);
// verify that calling MarkAsHandled again is a noop
lo.MarkErrorAsHandled();
lo.MarkErrorAsHandled();
// verify that calling MarkAsHandled on an operation not in error
// results in an exception
lo = new LoadOperation<Product>(query, LoadBehavior.KeepCurrent, null, null, null);
Assert.IsFalse(lo.HasError);
Assert.IsTrue(lo.IsErrorHandled);
ExceptionHelper.ExpectInvalidOperationException(delegate
{
lo.MarkErrorAsHandled();
}, Resource.Operation_HasErrorMustBeTrue);
}
/// <summary>
/// Verify that Load operations that don't specify a callback to handle
/// errors and don't specify throwOnError = false result in an exception.
/// </summary>
[TestMethod]
public void UnhandledLoadOperationError()
{
TestDataContext ctxt = new TestDataContext(new Uri(TestURIs.RootURI, "TestDomainServices-TestCatalog1.svc"));
var query = ctxt.CreateQuery<Product>("ThrowGeneralException", null, false, true);
LoadOperation lo = new LoadOperation<Product>(query, LoadBehavior.KeepCurrent, null, null, null);
DomainOperationException expectedException = null;
DomainOperationException ex = new DomainOperationException("Operation Failed!", OperationErrorStatus.ServerError, 42, "StackTrace");
try
{
lo.Complete(ex);
}
catch (DomainOperationException e)
{
expectedException = e;
}
// verify the exception properties
Assert.IsNotNull(expectedException);
Assert.AreEqual(string.Format(Resource.DomainContext_LoadOperationFailed, "ThrowGeneralException", ex.Message), expectedException.Message);
Assert.AreEqual(ex.StackTrace, expectedException.StackTrace);
Assert.AreEqual(ex.Status, expectedException.Status);
Assert.AreEqual(ex.ErrorCode, expectedException.ErrorCode);
Assert.AreEqual(false, lo.IsErrorHandled);
// now test again with validation errors
expectedException = null;
ValidationResult[] validationErrors = new ValidationResult[] { new ValidationResult("Foo", new string[] { "Bar" }) };
lo = new LoadOperation<Product>(query, LoadBehavior.KeepCurrent, null, null, null);
try
{
lo.Complete(validationErrors);
}
catch (DomainOperationException e)
{
expectedException = e;
}
// verify the exception properties
Assert.IsNotNull(expectedException);
Assert.AreEqual(string.Format(Resource.DomainContext_LoadOperationFailed_Validation, "ThrowGeneralException"), expectedException.Message);
}
/// <summary>
/// Verify that Load operations that don't specify a callback to handle
/// errors and don't specify throwOnError = false result in an exception.
/// </summary>
[TestMethod]
public void UnhandledInvokeOperationError()
{
CityDomainContext cities = new CityDomainContext(TestURIs.Cities);
InvokeOperation invoke = new InvokeOperation("Echo", null, null, null, null);
DomainOperationException expectedException = null;
DomainOperationException ex = new DomainOperationException("Operation Failed!", OperationErrorStatus.ServerError, 42, "StackTrace");
try
{
invoke.Complete(ex);
}
catch (DomainOperationException e)
{
expectedException = e;
}
// verify the exception properties
Assert.IsNotNull(expectedException);
Assert.AreEqual(string.Format(Resource.DomainContext_InvokeOperationFailed, "Echo", ex.Message), expectedException.Message);
Assert.AreEqual(ex.StackTrace, expectedException.StackTrace);
Assert.AreEqual(ex.Status, expectedException.Status);
Assert.AreEqual(ex.ErrorCode, expectedException.ErrorCode);
Assert.AreEqual(false, invoke.IsErrorHandled);
// now test again with validation errors
expectedException = null;
ValidationResult[] validationErrors = new ValidationResult[] { new ValidationResult("Foo", new string[] { "Bar" }) };
invoke = new InvokeOperation("Echo", null, null, null, null);
try
{
invoke.Complete(validationErrors);
}
catch (DomainOperationException e)
{
expectedException = e;
}
// verify the exception properties
Assert.IsNotNull(expectedException);
Assert.AreEqual(string.Format(Resource.DomainContext_InvokeOperationFailed_Validation, "Echo"), expectedException.Message);
}
/// <summary>
/// Verify that Load operations that don't specify a callback to handle
/// errors and don't specify throwOnError = false result in an exception.
/// </summary>
[TestMethod]
public void UnhandledSubmitOperationError()
{
CityDomainContext cities = new CityDomainContext(TestURIs.Cities);
CityData data = new CityData();
cities.Cities.LoadEntities(data.Cities.ToArray());
City city = cities.Cities.First();
city.ZoneID = 1;
Assert.IsTrue(cities.EntityContainer.HasChanges);
SubmitOperation submit = new SubmitOperation(cities.EntityContainer.GetChanges(), null, null, null);
DomainOperationException expectedException = null;
DomainOperationException ex = new DomainOperationException("Submit Failed!", OperationErrorStatus.ServerError, 42, "StackTrace");
try
{
submit.Complete(ex);
}
catch (DomainOperationException e)
{
expectedException = e;
}
// verify the exception properties
Assert.IsNotNull(expectedException);
Assert.AreEqual(string.Format(Resource.DomainContext_SubmitOperationFailed, ex.Message), expectedException.Message);
Assert.AreEqual(ex.StackTrace, expectedException.StackTrace);
Assert.AreEqual(ex.Status, expectedException.Status);
Assert.AreEqual(ex.ErrorCode, expectedException.ErrorCode);
Assert.AreEqual(false, submit.IsErrorHandled);
// now test again with conflicts
expectedException = null;
IEnumerable<ChangeSetEntry> entries = ChangeSetBuilder.Build(cities.EntityContainer.GetChanges());
ChangeSetEntry entry = entries.First();
entry.ValidationErrors = new ValidationResultInfo[] { new ValidationResultInfo("Foo", new string[] { "Bar" }) };
submit = new SubmitOperation(cities.EntityContainer.GetChanges(), null, null, null);
try
{
submit.Complete(OperationErrorStatus.Conflicts);
}
catch (DomainOperationException e)
{
expectedException = e;
}
// verify the exception properties
Assert.IsNotNull(expectedException);
Assert.AreEqual(string.Format(Resource.DomainContext_SubmitOperationFailed_Conflicts), expectedException.Message);
// now test again with validation errors
expectedException = null;
entries = ChangeSetBuilder.Build(cities.EntityContainer.GetChanges());
entry = entries.First();
entry.ConflictMembers = new string[] { "ZoneID" };
submit = new SubmitOperation(cities.EntityContainer.GetChanges(), null, null, null);
try
{
submit.Complete(OperationErrorStatus.ValidationFailed);
}
catch (DomainOperationException e)
{
expectedException = e;
}
// verify the exception properties
Assert.IsNotNull(expectedException);
Assert.AreEqual(string.Format(Resource.DomainContext_SubmitOperationFailed_Validation, ex.Message), expectedException.Message);
}
[TestMethod]
[Asynchronous]
[Description("Verifies that cached LoadOperation Entity results are valid when accessed from the complete callback.")]
public void Bug706034_AccessCachedEntityResultsInCallback()
{
Cities.CityDomainContext cities = new CityDomainContext(TestURIs.Cities);
bool callbackCalled = false;
Exception callbackException = null;
Action<LoadOperation<City>> callback = (op) =>
{
if (op.HasError)
{
op.MarkErrorAsHandled();
}
try
{
Assert.AreEqual(11, op.AllEntities.Count());
Assert.AreEqual(11, op.Entities.Count());
}
catch (Exception e)
{
callbackException = e;
}
finally
{
callbackCalled = true;
}
};
var q = cities.GetCitiesQuery();
LoadOperation<City> lo = cities.Load(q, callback, null);
// KEY to bug : access Entity collections to force them to cache
IEnumerable<City> entities = lo.Entities;
IEnumerable<Entity> allEntities = lo.AllEntities;
EnqueueConditional(() => lo.IsComplete && callbackCalled);
EnqueueCallback(delegate
{
Assert.IsNull(callbackException);
Assert.IsNull(lo.Error);
Assert.AreEqual(11, lo.AllEntities.Count());
Assert.AreEqual(11, lo.Entities.Count());
});
EnqueueTestComplete();
}
[TestMethod]
[Description("Verifies that exceptions are thrown and callstacks are preserved.")]
public void Exceptions()
{
Cities.CityDomainContext cities = new CityDomainContext(TestURIs.Cities);
Action<LoadOperation<City>> loCallback = (op) =>
{
if (op.HasError)
{
op.MarkErrorAsHandled();
}
throw new InvalidOperationException("Fnord!");
};
Action<SubmitOperation> soCallback = (op) =>
{
if (op.HasError)
{
op.MarkErrorAsHandled();
}
throw new InvalidOperationException("Fnord!");
};
Action<InvokeOperation> ioCallback = (op) =>
{
if (op.HasError)
{
op.MarkErrorAsHandled();
}
throw new InvalidOperationException("Fnord!");
};
LoadOperation lo = new LoadOperation<City>(cities.GetCitiesQuery(), LoadBehavior.MergeIntoCurrent, loCallback, null, loCallback);
// verify completion callbacks that throw
ExceptionHelper.ExpectInvalidOperationException(delegate
{
try
{
lo.Complete(DomainClientResult.CreateQueryResult(new Entity[0], new Entity[0], 0, new ValidationResult[0]));
}
catch (Exception ex)
{
Assert.IsTrue(ex.StackTrace.Contains("at OpenRiaServices.DomainServices.Client.Test.OperationTests"), "Stacktrace not preserved.");
throw;
}
}, "Fnord!");
// verify cancellation callbacks for all fx operation types
lo = new LoadOperation<City>(cities.GetCitiesQuery(), LoadBehavior.MergeIntoCurrent, null, null, loCallback);
ExceptionHelper.ExpectInvalidOperationException(delegate
{
lo.Cancel();
}, "Fnord!");
SubmitOperation so = new SubmitOperation(cities.EntityContainer.GetChanges(), soCallback, null, soCallback);
ExceptionHelper.ExpectInvalidOperationException(delegate
{
so.Cancel();
}, "Fnord!");
InvokeOperation io = new InvokeOperation("Fnord", null, null, null, ioCallback);
ExceptionHelper.ExpectInvalidOperationException(delegate
{
io.Cancel();
}, "Fnord!");
}
/// <summary>
/// Attempt to call cancel from the completion callback. Expect
/// an exception since the operation is already complete.
/// </summary>
[TestMethod]
[Asynchronous]
public void Bug706066_CancelInCallback()
{
Cities.CityDomainContext cities = new CityDomainContext(TestURIs.Cities);
bool callbackCalled = false;
InvalidOperationException expectedException = null;
Action<LoadOperation<City>> callback = (op) =>
{
if (op.HasError)
{
op.MarkErrorAsHandled();
}
// verify that CanCancel is false even though we'll
// ignore this and try below
Assert.IsFalse(op.CanCancel);
try
{
op.Cancel();
}
catch (InvalidOperationException io)
{
expectedException = io;
}
callbackCalled = true;
};
var q = cities.GetCitiesQuery().Take(1);
LoadOperation lo = cities.Load(q, callback, null);
EnqueueConditional(() => lo.IsComplete && callbackCalled);
EnqueueCallback(delegate
{
Assert.IsFalse(lo.IsCanceled);
Assert.AreEqual(Resources.AsyncOperation_AlreadyCompleted, expectedException.Message);
});
EnqueueTestComplete();
}
}
}
| Java |
require 'spec_helper'
describe 'source install' do
let(:chef_run) do
runner = ChefSpec::Runner.new(platform: 'ubuntu', version: '12.04')
runner.node.set['nrpe']['install_method'] = 'source'
runner.converge 'nrpe::default'
end
it 'includes the nrpe source recipes' do
expect(chef_run).to include_recipe('nrpe::_source_install')
expect(chef_run).to include_recipe('nrpe::_source_nrpe')
expect(chef_run).to include_recipe('nrpe::_source_plugins')
end
it 'includes the build-essential recipe' do
expect(chef_run).to include_recipe('build-essential')
end
it 'installs the correct packages' do
expect(chef_run).to install_package('libssl-dev')
expect(chef_run).to install_package('make')
expect(chef_run).to install_package('tar')
end
it 'creates the nrpe user' do
expect(chef_run).to create_user(chef_run.node['nrpe']['user'])
end
it 'creates the nrpe group' do
expect(chef_run).to create_group(chef_run.node['nrpe']['group'])
end
it 'creates config dir' do
expect(chef_run).to create_directory(chef_run.node['nrpe']['conf_dir'])
end
it 'templates init script' do
expect(chef_run).to render_file("/etc/init.d/#{chef_run.node['nrpe']['service_name']}").with_content('processname: nrpe')
end
it 'starts service called nrpe not nagios-nrpe-server' do
expect(chef_run).to start_service('nrpe')
end
end
| 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.jclouds.openstack.nova.v2_0;
import static org.jclouds.Constants.PROPERTY_ENDPOINT;
import static org.testng.Assert.assertEquals;
import java.util.Properties;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse;
import org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet;
/**
* Tests to ensure that we can pick the only endpoint of a service
*/
@Test(groups = "unit", testName = "EndpointIdIsRandomExpectTest")
public class EndpointIdIsRandomExpectTest extends BaseNovaApiExpectTest {
public EndpointIdIsRandomExpectTest() {
this.identity = "demo:demo";
this.credential = "password";
}
@Override
protected Properties setupProperties() {
Properties overrides = super.setupProperties();
overrides.setProperty(PROPERTY_ENDPOINT, "http://10.10.10.10:5000/v2.0/");
return overrides;
}
public void testVersionMatchOnConfiguredRegionsWhenResponseIs2xx() {
HttpRequest authenticate = HttpRequest
.builder()
.method("POST")
.endpoint("http://10.10.10.10:5000/v2.0/tokens")
.addHeader("Accept", "application/json")
.payload(
payloadFromStringWithContentType(
"{\"auth\":{\"passwordCredentials\":{\"username\":\"demo\",\"password\":\"password\"},\"tenantName\":\"demo\"}}",
"application/json")).build();
HttpResponse authenticationResponse = HttpResponse.builder().statusCode(200)
.payload(payloadFromResourceWithContentType("/access_version_uids.json", "application/json")).build();
NovaApi whenNovaRegionExists = requestSendsResponse(authenticate, authenticationResponse);
assertEquals(whenNovaRegionExists.getConfiguredRegions(), ImmutableSet.of("RegionOne"));
}
}
| Java |
<?php namespace Fungku\NetSuite\Classes;
class BudgetCategory extends Record {
public $name;
public $budgetType;
public $isInactive;
public $internalId;
static $paramtypesmap = array(
"name" => "string",
"budgetType" => "boolean",
"isInactive" => "boolean",
"internalId" => "string",
);
}
| Java |
/*
* Copyright 2014 Open Connectome Project (http://openconnecto.me)
* Written by Da Zheng ([email protected])
*
* This file is part of FlashMatrix.
*
* 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 "matrix_store.h"
#include "local_matrix_store.h"
#include "mem_matrix_store.h"
#include "EM_dense_matrix.h"
#include "EM_object.h"
#include "matrix_config.h"
#include "local_mem_buffer.h"
namespace fm
{
namespace detail
{
std::atomic<size_t> matrix_store::mat_counter;
matrix_store::ptr matrix_store::create(size_t nrow, size_t ncol,
matrix_layout_t layout, const scalar_type &type, int num_nodes,
bool in_mem, safs::safs_file_group::ptr group)
{
if (in_mem)
return mem_matrix_store::create(nrow, ncol, layout, type, num_nodes);
else
return EM_matrix_store::create(nrow, ncol, layout, type, group);
}
matrix_store::matrix_store(size_t nrow, size_t ncol, bool in_mem,
const scalar_type &_type): type(_type)
{
this->nrow = nrow;
this->ncol = ncol;
this->in_mem = in_mem;
this->entry_size = type.get_size();
this->cache_portion = true;
}
size_t matrix_store::get_num_portions() const
{
std::pair<size_t, size_t> chunk_size = get_portion_size();
if (is_wide())
return ceil(((double) get_num_cols()) / chunk_size.second);
else
return ceil(((double) get_num_rows()) / chunk_size.first);
}
local_matrix_store::ptr matrix_store::get_portion(size_t id)
{
size_t start_row;
size_t start_col;
size_t num_rows;
size_t num_cols;
std::pair<size_t, size_t> chunk_size = get_portion_size();
if (is_wide()) {
start_row = 0;
start_col = chunk_size.second * id;
num_rows = get_num_rows();
num_cols = std::min(chunk_size.second, get_num_cols() - start_col);
}
else {
start_row = chunk_size.first * id;
start_col = 0;
num_rows = std::min(chunk_size.first, get_num_rows() - start_row);
num_cols = get_num_cols();
}
return get_portion(start_row, start_col, num_rows, num_cols);
}
local_matrix_store::const_ptr matrix_store::get_portion(size_t id) const
{
size_t start_row;
size_t start_col;
size_t num_rows;
size_t num_cols;
std::pair<size_t, size_t> chunk_size = get_portion_size();
if (is_wide()) {
start_row = 0;
start_col = chunk_size.second * id;
num_rows = get_num_rows();
num_cols = std::min(chunk_size.second, get_num_cols() - start_col);
}
else {
start_row = chunk_size.first * id;
start_col = 0;
num_rows = std::min(chunk_size.first, get_num_rows() - start_row);
num_cols = get_num_cols();
}
return get_portion(start_row, start_col, num_rows, num_cols);
}
namespace
{
class reset_op: public set_operate
{
const scalar_type &type;
size_t entry_size;
public:
reset_op(const scalar_type &_type): type(_type) {
this->entry_size = type.get_size();
}
virtual void set(void *arr, size_t num_eles, off_t row_idx,
off_t col_idx) const {
memset(arr, 0, num_eles * entry_size);
}
virtual const scalar_type &get_type() const {
return type;
}
virtual set_operate::const_ptr transpose() const {
return set_operate::const_ptr();
}
};
class set_task: public thread_task
{
detail::local_matrix_store::ptr local_store;
const set_operate &op;
public:
set_task(detail::local_matrix_store::ptr local_store,
const set_operate &_op): op(_op) {
this->local_store = local_store;
}
void run() {
local_store->set_data(op);
}
};
/*
* These two functions define the length and portion size for 1D partitioning
* on a matrix.
*/
static inline size_t get_tot_len(const matrix_store &mat)
{
return mat.is_wide() ? mat.get_num_cols() : mat.get_num_rows();
}
static inline size_t get_portion_size(const matrix_store &mat)
{
return mat.is_wide() ? mat.get_portion_size().second : mat.get_portion_size().first;
}
class EM_mat_setdata_dispatcher: public EM_portion_dispatcher
{
const set_operate &op;
matrix_store &to_mat;
public:
EM_mat_setdata_dispatcher(matrix_store &store, const set_operate &_op);
virtual void create_task(off_t global_start, size_t length);
};
EM_mat_setdata_dispatcher::EM_mat_setdata_dispatcher(matrix_store &store,
const set_operate &_op): EM_portion_dispatcher(get_tot_len(store),
fm::detail::get_portion_size(store)), op(_op), to_mat(store)
{
}
void EM_mat_setdata_dispatcher::create_task(off_t global_start,
size_t length)
{
size_t global_start_row, global_start_col;
size_t num_rows, num_cols;
if (to_mat.is_wide()) {
global_start_row = 0;
global_start_col = global_start;
num_rows = to_mat.get_num_rows();
num_cols = length;
}
else {
global_start_row = global_start;
global_start_col = 0;
num_rows = length;
num_cols = to_mat.get_num_cols();
}
local_matrix_store::ptr buf;
if (to_mat.store_layout() == matrix_layout_t::L_COL)
buf = local_matrix_store::ptr(new local_buf_col_matrix_store(
global_start_row, global_start_col, num_rows, num_cols,
to_mat.get_type(), -1));
else
buf = local_matrix_store::ptr(new local_buf_row_matrix_store(
global_start_row, global_start_col, num_rows, num_cols,
to_mat.get_type(), -1));
buf->set_data(op);
to_mat.write_portion_async(buf, global_start_row, global_start_col);
}
}
void matrix_store::reset_data()
{
set_data(reset_op(get_type()));
}
void matrix_store::set_data(const set_operate &op)
{
size_t num_chunks = get_num_portions();
if (is_in_mem() && num_chunks == 1) {
local_matrix_store::ptr buf;
if (store_layout() == matrix_layout_t::L_ROW)
buf = local_matrix_store::ptr(new local_buf_row_matrix_store(0, 0,
get_num_rows(), get_num_cols(), get_type(), -1));
else
buf = local_matrix_store::ptr(new local_buf_col_matrix_store(0, 0,
get_num_rows(), get_num_cols(), get_type(), -1));
buf->set_data(op);
write_portion_async(buf, 0, 0);
// After computation, some matrices buffer local portions in the thread,
// we should try to clean these local portions. These local portions
// may contain pointers to some matrices that don't exist any more.
// We also need to clean them to reduce memory consumption.
// We might want to keep the memory buffer for I/O on dense matrices.
if (matrix_conf.is_keep_mem_buf())
detail::local_mem_buffer::clear_bufs(
detail::local_mem_buffer::MAT_PORTION);
else
detail::local_mem_buffer::clear_bufs();
}
else if (is_in_mem()) {
detail::mem_thread_pool::ptr mem_threads
= detail::mem_thread_pool::get_global_mem_threads();
for (size_t i = 0; i < num_chunks; i++) {
detail::local_matrix_store::ptr local_store = get_portion(i);
int node_id = local_store->get_node_id();
// If the local matrix portion is not assigned to any node,
// assign the tasks in round robin fashion.
if (node_id < 0)
node_id = i % mem_threads->get_num_nodes();
mem_threads->process_task(node_id, new set_task(local_store, op));
}
mem_threads->wait4complete();
}
else {
mem_thread_pool::ptr threads = mem_thread_pool::get_global_mem_threads();
EM_mat_setdata_dispatcher::ptr dispatcher(
new EM_mat_setdata_dispatcher(*this, op));
EM_matrix_store *em_this = dynamic_cast<EM_matrix_store *>(this);
assert(em_this);
em_this->start_stream();
for (size_t i = 0; i < threads->get_num_threads(); i++) {
io_worker_task *task = new io_worker_task(dispatcher);
const EM_object *obj = dynamic_cast<const EM_object *>(this);
task->register_EM_obj(const_cast<EM_object *>(obj));
threads->process_task(i % threads->get_num_nodes(), task);
}
threads->wait4complete();
em_this->end_stream();
}
}
matrix_stream::ptr matrix_stream::create(matrix_store::ptr store)
{
if (store->is_in_mem()) {
mem_matrix_store::ptr mem_store
= std::dynamic_pointer_cast<mem_matrix_store>(store);
if (mem_store == NULL) {
BOOST_LOG_TRIVIAL(error)
<< "The in-mem matrix store isn't writable";
return matrix_stream::ptr();
}
else
return mem_matrix_stream::create(mem_store);
}
else {
EM_matrix_store::ptr em_store
= std::dynamic_pointer_cast<EM_matrix_store>(store);
if (em_store == NULL) {
BOOST_LOG_TRIVIAL(error)
<< "The ext-mem matrix store isn't writable";
return matrix_stream::ptr();
}
else
return EM_matrix_stream::create(em_store);
}
}
matrix_store::const_ptr matrix_store::get_cols(
const std::vector<off_t> &idxs) const
{
matrix_store::const_ptr tm = transpose();
matrix_store::const_ptr rows = tm->get_rows(idxs);
if (rows == NULL)
return matrix_store::const_ptr();
else
return rows->transpose();
}
matrix_store::const_ptr matrix_store::get_cols(off_t start, off_t end) const
{
if (start < 0 || end < 0 || end - start < 0) {
BOOST_LOG_TRIVIAL(error) << "invalid range for selecting columns";
return matrix_store::const_ptr();
}
std::vector<off_t> idxs(end - start);
for (size_t i = 0; i < idxs.size(); i++)
idxs[i] = start + i;
return get_cols(idxs);
}
matrix_store::const_ptr matrix_store::get_rows(off_t start, off_t end) const
{
if (start < 0 || end < 0 || end - start < 0) {
BOOST_LOG_TRIVIAL(error) << "invalid range for selecting rows";
return matrix_store::const_ptr();
}
std::vector<off_t> idxs(end - start);
for (size_t i = 0; i < idxs.size(); i++)
idxs[i] = start + i;
return get_rows(idxs);
}
bool matrix_store::share_data(const matrix_store &store) const
{
// By default, we can use data id to determine if two matrices have
// the same data.
return get_data_id() == store.get_data_id()
&& get_data_id() != INVALID_MAT_ID;
}
matrix_append::matrix_append(matrix_store::ptr store)
{
this->res = store;
q.resize(1000);
last_append = -1;
written_eles = 0;
empty_portion = local_matrix_store::const_ptr(new local_buf_row_matrix_store(
0, 0, 0, 0, store->get_type(), -1, false));
}
void matrix_append::write_async(local_matrix_store::const_ptr portion,
off_t seq_id)
{
if (seq_id <= last_append) {
BOOST_LOG_TRIVIAL(error) << "Append a repeated portion";
return;
}
if (portion == NULL)
portion = empty_portion;
std::vector<local_matrix_store::const_ptr> data;
lock.lock();
// Add the new portion to the queue. If the queue is too small,
// we should resize the queue first.
off_t loc = seq_id - last_append - 1;
assert(loc >= 0);
if ((size_t) loc >= q.size())
q.resize(q.size() * 2);
q[loc] = portion;
off_t start_loc = -1;
if (q.front())
start_loc = written_eles;
// Get the portions from the queue.
while (q.front()) {
auto mat = q.front();
// If the portion isn't empty.
if (mat->get_num_rows() > 0 && mat->get_num_cols() > 0)
data.push_back(mat);
q.pop_front();
q.push_back(local_matrix_store::const_ptr());
last_append++;
written_eles += mat->get_num_rows() * mat->get_num_cols();
}
lock.unlock();
for (size_t i = 0; i < data.size(); i++) {
assert(start_loc >= 0);
// TODO this works if the result matrix is stored in memory.
if (res->is_wide()) {
off_t start_row = 0;
off_t start_col = start_loc / res->get_num_rows();
res->write_portion_async(data[i], start_row, start_col);
}
else {
off_t start_row = start_loc / res->get_num_cols();
off_t start_col = 0;
res->write_portion_async(data[i], start_row, start_col);
}
start_loc += data[i]->get_num_rows() * data[i]->get_num_cols();
}
}
matrix_append::~matrix_append()
{
for (size_t i = 0; i < q.size(); i++)
assert(q[i] == NULL);
}
void matrix_append::flush()
{
for (size_t i = 0; i < q.size(); i++)
assert(q[i] == NULL);
}
}
}
| Java |
// Copyright 2018 The LUCI 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 repo
import (
"context"
"strings"
"go.chromium.org/luci/common/data/stringset"
"go.chromium.org/luci/common/errors"
"go.chromium.org/luci/server/auth"
api "go.chromium.org/luci/cipd/api/cipd/v1"
)
// impliedRoles defines what roles are "inherited" by other roles, e.g.
// WRITERs are automatically READERs, so hasRole(..., READER) should return true
// for WRITERs too.
//
// The format is "role -> {role itself} + set of roles implied by it, perhaps
// indirectly".
//
// If a role is missing from this map, it assumed to not be implying any roles.
var impliedRoles = map[api.Role][]api.Role{
api.Role_READER: {api.Role_READER},
api.Role_WRITER: {api.Role_WRITER, api.Role_READER},
api.Role_OWNER: {api.Role_OWNER, api.Role_WRITER, api.Role_READER},
}
// impliedRolesRev is reverse of impliedRoles mapping.
//
// The format is "role -> {role itself} + set of roles that inherit it, perhaps
// indirectly".
//
// If a role is missing from this map, it assumed to not be inherited by
// anything.
var impliedRolesRev = map[api.Role]map[api.Role]struct{}{
api.Role_READER: roleSet(api.Role_READER, api.Role_WRITER, api.Role_OWNER),
api.Role_WRITER: roleSet(api.Role_WRITER, api.Role_OWNER),
api.Role_OWNER: roleSet(api.Role_OWNER),
}
func roleSet(roles ...api.Role) map[api.Role]struct{} {
m := make(map[api.Role]struct{}, len(roles))
for _, r := range roles {
m[r] = struct{}{}
}
return m
}
// hasRole checks whether the current caller has the given role in any of the
// supplied PrefixMetadata objects.
//
// It understands the role inheritance defined by impliedRoles map.
//
// 'metas' is metadata for some prefix and all parent prefixes. It is expected
// to be ordered by the prefix length (shortest first). Ordering is not really
// used now, but it may change in the future.
//
// Returns only transient errors.
func hasRole(c context.Context, metas []*api.PrefixMetadata, role api.Role) (bool, error) {
caller := string(auth.CurrentIdentity(c)) // e.g. "user:[email protected]"
// E.g. if 'role' is READER, 'roles' will be {READER, WRITER, OWNER}.
roles := impliedRolesRev[role]
if roles == nil {
roles = roleSet(role)
}
// Enumerate the set of principals that have any of the requested roles in any
// of the prefixes. Exit early if hitting the direct match, otherwise proceed
// to more expensive group membership checks. Note that we don't use isInACL
// here because we want to postpone all group checks until the very end,
// checking memberships in all groups mentioned in 'metas' at once.
groups := stringset.New(10) // 10 is picked arbitrarily
for _, meta := range metas {
for _, acl := range meta.Acls {
if _, ok := roles[acl.Role]; !ok {
continue // not the role we are interested in
}
for _, p := range acl.Principals {
if p == caller {
return true, nil // the caller was specified in ACLs explicitly
}
// Is this a reference to a group?
if s := strings.SplitN(p, ":", 2); len(s) == 2 && s[0] == "group" {
groups.Add(s[1])
}
}
}
}
yes, err := auth.IsMember(c, groups.ToSlice()...)
if err != nil {
return false, errors.Annotate(err, "failed to check group memberships when checking ACLs for role %s", role).Err()
}
return yes, nil
}
// rolesInPrefix returns a union of roles the caller has in given supplied
// PrefixMetadata objects.
//
// It understands the role inheritance defined by impliedRoles map.
//
// Returns only transient errors.
func rolesInPrefix(c context.Context, metas []*api.PrefixMetadata) ([]api.Role, error) {
roles := roleSet()
for _, meta := range metas {
for _, acl := range meta.Acls {
if _, ok := roles[acl.Role]; ok {
continue // seen this role already
}
switch yes, err := isInACL(c, acl); {
case err != nil:
return nil, err
case yes:
// Add acl.Role and all roles implied by it to 'roles' set.
for _, r := range impliedRoles[acl.Role] {
roles[r] = struct{}{}
}
}
}
}
// Arrange the result in the order of Role enum definition.
out := make([]api.Role, 0, len(roles))
for r := api.Role_READER; r <= api.Role_OWNER; r++ {
if _, ok := roles[r]; ok {
out = append(out, r)
}
}
return out, nil
}
// isInACL is true if the caller is in the given access control list.
func isInACL(c context.Context, acl *api.PrefixMetadata_ACL) (bool, error) {
caller := string(auth.CurrentIdentity(c)) // e.g. "user:[email protected]"
var groups []string
for _, p := range acl.Principals {
if p == caller {
return true, nil // the caller was specified in ACLs explicitly
}
if s := strings.SplitN(p, ":", 2); len(s) == 2 && s[0] == "group" {
groups = append(groups, s[1])
}
}
yes, err := auth.IsMember(c, groups...)
if err != nil {
return false, errors.Annotate(err, "failed to check group memberships when checking ACLs").Err()
}
return yes, nil
}
| 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.dubbo.registry.dubbo;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.Version;
import org.apache.dubbo.common.utils.ExecutorUtil;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.RegistryService;
import org.apache.dubbo.registry.support.FailbackRegistry;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.rpc.Invoker;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import static org.apache.dubbo.registry.Constants.REGISTRY_RECONNECT_PERIOD_KEY;
/**
* DubboRegistry
*/
public class DubboRegistry extends FailbackRegistry {
// Reconnecting detection cycle: 3 seconds (unit:millisecond)
private static final int RECONNECT_PERIOD_DEFAULT = 3 * 1000;
// Scheduled executor service
private final ScheduledExecutorService reconnectTimer = Executors.newScheduledThreadPool(1, new NamedThreadFactory("DubboRegistryReconnectTimer", true));
// Reconnection timer, regular check connection is available. If unavailable, unlimited reconnection.
private final ScheduledFuture<?> reconnectFuture;
// The lock for client acquisition process, lock the creation process of the client instance to prevent repeated clients
private final ReentrantLock clientLock = new ReentrantLock();
private final Invoker<RegistryService> registryInvoker;
private final RegistryService registryService;
/**
* The time in milliseconds the reconnectTimer will wait
*/
private final int reconnectPeriod;
public DubboRegistry(Invoker<RegistryService> registryInvoker, RegistryService registryService) {
super(registryInvoker.getUrl());
this.registryInvoker = registryInvoker;
this.registryService = registryService;
// Start reconnection timer
this.reconnectPeriod = registryInvoker.getUrl().getParameter(REGISTRY_RECONNECT_PERIOD_KEY, RECONNECT_PERIOD_DEFAULT);
reconnectFuture = reconnectTimer.scheduleWithFixedDelay(() -> {
// Check and connect to the registry
try {
connect();
} catch (Throwable t) { // Defensive fault tolerance
logger.error("Unexpected error occur at reconnect, cause: " + t.getMessage(), t);
}
}, reconnectPeriod, reconnectPeriod, TimeUnit.MILLISECONDS);
}
protected final void connect() {
try {
// Check whether or not it is connected
if (isAvailable()) {
return;
}
if (logger.isInfoEnabled()) {
logger.info("Reconnect to registry " + getUrl());
}
clientLock.lock();
try {
// Double check whether or not it is connected
if (isAvailable()) {
return;
}
recover();
} finally {
clientLock.unlock();
}
} catch (Throwable t) { // Ignore all the exceptions and wait for the next retry
if (getUrl().getParameter(Constants.CHECK_KEY, true)) {
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
}
throw new RuntimeException(t.getMessage(), t);
}
logger.error("Failed to connect to registry " + getUrl().getAddress() + " from provider/consumer " + NetUtils.getLocalHost() + " use dubbo " + Version.getVersion() + ", cause: " + t.getMessage(), t);
}
}
@Override
public boolean isAvailable() {
if (registryInvoker == null) {
return false;
}
return registryInvoker.isAvailable();
}
@Override
public void destroy() {
super.destroy();
try {
// Cancel the reconnection timer
ExecutorUtil.cancelScheduledFuture(reconnectFuture);
} catch (Throwable t) {
logger.warn("Failed to cancel reconnect timer", t);
}
registryInvoker.destroy();
ExecutorUtil.gracefulShutdown(reconnectTimer, reconnectPeriod);
}
@Override
public void doRegister(URL url) {
registryService.register(url);
}
@Override
public void doUnregister(URL url) {
registryService.unregister(url);
}
@Override
public void doSubscribe(URL url, NotifyListener listener) {
registryService.subscribe(url, listener);
}
@Override
public void doUnsubscribe(URL url, NotifyListener listener) {
registryService.unsubscribe(url, listener);
}
@Override
public List<URL> lookup(URL url) {
return registryService.lookup(url);
}
}
| Java |
# The following comment should be removed at some point in the future.
# mypy: disallow-untyped-defs=False
from __future__ import absolute_import
import logging
import os.path
import re
from pip._vendor.packaging.version import parse as parse_version
from pip._vendor.six.moves.urllib import parse as urllib_parse
from pip._vendor.six.moves.urllib import request as urllib_request
from pip._internal.exceptions import BadCommand, InstallationError
from pip._internal.utils.misc import display_path, hide_url
from pip._internal.utils.subprocess import make_command
from pip._internal.utils.temp_dir import TempDirectory
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
from pip._internal.vcs.versioncontrol import (
RemoteNotFoundError,
VersionControl,
find_path_to_setup_from_repo_root,
vcs,
)
if MYPY_CHECK_RUNNING:
from typing import Optional, Tuple
from pip._internal.utils.misc import HiddenText
from pip._internal.vcs.versioncontrol import AuthInfo, RevOptions
urlsplit = urllib_parse.urlsplit
urlunsplit = urllib_parse.urlunsplit
logger = logging.getLogger(__name__)
HASH_REGEX = re.compile('^[a-fA-F0-9]{40}$')
def looks_like_hash(sha):
return bool(HASH_REGEX.match(sha))
class Git(VersionControl):
name = 'git'
dirname = '.git'
repo_name = 'clone'
schemes = (
'git', 'git+http', 'git+https', 'git+ssh', 'git+git', 'git+file',
)
# Prevent the user's environment variables from interfering with pip:
# https://github.com/pypa/pip/issues/1130
unset_environ = ('GIT_DIR', 'GIT_WORK_TREE')
default_arg_rev = 'HEAD'
@staticmethod
def get_base_rev_args(rev):
return [rev]
def is_immutable_rev_checkout(self, url, dest):
# type: (str, str) -> bool
_, rev_options = self.get_url_rev_options(hide_url(url))
if not rev_options.rev:
return False
if not self.is_commit_id_equal(dest, rev_options.rev):
# the current commit is different from rev,
# which means rev was something else than a commit hash
return False
# return False in the rare case rev is both a commit hash
# and a tag or a branch; we don't want to cache in that case
# because that branch/tag could point to something else in the future
is_tag_or_branch = bool(
self.get_revision_sha(dest, rev_options.rev)[0]
)
return not is_tag_or_branch
def get_git_version(self):
VERSION_PFX = 'git version '
version = self.run_command(
['version'], show_stdout=False, stdout_only=True
)
if version.startswith(VERSION_PFX):
version = version[len(VERSION_PFX):].split()[0]
else:
version = ''
# get first 3 positions of the git version because
# on windows it is x.y.z.windows.t, and this parses as
# LegacyVersion which always smaller than a Version.
version = '.'.join(version.split('.')[:3])
return parse_version(version)
@classmethod
def get_current_branch(cls, location):
"""
Return the current branch, or None if HEAD isn't at a branch
(e.g. detached HEAD).
"""
# git-symbolic-ref exits with empty stdout if "HEAD" is a detached
# HEAD rather than a symbolic ref. In addition, the -q causes the
# command to exit with status code 1 instead of 128 in this case
# and to suppress the message to stderr.
args = ['symbolic-ref', '-q', 'HEAD']
output = cls.run_command(
args,
extra_ok_returncodes=(1, ),
show_stdout=False,
stdout_only=True,
cwd=location,
)
ref = output.strip()
if ref.startswith('refs/heads/'):
return ref[len('refs/heads/'):]
return None
def export(self, location, url):
# type: (str, HiddenText) -> None
"""Export the Git repository at the url to the destination location"""
if not location.endswith('/'):
location = location + '/'
with TempDirectory(kind="export") as temp_dir:
self.unpack(temp_dir.path, url=url)
self.run_command(
['checkout-index', '-a', '-f', '--prefix', location],
show_stdout=False, cwd=temp_dir.path
)
@classmethod
def get_revision_sha(cls, dest, rev):
"""
Return (sha_or_none, is_branch), where sha_or_none is a commit hash
if the revision names a remote branch or tag, otherwise None.
Args:
dest: the repository directory.
rev: the revision name.
"""
# Pass rev to pre-filter the list.
output = cls.run_command(
['show-ref', rev],
cwd=dest,
show_stdout=False,
stdout_only=True,
on_returncode='ignore',
)
refs = {}
for line in output.strip().splitlines():
try:
sha, ref = line.split()
except ValueError:
# Include the offending line to simplify troubleshooting if
# this error ever occurs.
raise ValueError('unexpected show-ref line: {!r}'.format(line))
refs[ref] = sha
branch_ref = 'refs/remotes/origin/{}'.format(rev)
tag_ref = 'refs/tags/{}'.format(rev)
sha = refs.get(branch_ref)
if sha is not None:
return (sha, True)
sha = refs.get(tag_ref)
return (sha, False)
@classmethod
def _should_fetch(cls, dest, rev):
"""
Return true if rev is a ref or is a commit that we don't have locally.
Branches and tags are not considered in this method because they are
assumed to be always available locally (which is a normal outcome of
``git clone`` and ``git fetch --tags``).
"""
if rev.startswith("refs/"):
# Always fetch remote refs.
return True
if not looks_like_hash(rev):
# Git fetch would fail with abbreviated commits.
return False
if cls.has_commit(dest, rev):
# Don't fetch if we have the commit locally.
return False
return True
@classmethod
def resolve_revision(cls, dest, url, rev_options):
# type: (str, HiddenText, RevOptions) -> RevOptions
"""
Resolve a revision to a new RevOptions object with the SHA1 of the
branch, tag, or ref if found.
Args:
rev_options: a RevOptions object.
"""
rev = rev_options.arg_rev
# The arg_rev property's implementation for Git ensures that the
# rev return value is always non-None.
assert rev is not None
sha, is_branch = cls.get_revision_sha(dest, rev)
if sha is not None:
rev_options = rev_options.make_new(sha)
rev_options.branch_name = rev if is_branch else None
return rev_options
# Do not show a warning for the common case of something that has
# the form of a Git commit hash.
if not looks_like_hash(rev):
logger.warning(
"Did not find branch or tag '%s', assuming revision or ref.",
rev,
)
if not cls._should_fetch(dest, rev):
return rev_options
# fetch the requested revision
cls.run_command(
make_command('fetch', '-q', url, rev_options.to_args()),
cwd=dest,
)
# Change the revision to the SHA of the ref we fetched
sha = cls.get_revision(dest, rev='FETCH_HEAD')
rev_options = rev_options.make_new(sha)
return rev_options
@classmethod
def is_commit_id_equal(cls, dest, name):
"""
Return whether the current commit hash equals the given name.
Args:
dest: the repository directory.
name: a string name.
"""
if not name:
# Then avoid an unnecessary subprocess call.
return False
return cls.get_revision(dest) == name
def fetch_new(self, dest, url, rev_options):
# type: (str, HiddenText, RevOptions) -> None
rev_display = rev_options.to_display()
logger.info('Cloning %s%s to %s', url, rev_display, display_path(dest))
self.run_command(make_command('clone', '-q', url, dest))
if rev_options.rev:
# Then a specific revision was requested.
rev_options = self.resolve_revision(dest, url, rev_options)
branch_name = getattr(rev_options, 'branch_name', None)
if branch_name is None:
# Only do a checkout if the current commit id doesn't match
# the requested revision.
if not self.is_commit_id_equal(dest, rev_options.rev):
cmd_args = make_command(
'checkout', '-q', rev_options.to_args(),
)
self.run_command(cmd_args, cwd=dest)
elif self.get_current_branch(dest) != branch_name:
# Then a specific branch was requested, and that branch
# is not yet checked out.
track_branch = 'origin/{}'.format(branch_name)
cmd_args = [
'checkout', '-b', branch_name, '--track', track_branch,
]
self.run_command(cmd_args, cwd=dest)
#: repo may contain submodules
self.update_submodules(dest)
def switch(self, dest, url, rev_options):
# type: (str, HiddenText, RevOptions) -> None
self.run_command(
make_command('config', 'remote.origin.url', url),
cwd=dest,
)
cmd_args = make_command('checkout', '-q', rev_options.to_args())
self.run_command(cmd_args, cwd=dest)
self.update_submodules(dest)
def update(self, dest, url, rev_options):
# type: (str, HiddenText, RevOptions) -> None
# First fetch changes from the default remote
if self.get_git_version() >= parse_version('1.9.0'):
# fetch tags in addition to everything else
self.run_command(['fetch', '-q', '--tags'], cwd=dest)
else:
self.run_command(['fetch', '-q'], cwd=dest)
# Then reset to wanted revision (maybe even origin/master)
rev_options = self.resolve_revision(dest, url, rev_options)
cmd_args = make_command('reset', '--hard', '-q', rev_options.to_args())
self.run_command(cmd_args, cwd=dest)
#: update submodules
self.update_submodules(dest)
@classmethod
def get_remote_url(cls, location):
"""
Return URL of the first remote encountered.
Raises RemoteNotFoundError if the repository does not have a remote
url configured.
"""
# We need to pass 1 for extra_ok_returncodes since the command
# exits with return code 1 if there are no matching lines.
stdout = cls.run_command(
['config', '--get-regexp', r'remote\..*\.url'],
extra_ok_returncodes=(1, ),
show_stdout=False,
stdout_only=True,
cwd=location,
)
remotes = stdout.splitlines()
try:
found_remote = remotes[0]
except IndexError:
raise RemoteNotFoundError
for remote in remotes:
if remote.startswith('remote.origin.url '):
found_remote = remote
break
url = found_remote.split(' ')[1]
return url.strip()
@classmethod
def has_commit(cls, location, rev):
"""
Check if rev is a commit that is available in the local repository.
"""
try:
cls.run_command(
['rev-parse', '-q', '--verify', "sha^" + rev],
cwd=location,
log_failed_cmd=False,
)
except InstallationError:
return False
else:
return True
@classmethod
def get_revision(cls, location, rev=None):
if rev is None:
rev = 'HEAD'
current_rev = cls.run_command(
['rev-parse', rev],
show_stdout=False,
stdout_only=True,
cwd=location,
)
return current_rev.strip()
@classmethod
def get_subdirectory(cls, location):
"""
Return the path to setup.py, relative to the repo root.
Return None if setup.py is in the repo root.
"""
# find the repo root
git_dir = cls.run_command(
['rev-parse', '--git-dir'],
show_stdout=False,
stdout_only=True,
cwd=location,
).strip()
if not os.path.isabs(git_dir):
git_dir = os.path.join(location, git_dir)
repo_root = os.path.abspath(os.path.join(git_dir, '..'))
return find_path_to_setup_from_repo_root(location, repo_root)
@classmethod
def get_url_rev_and_auth(cls, url):
# type: (str) -> Tuple[str, Optional[str], AuthInfo]
"""
Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'.
That's required because although they use SSH they sometimes don't
work with a ssh:// scheme (e.g. GitHub). But we need a scheme for
parsing. Hence we remove it again afterwards and return it as a stub.
"""
# Works around an apparent Git bug
# (see https://article.gmane.org/gmane.comp.version-control.git/146500)
scheme, netloc, path, query, fragment = urlsplit(url)
if scheme.endswith('file'):
initial_slashes = path[:-len(path.lstrip('/'))]
newpath = (
initial_slashes +
urllib_request.url2pathname(path)
.replace('\\', '/').lstrip('/')
)
after_plus = scheme.find('+') + 1
url = scheme[:after_plus] + urlunsplit(
(scheme[after_plus:], netloc, newpath, query, fragment),
)
if '://' not in url:
assert 'file:' not in url
url = url.replace('git+', 'git+ssh://')
url, rev, user_pass = super(Git, cls).get_url_rev_and_auth(url)
url = url.replace('ssh://', '')
else:
url, rev, user_pass = super(Git, cls).get_url_rev_and_auth(url)
return url, rev, user_pass
@classmethod
def update_submodules(cls, location):
if not os.path.exists(os.path.join(location, '.gitmodules')):
return
cls.run_command(
['submodule', 'update', '--init', '--recursive', '-q'],
cwd=location,
)
@classmethod
def get_repository_root(cls, location):
loc = super(Git, cls).get_repository_root(location)
if loc:
return loc
try:
r = cls.run_command(
['rev-parse', '--show-toplevel'],
cwd=location,
show_stdout=False,
stdout_only=True,
on_returncode='raise',
log_failed_cmd=False,
)
except BadCommand:
logger.debug("could not determine if %s is under git control "
"because git is not available", location)
return None
except InstallationError:
return None
return os.path.normpath(r.rstrip('\r\n'))
vcs.register(Git)
| Java |
# coding: utf-8
#
# Copyright (c) 2013 OpenStack Foundation
# 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.
#
# Base on code in migrate/changeset/databases/sqlite.py which is under
# the following license:
#
# The MIT License
#
# Copyright (c) 2009 Evan Rosson, Jan Dittberner, Domen Kožar
#
# 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.
import os
import re
from migrate.changeset import ansisql
from migrate.changeset.databases import sqlite
from migrate import exceptions as versioning_exceptions
from migrate.versioning import api as versioning_api
from migrate.versioning.repository import Repository
import sqlalchemy
from sqlalchemy.schema import UniqueConstraint
from essential.db import exception
from essential.gettextutils import _
def _get_unique_constraints(self, table):
"""Retrieve information about existing unique constraints of the table
This feature is needed for _recreate_table() to work properly.
Unfortunately, it's not available in sqlalchemy 0.7.x/0.8.x.
"""
data = table.metadata.bind.execute(
"""SELECT sql
FROM sqlite_master
WHERE
type='table' AND
name=:table_name""",
table_name=table.name
).fetchone()[0]
UNIQUE_PATTERN = "CONSTRAINT (\w+) UNIQUE \(([^\)]+)\)"
return [
UniqueConstraint(
*[getattr(table.columns, c.strip(' "')) for c in cols.split(",")],
name=name
)
for name, cols in re.findall(UNIQUE_PATTERN, data)
]
def _recreate_table(self, table, column=None, delta=None, omit_uniques=None):
"""Recreate the table properly
Unlike the corresponding original method of sqlalchemy-migrate this one
doesn't drop existing unique constraints when creating a new one.
"""
table_name = self.preparer.format_table(table)
# we remove all indexes so as not to have
# problems during copy and re-create
for index in table.indexes:
index.drop()
# reflect existing unique constraints
for uc in self._get_unique_constraints(table):
table.append_constraint(uc)
# omit given unique constraints when creating a new table if required
table.constraints = set([
cons for cons in table.constraints
if omit_uniques is None or cons.name not in omit_uniques
])
self.append('ALTER TABLE %s RENAME TO migration_tmp' % table_name)
self.execute()
insertion_string = self._modify_table(table, column, delta)
table.create(bind=self.connection)
self.append(insertion_string % {'table_name': table_name})
self.execute()
self.append('DROP TABLE migration_tmp')
self.execute()
def _visit_migrate_unique_constraint(self, *p, **k):
"""Drop the given unique constraint
The corresponding original method of sqlalchemy-migrate just
raises NotImplemented error
"""
self.recreate_table(p[0].table, omit_uniques=[p[0].name])
def patch_migrate():
"""A workaround for SQLite's inability to alter things
SQLite abilities to alter tables are very limited (please read
http://www.sqlite.org/lang_altertable.html for more details).
E. g. one can't drop a column or a constraint in SQLite. The
workaround for this is to recreate the original table omitting
the corresponding constraint (or column).
sqlalchemy-migrate library has recreate_table() method that
implements this workaround, but it does it wrong:
- information about unique constraints of a table
is not retrieved. So if you have a table with one
unique constraint and a migration adding another one
you will end up with a table that has only the
latter unique constraint, and the former will be lost
- dropping of unique constraints is not supported at all
The proper way to fix this is to provide a pull-request to
sqlalchemy-migrate, but the project seems to be dead. So we
can go on with monkey-patching of the lib at least for now.
"""
# this patch is needed to ensure that recreate_table() doesn't drop
# existing unique constraints of the table when creating a new one
helper_cls = sqlite.SQLiteHelper
helper_cls.recreate_table = _recreate_table
helper_cls._get_unique_constraints = _get_unique_constraints
# this patch is needed to be able to drop existing unique constraints
constraint_cls = sqlite.SQLiteConstraintDropper
constraint_cls.visit_migrate_unique_constraint = \
_visit_migrate_unique_constraint
constraint_cls.__bases__ = (ansisql.ANSIColumnDropper,
sqlite.SQLiteConstraintGenerator)
def db_sync(engine, abs_path, version=None, init_version=0, sanity_check=True):
"""Upgrade or downgrade a database.
Function runs the upgrade() or downgrade() functions in change scripts.
:param engine: SQLAlchemy engine instance for a given database
:param abs_path: Absolute path to migrate repository.
:param version: Database will upgrade/downgrade until this version.
If None - database will update to the latest
available version.
:param init_version: Initial database version
:param sanity_check: Require schema sanity checking for all tables
"""
if version is not None:
try:
version = int(version)
except ValueError:
raise exception.DbMigrationError(
message=_("version should be an integer"))
current_version = db_version(engine, abs_path, init_version)
repository = _find_migrate_repo(abs_path)
if sanity_check:
_db_schema_sanity_check(engine)
if version is None or version > current_version:
return versioning_api.upgrade(engine, repository, version)
else:
return versioning_api.downgrade(engine, repository,
version)
def _db_schema_sanity_check(engine):
"""Ensure all database tables were created with required parameters.
:param engine: SQLAlchemy engine instance for a given database
"""
if engine.name == 'mysql':
onlyutf8_sql = ('SELECT TABLE_NAME,TABLE_COLLATION '
'from information_schema.TABLES '
'where TABLE_SCHEMA=%s and '
'TABLE_COLLATION NOT LIKE "%%utf8%%"')
table_names = [res[0] for res in engine.execute(onlyutf8_sql,
engine.url.database)]
if len(table_names) > 0:
raise ValueError(_('Tables "%s" have non utf8 collation, '
'please make sure all tables are CHARSET=utf8'
) % ','.join(table_names))
def db_version(engine, abs_path, init_version):
"""Show the current version of the repository.
:param engine: SQLAlchemy engine instance for a given database
:param abs_path: Absolute path to migrate repository
:param version: Initial database version
"""
repository = _find_migrate_repo(abs_path)
try:
return versioning_api.db_version(engine, repository)
except versioning_exceptions.DatabaseNotControlledError:
meta = sqlalchemy.MetaData()
meta.reflect(bind=engine)
tables = meta.tables
if len(tables) == 0 or 'alembic_version' in tables:
db_version_control(engine, abs_path, version=init_version)
return versioning_api.db_version(engine, repository)
else:
raise exception.DbMigrationError(
message=_(
"The database is not under version control, but has "
"tables. Please stamp the current version of the schema "
"manually."))
def db_version_control(engine, abs_path, version=None):
"""Mark a database as under this repository's version control.
Once a database is under version control, schema changes should
only be done via change scripts in this repository.
:param engine: SQLAlchemy engine instance for a given database
:param abs_path: Absolute path to migrate repository
:param version: Initial database version
"""
repository = _find_migrate_repo(abs_path)
versioning_api.version_control(engine, repository, version)
return version
def _find_migrate_repo(abs_path):
"""Get the project's change script repository
:param abs_path: Absolute path to migrate repository
"""
if not os.path.exists(abs_path):
raise exception.DbMigrationError("Path %s not found" % abs_path)
return Repository(abs_path)
| Java |
package org.ovirt.engine.core.itests;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertNotNull;
import org.ovirt.engine.core.common.queries.*;
import org.ovirt.engine.core.common.action.LoginUserParameters;
import org.ovirt.engine.core.common.action.VdcReturnValueBase;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.action.RunVmParams;
import org.ovirt.engine.core.compat.Guid;
/**
* Created by IntelliJ IDEA. User: gmostizk Date: Aug 31, 2009 Time: 11:28:01 AM To change this template use File |
* Settings | File Templates.
*/
@Ignore
public class ClientHandshakeSequenceTest extends AbstractBackendTest {
@Test
public void getDomainList() {
VdcQueryReturnValue value = backend.RunPublicQuery(VdcQueryType.GetDomainList, new VdcQueryParametersBase());
assertTrue(value.getSucceeded());
assertNotNull(value.getReturnValue());
System.out.println(value.getReturnValue());
}
@Test
public void getVersion() {
VdcQueryReturnValue value = backend.RunPublicQuery(VdcQueryType.GetConfigurationValue,
new GetConfigurationValueParameters(ConfigurationValues.VdcVersion));
assertNotNull(value);
assertNotNull(value.getReturnValue());
System.out.println("Version: " + value.getReturnValue());
}
@Test
public void loginAdmin() {
VdcReturnValueBase value = backend.Login(new LoginUserParameters("admin", "admin", "domain", "os", "browser",
"client_type"));
assertTrue(value.getSucceeded());
assertNotNull(value.getActionReturnValue());
}
@Test
public void testRunVm() {
RunVmParams params = new RunVmParams(Guid.NewGuid());
VdcReturnValueBase result = backend.runInternalAction(VdcActionType.RunVm, params);
}
}
| Java |
#!/bin/bash
# This script will build the project.
if [ "$TRAVIS_PULL_REQUEST" != "false" ]; then
echo -e "Build Pull Request #$TRAVIS_PULL_REQUEST => Branch [$TRAVIS_BRANCH]"
./gradlew build --stacktrace --info
elif [ "$TRAVIS_PULL_REQUEST" == "false" ] && [ "$TRAVIS_TAG" == "" ]; then
echo -e 'Build Branch with Snapshot => Branch ['$TRAVIS_BRANCH']'
./gradlew -Prelease.travisci=true -PbintrayUser="${bintrayUser}" -PbintrayKey="${bintrayKey}" -PsonatypeUsername="${sonatypeUsername}" -PsonatypePassword="${sonatypePassword}" build snapshot
elif [ "$TRAVIS_PULL_REQUEST" == "false" ] && [ "$TRAVIS_TAG" != "" ]; then
echo -e 'Build Branch for Release => Branch ['$TRAVIS_BRANCH'] Tag ['$TRAVIS_TAG']'
case "$TRAVIS_TAG" in
*-rc\.*)
./gradlew -Prelease.travisci=true -Prelease.useLastTag=true -PbintrayUser="${bintrayUser}" -PbintrayKey="${bintrayKey}" -PsonatypeUsername="${sonatypeUsername}" -PsonatypePassword="${sonatypePassword}" candidate
;;
*)
./gradlew -Prelease.travisci=true -Prelease.useLastTag=true -PbintrayUser="${bintrayUser}" -PbintrayKey="${bintrayKey}" -PsonatypeUsername="${sonatypeUsername}" -PsonatypePassword="${sonatypePassword}" final
;;
esac
else
echo -e 'WARN: Should not be here => Branch ['$TRAVIS_BRANCH'] Tag ['$TRAVIS_TAG'] Pull Request ['$TRAVIS_PULL_REQUEST']'
./gradlew build
fi
| 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.lucene.analysis.reverse;
import java.io.IOException;
import java.io.StringReader;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.MockTokenizer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.BaseTokenStreamTestCase;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.core.KeywordTokenizer;
public class TestReverseStringFilter extends BaseTokenStreamTestCase {
public void testFilter() throws Exception {
TokenStream stream = new MockTokenizer(MockTokenizer.WHITESPACE, false); // 1-4 length string
((Tokenizer)stream).setReader(new StringReader("Do have a nice day"));
ReverseStringFilter filter = new ReverseStringFilter(stream);
assertTokenStreamContents(filter, new String[] { "oD", "evah", "a", "ecin", "yad" });
}
public void testFilterWithMark() throws Exception {
TokenStream stream = new MockTokenizer(MockTokenizer.WHITESPACE, false); // 1-4 length string
((Tokenizer)stream).setReader(new StringReader("Do have a nice day"));
ReverseStringFilter filter = new ReverseStringFilter(stream, '\u0001');
assertTokenStreamContents(filter,
new String[] { "\u0001oD", "\u0001evah", "\u0001a", "\u0001ecin", "\u0001yad" });
}
public void testReverseString() throws Exception {
assertEquals( "A", ReverseStringFilter.reverse( "A" ) );
assertEquals( "BA", ReverseStringFilter.reverse( "AB" ) );
assertEquals( "CBA", ReverseStringFilter.reverse( "ABC" ) );
}
public void testReverseChar() throws Exception {
char[] buffer = { 'A', 'B', 'C', 'D', 'E', 'F' };
ReverseStringFilter.reverse( buffer, 2, 3 );
assertEquals( "ABEDCF", new String( buffer ) );
}
public void testReverseSupplementary() throws Exception {
// supplementary at end
assertEquals("𩬅艱鍟䇹愯瀛", ReverseStringFilter.reverse("瀛愯䇹鍟艱𩬅"));
// supplementary at end - 1
assertEquals("a𩬅艱鍟䇹愯瀛", ReverseStringFilter.reverse("瀛愯䇹鍟艱𩬅a"));
// supplementary at start
assertEquals("fedcba𩬅", ReverseStringFilter.reverse("𩬅abcdef"));
// supplementary at start + 1
assertEquals("fedcba𩬅z", ReverseStringFilter.reverse("z𩬅abcdef"));
// supplementary medial
assertEquals("gfe𩬅dcba", ReverseStringFilter.reverse("abcd𩬅efg"));
}
public void testReverseSupplementaryChar() throws Exception {
// supplementary at end
char[] buffer = "abc瀛愯䇹鍟艱𩬅".toCharArray();
ReverseStringFilter.reverse(buffer, 3, 7);
assertEquals("abc𩬅艱鍟䇹愯瀛", new String(buffer));
// supplementary at end - 1
buffer = "abc瀛愯䇹鍟艱𩬅d".toCharArray();
ReverseStringFilter.reverse(buffer, 3, 8);
assertEquals("abcd𩬅艱鍟䇹愯瀛", new String(buffer));
// supplementary at start
buffer = "abc𩬅瀛愯䇹鍟艱".toCharArray();
ReverseStringFilter.reverse(buffer, 3, 7);
assertEquals("abc艱鍟䇹愯瀛𩬅", new String(buffer));
// supplementary at start + 1
buffer = "abcd𩬅瀛愯䇹鍟艱".toCharArray();
ReverseStringFilter.reverse(buffer, 3, 8);
assertEquals("abc艱鍟䇹愯瀛𩬅d", new String(buffer));
// supplementary medial
buffer = "abc瀛愯𩬅def".toCharArray();
ReverseStringFilter.reverse(buffer, 3, 7);
assertEquals("abcfed𩬅愯瀛", new String(buffer));
}
/** blast some random strings through the analyzer */
public void testRandomStrings() throws Exception {
Analyzer a = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName) {
Tokenizer tokenizer = new MockTokenizer(MockTokenizer.WHITESPACE, false);
return new TokenStreamComponents(tokenizer, new ReverseStringFilter(tokenizer));
}
};
checkRandomData(random(), a, 1000*RANDOM_MULTIPLIER);
}
public void testEmptyTerm() throws IOException {
Analyzer a = new Analyzer() {
@Override
protected TokenStreamComponents createComponents(String fieldName) {
Tokenizer tokenizer = new KeywordTokenizer();
return new TokenStreamComponents(tokenizer, new ReverseStringFilter(tokenizer));
}
};
checkOneTerm(a, "", "");
}
}
| Java |
/*
*
* Copyright (c) 1998-2004
* John Maddock
*
* Use, modification and distribution are subject to the
* Boost Software License, Version 1.0. (See accompanying file
* LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
*/
/*
* LOCATION: see http://www.boost.org for most recent version.
* FILE: regex_debug.cpp
* VERSION: see <autoboost/version.hpp>
* DESCRIPTION: Misc. debugging helpers.
*/
#define AUTOBOOST_REGEX_SOURCE
#include <autoboost/regex/config.hpp>
//
// regex configuration information: this prints out the settings used
// when the library was built - include in debugging builds only:
//
#ifdef AUTOBOOST_REGEX_CONFIG_INFO
#define print_macro regex_lib_print_macro
#define print_expression regex_lib_print_expression
#define print_byte_order regex_lib_print_byte_order
#define print_sign regex_lib_print_sign
#define print_compiler_macros regex_lib_print_compiler_macros
#define print_stdlib_macros regex_lib_print_stdlib_macros
#define print_platform_macros regex_lib_print_platform_macros
#define print_autoboost_macros regex_lib_print_autoboost_macros
#define print_separator regex_lib_print_separator
#define OLD_MAIN regex_lib_main
#define NEW_MAIN regex_lib_main2
#define NO_RECURSE
#include <libs/regex/test/config_info/regex_config_info.cpp>
AUTOBOOST_REGEX_DECL void AUTOBOOST_REGEX_CALL print_regex_library_info()
{
std::cout << "\n\n";
print_separator();
std::cout << "Regex library build configuration:\n\n";
regex_lib_main2();
}
#endif
| Java |
/**
* Copyright 2016 Google 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.
*/
goog.provide('audioCat.audio.record.RecordingJobCreatedEvent');
goog.require('audioCat.audio.record.Event');
goog.require('audioCat.utility.Event');
/**
* An event marking the creation of a new recording job.
* @param {!audioCat.audio.record.RecordingJob} recordingJob The newly created
* job recording.
* @constructor
* @extends {audioCat.utility.Event}
*/
audioCat.audio.record.RecordingJobCreatedEvent = function(recordingJob) {
goog.base(this, audioCat.audio.record.Event.DEFAULT_RECORDING_JOB_CREATED);
/**
* The newly made recording job.
* @type {!audioCat.audio.record.RecordingJob}
*/
this.recordingJob = recordingJob;
};
goog.inherits(
audioCat.audio.record.RecordingJobCreatedEvent, audioCat.utility.Event);
| Java |
package org.cloudfoundry.autoscaler.data.couchdb.dao.impl;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.cloudfoundry.autoscaler.data.couchdb.dao.AppInstanceMetricsDAO;
import org.cloudfoundry.autoscaler.data.couchdb.dao.base.TypedCouchDbRepositorySupport;
import org.cloudfoundry.autoscaler.data.couchdb.document.AppInstanceMetrics;
import org.ektorp.ComplexKey;
import org.ektorp.CouchDbConnector;
import org.ektorp.ViewQuery;
import org.ektorp.support.View;
public class AppInstanceMetricsDAOImpl extends CommonDAOImpl implements AppInstanceMetricsDAO {
@View(name = "byAll", map = "function(doc) { if (doc.type == 'AppInstanceMetrics' ) emit([doc.appId, doc.appType, doc.timestamp], doc._id)}")
private static class AppInstanceMetricsRepository_All extends TypedCouchDbRepositorySupport<AppInstanceMetrics> {
public AppInstanceMetricsRepository_All(CouchDbConnector db) {
super(AppInstanceMetrics.class, db, "AppInstanceMetrics_byAll");
}
public List<AppInstanceMetrics> getAllRecords() {
return queryView("byAll");
}
}
@View(name = "by_appId", map = "function(doc) { if (doc.type=='AppInstanceMetrics' && doc.appId) { emit([doc.appId], doc._id) } }")
private static class AppInstanceMetricsRepository_ByAppId
extends TypedCouchDbRepositorySupport<AppInstanceMetrics> {
public AppInstanceMetricsRepository_ByAppId(CouchDbConnector db) {
super(AppInstanceMetrics.class, db, "AppInstanceMetrics_ByAppId");
}
public List<AppInstanceMetrics> findByAppId(String appId) {
ComplexKey key = ComplexKey.of(appId);
return queryView("by_appId", key);
}
}
@View(name = "by_appId_between", map = "function(doc) { if (doc.type=='AppInstanceMetrics' && doc.appId && doc.timestamp) { emit([doc.appId, doc.timestamp], doc._id) } }")
private static class AppInstanceMetricsRepository_ByAppIdBetween
extends TypedCouchDbRepositorySupport<AppInstanceMetrics> {
public AppInstanceMetricsRepository_ByAppIdBetween(CouchDbConnector db) {
super(AppInstanceMetrics.class, db, "AppInstanceMetrics_ByAppIdBetween");
}
public List<AppInstanceMetrics> findByAppIdBetween(String appId, long startTimestamp, long endTimestamp)
throws Exception {
ComplexKey startKey = ComplexKey.of(appId, startTimestamp);
ComplexKey endKey = ComplexKey.of(appId, endTimestamp);
ViewQuery q = createQuery("by_appId_between").includeDocs(true).startKey(startKey).endKey(endKey);
List<AppInstanceMetrics> returnvalue = null;
String[] input = beforeConnection("QUERY", new String[] { "by_appId_between", appId,
String.valueOf(startTimestamp), String.valueOf(endTimestamp) });
try {
returnvalue = db.queryView(q, AppInstanceMetrics.class);
} catch (Exception e) {
e.printStackTrace();
}
afterConnection(input);
return returnvalue;
}
}
@View(name = "by_serviceId_before", map = "function(doc) { if (doc.type=='AppInstanceMetrics' && doc.serviceId && doc.timestamp) { emit([ doc.serviceId, doc.timestamp], doc._id) } }")
private static class AppInstanceMetricsRepository_ByServiceId_Before
extends TypedCouchDbRepositorySupport<AppInstanceMetrics> {
public AppInstanceMetricsRepository_ByServiceId_Before(CouchDbConnector db) {
super(AppInstanceMetrics.class, db, "AppInstanceMetrics_ByServiceId");
}
public List<AppInstanceMetrics> findByServiceIdBefore(String serviceId, long olderThan) throws Exception {
ComplexKey startKey = ComplexKey.of(serviceId, 0);
ComplexKey endKey = ComplexKey.of(serviceId, olderThan);
ViewQuery q = createQuery("by_serviceId_before").includeDocs(true).startKey(startKey).endKey(endKey);
List<AppInstanceMetrics> returnvalue = null;
String[] input = beforeConnection("QUERY",
new String[] { "by_serviceId_before", serviceId, String.valueOf(0), String.valueOf(olderThan) });
try {
returnvalue = db.queryView(q, AppInstanceMetrics.class);
} catch (Exception e) {
e.printStackTrace();
}
afterConnection(input);
return returnvalue;
}
}
private static final Logger logger = Logger.getLogger(AppInstanceMetricsDAOImpl.class);
private AppInstanceMetricsRepository_All metricsRepoAll;
private AppInstanceMetricsRepository_ByAppId metricsRepoByAppId;
private AppInstanceMetricsRepository_ByAppIdBetween metricsRepoByAppIdBetween;
private AppInstanceMetricsRepository_ByServiceId_Before metricsRepoByServiceIdBefore;
public AppInstanceMetricsDAOImpl(CouchDbConnector db) {
metricsRepoAll = new AppInstanceMetricsRepository_All(db);
metricsRepoByAppId = new AppInstanceMetricsRepository_ByAppId(db);
metricsRepoByAppIdBetween = new AppInstanceMetricsRepository_ByAppIdBetween(db);
metricsRepoByServiceIdBefore = new AppInstanceMetricsRepository_ByServiceId_Before(db);
}
public AppInstanceMetricsDAOImpl(CouchDbConnector db, boolean initDesignDocument) {
this(db);
if (initDesignDocument) {
try {
initAllRepos();
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
}
@Override
public List<AppInstanceMetrics> findAll() {
// TODO Auto-generated method stub
return this.metricsRepoAll.getAllRecords();
}
@Override
public List<AppInstanceMetrics> findByAppId(String appId) {
// TODO Auto-generated method stub
return this.metricsRepoByAppId.findByAppId(appId);
}
@Override
public List<AppInstanceMetrics> findByAppIdBetween(String appId, long startTimestamp, long endTimestamp)
throws Exception {
// TODO Auto-generated method stub
return this.metricsRepoByAppIdBetween.findByAppIdBetween(appId, startTimestamp, endTimestamp);
}
@Override
public List<AppInstanceMetrics> findByServiceIdBefore(String serviceId, long olderThan) throws Exception {
// TODO Auto-generated method stub
return this.metricsRepoByServiceIdBefore.findByServiceIdBefore(serviceId, olderThan);
}
@Override
public List<AppInstanceMetrics> findByAppIdAfter(String appId, long timestamp) throws Exception {
try {
return findByAppIdBetween(appId, timestamp, System.currentTimeMillis());
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return null;
}
@SuppressWarnings("unchecked")
@Override
public <T> TypedCouchDbRepositorySupport<T> getDefaultRepo() {
// TODO Auto-generated method stub
return (TypedCouchDbRepositorySupport<T>) this.metricsRepoAll;
}
@SuppressWarnings("unchecked")
@Override
public <T> List<TypedCouchDbRepositorySupport<T>> getAllRepos() {
// TODO Auto-generated method stub
List<TypedCouchDbRepositorySupport<T>> repoList = new ArrayList<TypedCouchDbRepositorySupport<T>>();
repoList.add((TypedCouchDbRepositorySupport<T>) this.metricsRepoAll);
repoList.add((TypedCouchDbRepositorySupport<T>) this.metricsRepoByAppId);
repoList.add((TypedCouchDbRepositorySupport<T>) this.metricsRepoByAppIdBetween);
repoList.add((TypedCouchDbRepositorySupport<T>) this.metricsRepoByServiceIdBefore);
return repoList;
}
}
| Java |
package jef.common.wrapper;
import java.io.Serializable;
public interface IHolder<T> extends Serializable{
T get();
void set(T obj);
}
| Java |
/*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.restassured.response;
public interface Validatable<T extends ValidatableResponseOptions<T, R>, R extends ResponseBody<R> & ResponseOptions<R>> {
/**
* Returns a validatable response that's lets you validate the response. Usage example:
* <p/>
* <pre>
* given().
* param("firstName", "John").
* param("lastName", "Doe").
* when().
* get("/greet").
* then().
* body("greeting", equalTo("John Doe"));
* </pre>
*
* @return A validatable response
*/
T then();
}
| Java |
/*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014 The Billing Project, LLC
*
* Ning 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.killbill.billing.plugin.meter.timeline.shutdown;
import java.util.HashMap;
import java.util.Map;
import org.joda.time.DateTime;
/**
* This class is used solely as a Json mapping class when saving timelines in a database
* blob on shutdown, and restoring them on startup.
* <p/>
* The Map<Integer, Map<Integer, DateTime>> maps from sourceId to eventCategoryId to startTime.
*/
public class StartTimes {
private final DateTime timeInserted;
private final Map<Integer, Map<Integer, DateTime>> startTimesMap;
private DateTime minStartTime;
public StartTimes(final DateTime timeInserted, final Map<Integer, Map<Integer, DateTime>> startTimesMap) {
this.timeInserted = timeInserted;
this.startTimesMap = startTimesMap;
DateTime minDateTime = new DateTime(Long.MAX_VALUE);
for (final Map<Integer, DateTime> categoryMap : startTimesMap.values()) {
for (final DateTime startTime : categoryMap.values()) {
if (minDateTime.isAfter(startTime)) {
minDateTime = startTime;
}
}
}
this.minStartTime = minDateTime;
}
public StartTimes() {
this.timeInserted = new DateTime();
minStartTime = new DateTime(Long.MAX_VALUE);
this.startTimesMap = new HashMap<Integer, Map<Integer, DateTime>>();
}
public void addTime(final int sourceId, final int categoryId, final DateTime dateTime) {
Map<Integer, DateTime> sourceTimes = startTimesMap.get(sourceId);
if (sourceTimes == null) {
sourceTimes = new HashMap<Integer, DateTime>();
startTimesMap.put(sourceId, sourceTimes);
}
sourceTimes.put(categoryId, dateTime);
if (dateTime.isBefore(minStartTime)) {
minStartTime = dateTime;
}
}
public DateTime getStartTimeForSourceIdAndCategoryId(final int sourceId, final int categoryId) {
final Map<Integer, DateTime> sourceTimes = startTimesMap.get(sourceId);
if (sourceTimes != null) {
return sourceTimes.get(categoryId);
} else {
return null;
}
}
public Map<Integer, Map<Integer, DateTime>> getStartTimesMap() {
return startTimesMap;
}
public DateTime getTimeInserted() {
return timeInserted;
}
public DateTime getMinStartTime() {
return minStartTime;
}
}
| Java |
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2020 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Michael Hackstein
/// @author Copyright 2018, ArangoDB GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "gtest/gtest.h"
#include "fakeit.hpp"
#include "Aql/AqlValue.h"
#include "Aql/AstNode.h"
#include "Aql/ExpressionContext.h"
#include "Aql/Function.h"
#include "Aql/Functions.h"
#include "Containers/SmallVector.h"
#include "Transaction/Methods.h"
#include <velocypack/Builder.h>
#include <velocypack/Iterator.h>
#include <velocypack/Parser.h>
#include <velocypack/Slice.h>
#include <velocypack/velocypack-aliases.h>
#include <cmath>
using namespace arangodb;
using namespace arangodb::aql;
using namespace arangodb::containers;
namespace arangodb {
namespace tests {
namespace date_functions_aql {
struct TestDateModifierFlagFactory {
public:
enum FLAGS { INVALID, MILLI, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, YEAR };
static std::vector<std::string> createAllFlags(FLAGS const& e) {
switch (e) {
case INVALID:
return {"abc"};
case MILLI:
return {"f", "millisecond", "milliseconds", "MiLLiSeCOnd"};
case SECOND:
return {"s", "second", "seconds", "SeCoNd"};
case MINUTE:
return {"i", "minute", "minutes", "MiNutEs"};
case HOUR:
return {"h", "hour", "hours", "HoUr"};
case DAY:
return {"d", "day", "days", "daYs"};
case WEEK:
return {"w", "week", "weeks", "WeEkS"};
case MONTH:
return {"m", "month", "months", "mOnTHs"};
case YEAR:
return {"y", "year", "years", "yeArS"};
}
return {"abc"};
}
static std::string createFlag(FLAGS const& e) {
switch (e) {
case INVALID:
return "abc";
case MILLI:
return "f";
case SECOND:
return "s";
case MINUTE:
return "i";
case HOUR:
return "h";
case DAY:
return "d";
case WEEK:
return "w";
case MONTH:
return "m";
case YEAR:
return "y";
}
}
};
namespace is_datestring {
struct TestDate {
public:
TestDate(std::string const json, bool v) : _date(nullptr), _isValid(v) {
// Make sure to only insert valid JSON.
// We are not testing the parser here.
_date = arangodb::velocypack::Parser::fromJson(json);
}
std::string const testName() const {
return _date->toJson() + " => " + (_isValid ? "true" : "false");
}
void buildParams(VPackFunctionParameters& input) const {
input.emplace_back(_date->slice());
}
void validateResult(AqlValue const& result) const {
ASSERT_TRUE(result.isBoolean());
ASSERT_EQ(result.toBoolean(), _isValid);
}
private:
std::shared_ptr<arangodb::velocypack::Builder> _date;
bool _isValid;
};
TEST(DateFunctionsTest, IS_DATESTRING) {
fakeit::Mock<ExpressionContext> expressionContextMock;
ExpressionContext& expressionContext = expressionContextMock.get();
std::vector<TestDate> testees = {
#include "IS_DATESTRING.testcases"
};
arangodb::aql::Function fun("IS_DATESTRING", &Functions::IsDatestring);
arangodb::aql::AstNode node(NODE_TYPE_FCALL);
node.setData(static_cast<void const*>(&fun));
for (auto const& testee : testees) {
SmallVector<AqlValue>::allocator_type::arena_type arena;
SmallVector<AqlValue> params{arena};
testee.buildParams(params);
AqlValue res = Functions::IsDatestring(&expressionContext, node, params);
testee.validateResult(res);
// Free input parameters
for (auto& it : params) {
it.destroy();
}
}
}
} // namespace is_datestring
namespace date_compare {
struct TestDate {
public:
TestDate(std::vector<std::string> const args, bool v) : _isValid(v) {
_argBuilder.openArray();
for (auto const& it : args) {
_argBuilder.add(VPackValue(it));
}
_argBuilder.close();
}
std::string const testName() const {
return "Input: " + _argBuilder.toJson() + " => " + (_isValid ? "true" : "false");
}
void buildParams(VPackFunctionParameters& input) const {
for (VPackSlice it : VPackArrayIterator(_argBuilder.slice())) {
input.emplace_back(it);
}
}
void validateResult(AqlValue const& result) const {
ASSERT_TRUE(result.isBoolean());
ASSERT_EQ(result.toBoolean(), _isValid);
}
private:
arangodb::velocypack::Builder _argBuilder;
bool _isValid;
};
TEST(DateFunctionsTest, DATE_COMPARE) {
fakeit::Mock<ExpressionContext> expressionContextMock;
ExpressionContext& expressionContext = expressionContextMock.get();
std::vector<TestDate> testees = {
#include "DATE_COMPARE.testcases"
};
arangodb::aql::Function fun("DATE_COMPARE", &Functions::DateCompare);
arangodb::aql::AstNode node(NODE_TYPE_FCALL);
node.setData(static_cast<void const*>(&fun));
for (auto const& testee : testees) {
SmallVector<AqlValue>::allocator_type::arena_type arena;
SmallVector<AqlValue> params{arena};
testee.buildParams(params);
AqlValue res = Functions::DateCompare(&expressionContext, node, params);
testee.validateResult(res);
// Free input parameters
for (auto& it : params) {
it.destroy();
}
}
}
} // namespace date_compare
namespace date_diff {
class DateFunctionsTestDateDiff : public ::testing::Test {
protected:
fakeit::Mock<ExpressionContext> expressionContextMock;
ExpressionContext& expressionContext;
fakeit::Mock<transaction::Methods> trxMock;
transaction::Methods& trx;
// These dates differ by:
// 1 year
// 2 months
// 1 week
// 12 days
// 4 hours
// 5 minutes
// 6 seconds
// 123 milliseconds
std::string const earlierDate;
std::string const laterDate;
// Exact milisecond difference
double dateDiffMillis;
// Average number of days per month in the given dates
double avgDaysPerMonth;
SmallVector<AqlValue>::allocator_type::arena_type arena;
SmallVector<AqlValue> params;
VPackBuilder dateBuilder;
VPackBuilder flagBuilder;
VPackBuilder switchBuilder;
DateFunctionsTestDateDiff()
: expressionContext(expressionContextMock.get()),
trx(trxMock.get()),
earlierDate("2000-04-01T02:48:42.123"),
laterDate("2001-06-13T06:53:48.246"),
dateDiffMillis(37857906123),
avgDaysPerMonth(365.0/12.0),
params(arena) {
dateBuilder.openArray();
dateBuilder.add(VPackValue(earlierDate));
dateBuilder.add(VPackValue(laterDate));
dateBuilder.close();
}
void testCombinations(std::string const& f, double expected) {
arangodb::aql::Function fun("DATE_DIFF", &Functions::DateDiff);
arangodb::aql::AstNode node(NODE_TYPE_FCALL);
node.setData(static_cast<void const*>(&fun));
{
double eps = 0.05;
params.clear();
flagBuilder.clear();
flagBuilder.add(VPackValue(f));
params.emplace_back(dateBuilder.slice().at(0));
params.emplace_back(dateBuilder.slice().at(1));
params.emplace_back(flagBuilder.slice());
switchBuilder.add(VPackValue(true));
params.emplace_back(switchBuilder.slice());
AqlValue res = Functions::DateDiff(&expressionContext, node, params);
ASSERT_TRUE(res.isNumber());
double out = res.toDouble();
ASSERT_GE(out, expected - eps);
ASSERT_LE(out, expected + eps);
for (auto& it : params) {
it.destroy();
}
}
{
params.clear();
flagBuilder.clear();
flagBuilder.add(VPackValue(f));
params.emplace_back(dateBuilder.slice().at(0));
params.emplace_back(dateBuilder.slice().at(1));
params.emplace_back(flagBuilder.slice());
switchBuilder.add(VPackValue(false));
params.emplace_back(switchBuilder.slice());
AqlValue res = Functions::DateDiff(&expressionContext, node, params);
ASSERT_TRUE(res.isNumber());
ASSERT_EQ(std::round(res.toDouble()), std::round(expected));
for (auto& it : params) {
it.destroy();
}
}
{
double eps = 0.05;
params.clear();
flagBuilder.clear();
flagBuilder.add(VPackValue(f));
params.emplace_back(dateBuilder.slice().at(1));
params.emplace_back(dateBuilder.slice().at(0));
params.emplace_back(flagBuilder.slice());
switchBuilder.add(VPackValue(true));
params.emplace_back(switchBuilder.slice());
AqlValue res = Functions::DateDiff(&expressionContext, node, params);
ASSERT_TRUE(res.isNumber());
double out = res.toDouble();
ASSERT_GE(out, -(expected + eps));
ASSERT_LE(out, -(expected - eps));
for (auto& it : params) {
it.destroy();
}
}
{
params.clear();
flagBuilder.clear();
flagBuilder.add(VPackValue(f));
params.emplace_back(dateBuilder.slice().at(1));
params.emplace_back(dateBuilder.slice().at(0));
params.emplace_back(flagBuilder.slice());
switchBuilder.add(VPackValue(false));
params.emplace_back(switchBuilder.slice());
AqlValue res = Functions::DateDiff(&expressionContext, node, params);
ASSERT_TRUE(res.isNumber());
ASSERT_EQ(std::round(res.toDouble()), -std::round(expected));
for (auto& it : params) {
it.destroy();
}
}
}
};
TEST_F(DateFunctionsTestDateDiff, checking_millis) {
double expectedDiff = dateDiffMillis;
auto allFlags = TestDateModifierFlagFactory::createAllFlags(
TestDateModifierFlagFactory::FLAGS::MILLI);
for (auto const& f : allFlags) {
testCombinations(f, expectedDiff);
}
}
TEST_F(DateFunctionsTestDateDiff, checking_seconds) {
double expectedDiff = dateDiffMillis / 1000;
auto allFlags = TestDateModifierFlagFactory::createAllFlags(
TestDateModifierFlagFactory::FLAGS::SECOND);
for (auto const& f : allFlags) {
testCombinations(f, expectedDiff);
}
}
TEST_F(DateFunctionsTestDateDiff, checking_minutes) {
double expectedDiff = dateDiffMillis / (1000 * 60);
auto allFlags = TestDateModifierFlagFactory::createAllFlags(
TestDateModifierFlagFactory::FLAGS::MINUTE);
for (auto const& f : allFlags) {
testCombinations(f, expectedDiff);
}
}
TEST_F(DateFunctionsTestDateDiff, checking_hours) {
double expectedDiff = dateDiffMillis / (1000 * 60 * 60);
auto allFlags = TestDateModifierFlagFactory::createAllFlags(
TestDateModifierFlagFactory::FLAGS::HOUR);
for (auto const& f : allFlags) {
testCombinations(f, expectedDiff);
}
}
TEST_F(DateFunctionsTestDateDiff, checking_days) {
double expectedDiff = dateDiffMillis / (1000 * 60 * 60 * 24);
auto allFlags = TestDateModifierFlagFactory::createAllFlags(
TestDateModifierFlagFactory::FLAGS::DAY);
for (auto const& f : allFlags) {
testCombinations(f, expectedDiff);
}
}
TEST_F(DateFunctionsTestDateDiff, checking_weeks) {
double expectedDiff = dateDiffMillis / (1000 * 60 * 60 * 24 * 7);
auto allFlags = TestDateModifierFlagFactory::createAllFlags(
TestDateModifierFlagFactory::FLAGS::WEEK);
for (auto const& f : allFlags) {
testCombinations(f, expectedDiff);
}
}
TEST_F(DateFunctionsTestDateDiff, checking_months) {
double expectedDiff = dateDiffMillis / (1000 * 60 * 60 * 24) / avgDaysPerMonth;
auto allFlags = TestDateModifierFlagFactory::createAllFlags(
TestDateModifierFlagFactory::FLAGS::MONTH);
for (auto const& f : allFlags) {
testCombinations(f, expectedDiff);
}
}
TEST_F(DateFunctionsTestDateDiff, checking_years) {
double expectedDiff = dateDiffMillis / (1000 * 60 * 60 * 24) / 365;
auto allFlags = TestDateModifierFlagFactory::createAllFlags(
TestDateModifierFlagFactory::FLAGS::YEAR);
for (auto const& f : allFlags) {
testCombinations(f, expectedDiff);
}
}
TEST_F(DateFunctionsTestDateDiff, checking_leap_days) {
// TODO!
}
} // namespace date_diff
namespace date_subtract {
struct TestDate {
public:
TestDate(std::string const& json, std::string const& v)
: _input(nullptr), _result(v) {
// Make sure to only insert valid JSON.
// We are not testing the parser here.
_input = arangodb::velocypack::Parser::fromJson(json);
}
std::string const testName() const {
return _input->toJson() + " => " + _result;
}
void buildParams(VPackFunctionParameters& input) const {
VPackSlice s = _input->slice();
for (VPackSlice it : VPackArrayIterator(s)) {
input.emplace_back(it);
}
}
void validateResult(AqlValue const& result) const {
ASSERT_TRUE(result.isString());
auto res = result.slice();
std::string ref = res.copyString(); // Readability in test Tool
ASSERT_EQ(ref, _result);
}
private:
std::shared_ptr<arangodb::velocypack::Builder> _input;
std::string const _result;
};
TEST(DateFunctionsTest, DATE_SUBTRACT) {
fakeit::Mock<ExpressionContext> expressionContextMock;
ExpressionContext& expressionContext = expressionContextMock.get();
std::vector<TestDate> testees = {
#include "DATE_SUBTRACT.testcases"
};
arangodb::aql::Function fun("DATE_SUBTRACT", &Functions::DateSubtract);
arangodb::aql::AstNode node(NODE_TYPE_FCALL);
node.setData(static_cast<void const*>(&fun));
for (auto const& testee : testees) {
SmallVector<AqlValue>::allocator_type::arena_type arena;
SmallVector<AqlValue> params{arena};
testee.buildParams(params);
AqlValue res = Functions::DateSubtract(&expressionContext, node, params);
testee.validateResult(res);
res.destroy();
// Free input parameters
for (auto& it : params) {
it.destroy();
}
}
}
} // namespace date_subtract
} // namespace date_functions_aql
} // namespace tests
} // namespace arangodb
| Java |
/*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets 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 io.druid.metadata;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import io.druid.indexing.overlord.DataSourceMetadata;
import io.druid.indexing.overlord.ObjectMetadata;
import io.druid.indexing.overlord.SegmentPublishResult;
import io.druid.jackson.DefaultObjectMapper;
import io.druid.java.util.common.StringUtils;
import io.druid.timeline.DataSegment;
import io.druid.timeline.partition.LinearShardSpec;
import io.druid.timeline.partition.NoneShardSpec;
import io.druid.timeline.partition.NumberedShardSpec;
import org.joda.time.Interval;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.skife.jdbi.v2.Handle;
import org.skife.jdbi.v2.tweak.HandleCallback;
import org.skife.jdbi.v2.util.StringMapper;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
public class IndexerSQLMetadataStorageCoordinatorTest
{
@Rule
public final TestDerbyConnector.DerbyConnectorRule derbyConnectorRule = new TestDerbyConnector.DerbyConnectorRule();
private final ObjectMapper mapper = new DefaultObjectMapper();
private final DataSegment defaultSegment = new DataSegment(
"fooDataSource",
Interval.parse("2015-01-01T00Z/2015-01-02T00Z"),
"version",
ImmutableMap.<String, Object>of(),
ImmutableList.of("dim1"),
ImmutableList.of("m1"),
new LinearShardSpec(0),
9,
100
);
private final DataSegment defaultSegment2 = new DataSegment(
"fooDataSource",
Interval.parse("2015-01-01T00Z/2015-01-02T00Z"),
"version",
ImmutableMap.<String, Object>of(),
ImmutableList.of("dim1"),
ImmutableList.of("m1"),
new LinearShardSpec(1),
9,
100
);
private final DataSegment defaultSegment3 = new DataSegment(
"fooDataSource",
Interval.parse("2015-01-03T00Z/2015-01-04T00Z"),
"version",
ImmutableMap.<String, Object>of(),
ImmutableList.of("dim1"),
ImmutableList.of("m1"),
NoneShardSpec.instance(),
9,
100
);
// Overshadows defaultSegment, defaultSegment2
private final DataSegment defaultSegment4 = new DataSegment(
"fooDataSource",
Interval.parse("2015-01-01T00Z/2015-01-02T00Z"),
"zversion",
ImmutableMap.<String, Object>of(),
ImmutableList.of("dim1"),
ImmutableList.of("m1"),
new LinearShardSpec(0),
9,
100
);
private final DataSegment numberedSegment0of0 = new DataSegment(
"fooDataSource",
Interval.parse("2015-01-01T00Z/2015-01-02T00Z"),
"zversion",
ImmutableMap.<String, Object>of(),
ImmutableList.of("dim1"),
ImmutableList.of("m1"),
new NumberedShardSpec(0, 0),
9,
100
);
private final DataSegment numberedSegment1of0 = new DataSegment(
"fooDataSource",
Interval.parse("2015-01-01T00Z/2015-01-02T00Z"),
"zversion",
ImmutableMap.<String, Object>of(),
ImmutableList.of("dim1"),
ImmutableList.of("m1"),
new NumberedShardSpec(1, 0),
9,
100
);
private final DataSegment numberedSegment2of0 = new DataSegment(
"fooDataSource",
Interval.parse("2015-01-01T00Z/2015-01-02T00Z"),
"zversion",
ImmutableMap.<String, Object>of(),
ImmutableList.of("dim1"),
ImmutableList.of("m1"),
new NumberedShardSpec(2, 0),
9,
100
);
private final DataSegment numberedSegment2of1 = new DataSegment(
"fooDataSource",
Interval.parse("2015-01-01T00Z/2015-01-02T00Z"),
"zversion",
ImmutableMap.<String, Object>of(),
ImmutableList.of("dim1"),
ImmutableList.of("m1"),
new NumberedShardSpec(2, 1),
9,
100
);
private final DataSegment numberedSegment3of1 = new DataSegment(
"fooDataSource",
Interval.parse("2015-01-01T00Z/2015-01-02T00Z"),
"zversion",
ImmutableMap.<String, Object>of(),
ImmutableList.of("dim1"),
ImmutableList.of("m1"),
new NumberedShardSpec(3, 1),
9,
100
);
private final Set<DataSegment> SEGMENTS = ImmutableSet.of(defaultSegment, defaultSegment2);
private final AtomicLong metadataUpdateCounter = new AtomicLong();
private IndexerSQLMetadataStorageCoordinator coordinator;
private TestDerbyConnector derbyConnector;
@Before
public void setUp()
{
derbyConnector = derbyConnectorRule.getConnector();
mapper.registerSubtypes(LinearShardSpec.class);
derbyConnector.createDataSourceTable();
derbyConnector.createTaskTables();
derbyConnector.createSegmentTable();
metadataUpdateCounter.set(0);
coordinator = new IndexerSQLMetadataStorageCoordinator(
mapper,
derbyConnectorRule.metadataTablesConfigSupplier().get(),
derbyConnector
)
{
@Override
protected DataSourceMetadataUpdateResult updateDataSourceMetadataWithHandle(
Handle handle,
String dataSource,
DataSourceMetadata startMetadata,
DataSourceMetadata endMetadata
) throws IOException
{
// Count number of times this method is called.
metadataUpdateCounter.getAndIncrement();
return super.updateDataSourceMetadataWithHandle(handle, dataSource, startMetadata, endMetadata);
}
};
}
private void unUseSegment()
{
for (final DataSegment segment : SEGMENTS) {
Assert.assertEquals(
1, (int) derbyConnector.getDBI().<Integer>withHandle(
new HandleCallback<Integer>()
{
@Override
public Integer withHandle(Handle handle) throws Exception
{
return handle.createStatement(
StringUtils.format(
"UPDATE %s SET used = false WHERE id = :id",
derbyConnectorRule.metadataTablesConfigSupplier().get().getSegmentsTable()
)
).bind("id", segment.getIdentifier()).execute();
}
}
)
);
}
}
private List<String> getUsedIdentifiers()
{
final String table = derbyConnectorRule.metadataTablesConfigSupplier().get().getSegmentsTable();
return derbyConnector.retryWithHandle(
new HandleCallback<List<String>>()
{
@Override
public List<String> withHandle(Handle handle) throws Exception
{
return handle.createQuery("SELECT id FROM " + table + " WHERE used = true ORDER BY id")
.map(StringMapper.FIRST)
.list();
}
}
);
}
@Test
public void testSimpleAnnounce() throws IOException
{
coordinator.announceHistoricalSegments(SEGMENTS);
for (DataSegment segment : SEGMENTS) {
Assert.assertArrayEquals(
mapper.writeValueAsString(segment).getBytes("UTF-8"),
derbyConnector.lookup(
derbyConnectorRule.metadataTablesConfigSupplier().get().getSegmentsTable(),
"id",
"payload",
segment.getIdentifier()
)
);
}
Assert.assertEquals(
ImmutableList.of(defaultSegment.getIdentifier(), defaultSegment2.getIdentifier()),
getUsedIdentifiers()
);
// Should not update dataSource metadata.
Assert.assertEquals(0, metadataUpdateCounter.get());
}
@Test
public void testOvershadowingAnnounce() throws IOException
{
final ImmutableSet<DataSegment> segments = ImmutableSet.of(defaultSegment, defaultSegment2, defaultSegment4);
coordinator.announceHistoricalSegments(segments);
for (DataSegment segment : segments) {
Assert.assertArrayEquals(
mapper.writeValueAsString(segment).getBytes("UTF-8"),
derbyConnector.lookup(
derbyConnectorRule.metadataTablesConfigSupplier().get().getSegmentsTable(),
"id",
"payload",
segment.getIdentifier()
)
);
}
Assert.assertEquals(ImmutableList.of(defaultSegment4.getIdentifier()), getUsedIdentifiers());
}
@Test
public void testTransactionalAnnounceSuccess() throws IOException
{
// Insert first segment.
final SegmentPublishResult result1 = coordinator.announceHistoricalSegments(
ImmutableSet.of(defaultSegment),
new ObjectMetadata(null),
new ObjectMetadata(ImmutableMap.of("foo", "bar"))
);
Assert.assertEquals(new SegmentPublishResult(ImmutableSet.of(defaultSegment), true), result1);
Assert.assertArrayEquals(
mapper.writeValueAsString(defaultSegment).getBytes("UTF-8"),
derbyConnector.lookup(
derbyConnectorRule.metadataTablesConfigSupplier().get().getSegmentsTable(),
"id",
"payload",
defaultSegment.getIdentifier()
)
);
// Insert second segment.
final SegmentPublishResult result2 = coordinator.announceHistoricalSegments(
ImmutableSet.of(defaultSegment2),
new ObjectMetadata(ImmutableMap.of("foo", "bar")),
new ObjectMetadata(ImmutableMap.of("foo", "baz"))
);
Assert.assertEquals(new SegmentPublishResult(ImmutableSet.of(defaultSegment2), true), result2);
Assert.assertArrayEquals(
mapper.writeValueAsString(defaultSegment2).getBytes("UTF-8"),
derbyConnector.lookup(
derbyConnectorRule.metadataTablesConfigSupplier().get().getSegmentsTable(),
"id",
"payload",
defaultSegment2.getIdentifier()
)
);
// Examine metadata.
Assert.assertEquals(
new ObjectMetadata(ImmutableMap.of("foo", "baz")),
coordinator.getDataSourceMetadata("fooDataSource")
);
// Should only be tried once per call.
Assert.assertEquals(2, metadataUpdateCounter.get());
}
@Test
public void testTransactionalAnnounceRetryAndSuccess() throws IOException
{
final AtomicLong attemptCounter = new AtomicLong();
final IndexerSQLMetadataStorageCoordinator failOnceCoordinator = new IndexerSQLMetadataStorageCoordinator(
mapper,
derbyConnectorRule.metadataTablesConfigSupplier().get(),
derbyConnector
)
{
@Override
protected DataSourceMetadataUpdateResult updateDataSourceMetadataWithHandle(
Handle handle,
String dataSource,
DataSourceMetadata startMetadata,
DataSourceMetadata endMetadata
) throws IOException
{
metadataUpdateCounter.getAndIncrement();
if (attemptCounter.getAndIncrement() == 0) {
return DataSourceMetadataUpdateResult.TRY_AGAIN;
} else {
return super.updateDataSourceMetadataWithHandle(handle, dataSource, startMetadata, endMetadata);
}
}
};
// Insert first segment.
final SegmentPublishResult result1 = failOnceCoordinator.announceHistoricalSegments(
ImmutableSet.of(defaultSegment),
new ObjectMetadata(null),
new ObjectMetadata(ImmutableMap.of("foo", "bar"))
);
Assert.assertEquals(new SegmentPublishResult(ImmutableSet.of(defaultSegment), true), result1);
Assert.assertArrayEquals(
mapper.writeValueAsString(defaultSegment).getBytes("UTF-8"),
derbyConnector.lookup(
derbyConnectorRule.metadataTablesConfigSupplier().get().getSegmentsTable(),
"id",
"payload",
defaultSegment.getIdentifier()
)
);
// Reset attempt counter to induce another failure.
attemptCounter.set(0);
// Insert second segment.
final SegmentPublishResult result2 = failOnceCoordinator.announceHistoricalSegments(
ImmutableSet.of(defaultSegment2),
new ObjectMetadata(ImmutableMap.of("foo", "bar")),
new ObjectMetadata(ImmutableMap.of("foo", "baz"))
);
Assert.assertEquals(new SegmentPublishResult(ImmutableSet.of(defaultSegment2), true), result2);
Assert.assertArrayEquals(
mapper.writeValueAsString(defaultSegment2).getBytes("UTF-8"),
derbyConnector.lookup(
derbyConnectorRule.metadataTablesConfigSupplier().get().getSegmentsTable(),
"id",
"payload",
defaultSegment2.getIdentifier()
)
);
// Examine metadata.
Assert.assertEquals(
new ObjectMetadata(ImmutableMap.of("foo", "baz")),
failOnceCoordinator.getDataSourceMetadata("fooDataSource")
);
// Should be tried twice per call.
Assert.assertEquals(4, metadataUpdateCounter.get());
}
@Test
public void testTransactionalAnnounceFailDbNullWantNotNull() throws IOException
{
final SegmentPublishResult result1 = coordinator.announceHistoricalSegments(
ImmutableSet.of(defaultSegment),
new ObjectMetadata(ImmutableMap.of("foo", "bar")),
new ObjectMetadata(ImmutableMap.of("foo", "baz"))
);
Assert.assertEquals(new SegmentPublishResult(ImmutableSet.<DataSegment>of(), false), result1);
// Should only be tried once.
Assert.assertEquals(1, metadataUpdateCounter.get());
}
@Test
public void testTransactionalAnnounceFailDbNotNullWantNull() throws IOException
{
final SegmentPublishResult result1 = coordinator.announceHistoricalSegments(
ImmutableSet.of(defaultSegment),
new ObjectMetadata(null),
new ObjectMetadata(ImmutableMap.of("foo", "baz"))
);
Assert.assertEquals(new SegmentPublishResult(ImmutableSet.of(defaultSegment), true), result1);
final SegmentPublishResult result2 = coordinator.announceHistoricalSegments(
ImmutableSet.of(defaultSegment2),
new ObjectMetadata(null),
new ObjectMetadata(ImmutableMap.of("foo", "baz"))
);
Assert.assertEquals(new SegmentPublishResult(ImmutableSet.<DataSegment>of(), false), result2);
// Should only be tried once per call.
Assert.assertEquals(2, metadataUpdateCounter.get());
}
@Test
public void testTransactionalAnnounceFailDbNotNullWantDifferent() throws IOException
{
final SegmentPublishResult result1 = coordinator.announceHistoricalSegments(
ImmutableSet.of(defaultSegment),
new ObjectMetadata(null),
new ObjectMetadata(ImmutableMap.of("foo", "baz"))
);
Assert.assertEquals(new SegmentPublishResult(ImmutableSet.of(defaultSegment), true), result1);
final SegmentPublishResult result2 = coordinator.announceHistoricalSegments(
ImmutableSet.of(defaultSegment2),
new ObjectMetadata(ImmutableMap.of("foo", "qux")),
new ObjectMetadata(ImmutableMap.of("foo", "baz"))
);
Assert.assertEquals(new SegmentPublishResult(ImmutableSet.<DataSegment>of(), false), result2);
// Should only be tried once per call.
Assert.assertEquals(2, metadataUpdateCounter.get());
}
@Test
public void testSimpleUsedList() throws IOException
{
coordinator.announceHistoricalSegments(SEGMENTS);
Assert.assertEquals(
SEGMENTS,
ImmutableSet.copyOf(
coordinator.getUsedSegmentsForInterval(
defaultSegment.getDataSource(),
defaultSegment.getInterval()
)
)
);
}
@Test
public void testMultiIntervalUsedList() throws IOException
{
coordinator.announceHistoricalSegments(SEGMENTS);
coordinator.announceHistoricalSegments(ImmutableSet.of(defaultSegment3));
Assert.assertEquals(
SEGMENTS,
ImmutableSet.copyOf(
coordinator.getUsedSegmentsForIntervals(
defaultSegment.getDataSource(),
ImmutableList.of(defaultSegment.getInterval())
)
)
);
Assert.assertEquals(
ImmutableSet.of(defaultSegment3),
ImmutableSet.copyOf(
coordinator.getUsedSegmentsForIntervals(
defaultSegment.getDataSource(),
ImmutableList.of(defaultSegment3.getInterval())
)
)
);
Assert.assertEquals(
ImmutableSet.of(defaultSegment, defaultSegment2, defaultSegment3),
ImmutableSet.copyOf(
coordinator.getUsedSegmentsForIntervals(
defaultSegment.getDataSource(),
ImmutableList.of(defaultSegment.getInterval(), defaultSegment3.getInterval())
)
)
);
//case to check no duplication if two intervals overlapped with the interval of same segment.
Assert.assertEquals(
ImmutableList.of(defaultSegment3),
coordinator.getUsedSegmentsForIntervals(
defaultSegment.getDataSource(),
ImmutableList.of(
Interval.parse("2015-01-03T00Z/2015-01-03T05Z"),
Interval.parse("2015-01-03T09Z/2015-01-04T00Z")
)
)
);
}
@Test
public void testSimpleUnUsedList() throws IOException
{
coordinator.announceHistoricalSegments(SEGMENTS);
unUseSegment();
Assert.assertEquals(
SEGMENTS,
ImmutableSet.copyOf(
coordinator.getUnusedSegmentsForInterval(
defaultSegment.getDataSource(),
defaultSegment.getInterval()
)
)
);
}
@Test
public void testUsedOverlapLow() throws IOException
{
coordinator.announceHistoricalSegments(SEGMENTS);
Set<DataSegment> actualSegments = ImmutableSet.copyOf(
coordinator.getUsedSegmentsForInterval(
defaultSegment.getDataSource(),
Interval.parse("2014-12-31T23:59:59.999Z/2015-01-01T00:00:00.001Z") // end is exclusive
)
);
Assert.assertEquals(
SEGMENTS,
actualSegments
);
}
@Test
public void testUsedOverlapHigh() throws IOException
{
coordinator.announceHistoricalSegments(SEGMENTS);
Assert.assertEquals(
SEGMENTS,
ImmutableSet.copyOf(
coordinator.getUsedSegmentsForInterval(
defaultSegment.getDataSource(),
Interval.parse("2015-1-1T23:59:59.999Z/2015-02-01T00Z")
)
)
);
}
@Test
public void testUsedOutOfBoundsLow() throws IOException
{
coordinator.announceHistoricalSegments(SEGMENTS);
Assert.assertTrue(
coordinator.getUsedSegmentsForInterval(
defaultSegment.getDataSource(),
new Interval(defaultSegment.getInterval().getStart().minus(1), defaultSegment.getInterval().getStart())
).isEmpty()
);
}
@Test
public void testUsedOutOfBoundsHigh() throws IOException
{
coordinator.announceHistoricalSegments(SEGMENTS);
Assert.assertTrue(
coordinator.getUsedSegmentsForInterval(
defaultSegment.getDataSource(),
new Interval(defaultSegment.getInterval().getEnd(), defaultSegment.getInterval().getEnd().plusDays(10))
).isEmpty()
);
}
@Test
public void testUsedWithinBoundsEnd() throws IOException
{
coordinator.announceHistoricalSegments(SEGMENTS);
Assert.assertEquals(
SEGMENTS,
ImmutableSet.copyOf(
coordinator.getUsedSegmentsForInterval(
defaultSegment.getDataSource(),
defaultSegment.getInterval().withEnd(defaultSegment.getInterval().getEnd().minusMillis(1))
)
)
);
}
@Test
public void testUsedOverlapEnd() throws IOException
{
coordinator.announceHistoricalSegments(SEGMENTS);
Assert.assertEquals(
SEGMENTS,
ImmutableSet.copyOf(
coordinator.getUsedSegmentsForInterval(
defaultSegment.getDataSource(),
defaultSegment.getInterval().withEnd(defaultSegment.getInterval().getEnd().plusMillis(1))
)
)
);
}
@Test
public void testUnUsedOverlapLow() throws IOException
{
coordinator.announceHistoricalSegments(SEGMENTS);
unUseSegment();
Assert.assertTrue(
coordinator.getUnusedSegmentsForInterval(
defaultSegment.getDataSource(),
new Interval(
defaultSegment.getInterval().getStart().minus(1),
defaultSegment.getInterval().getStart().plus(1)
)
).isEmpty()
);
}
@Test
public void testUnUsedUnderlapLow() throws IOException
{
coordinator.announceHistoricalSegments(SEGMENTS);
unUseSegment();
Assert.assertTrue(
coordinator.getUnusedSegmentsForInterval(
defaultSegment.getDataSource(),
new Interval(defaultSegment.getInterval().getStart().plus(1), defaultSegment.getInterval().getEnd())
).isEmpty()
);
}
@Test
public void testUnUsedUnderlapHigh() throws IOException
{
coordinator.announceHistoricalSegments(SEGMENTS);
unUseSegment();
Assert.assertTrue(
coordinator.getUnusedSegmentsForInterval(
defaultSegment.getDataSource(),
new Interval(defaultSegment.getInterval().getStart(), defaultSegment.getInterval().getEnd().minus(1))
).isEmpty()
);
}
@Test
public void testUnUsedOverlapHigh() throws IOException
{
coordinator.announceHistoricalSegments(SEGMENTS);
unUseSegment();
Assert.assertTrue(
coordinator.getUnusedSegmentsForInterval(
defaultSegment.getDataSource(),
defaultSegment.getInterval().withStart(defaultSegment.getInterval().getEnd().minus(1))
).isEmpty()
);
}
@Test
public void testUnUsedBigOverlap() throws IOException
{
coordinator.announceHistoricalSegments(SEGMENTS);
unUseSegment();
Assert.assertEquals(
SEGMENTS,
ImmutableSet.copyOf(
coordinator.getUnusedSegmentsForInterval(
defaultSegment.getDataSource(),
Interval.parse("2000/2999")
)
)
);
}
@Test
public void testUnUsedLowRange() throws IOException
{
coordinator.announceHistoricalSegments(SEGMENTS);
unUseSegment();
Assert.assertEquals(
SEGMENTS,
ImmutableSet.copyOf(
coordinator.getUnusedSegmentsForInterval(
defaultSegment.getDataSource(),
defaultSegment.getInterval().withStart(defaultSegment.getInterval().getStart().minus(1))
)
)
);
Assert.assertEquals(
SEGMENTS,
ImmutableSet.copyOf(
coordinator.getUnusedSegmentsForInterval(
defaultSegment.getDataSource(),
defaultSegment.getInterval().withStart(defaultSegment.getInterval().getStart().minusYears(1))
)
)
);
}
@Test
public void testUnUsedHighRange() throws IOException
{
coordinator.announceHistoricalSegments(SEGMENTS);
unUseSegment();
Assert.assertEquals(
SEGMENTS,
ImmutableSet.copyOf(
coordinator.getUnusedSegmentsForInterval(
defaultSegment.getDataSource(),
defaultSegment.getInterval().withEnd(defaultSegment.getInterval().getEnd().plus(1))
)
)
);
Assert.assertEquals(
SEGMENTS,
ImmutableSet.copyOf(
coordinator.getUnusedSegmentsForInterval(
defaultSegment.getDataSource(),
defaultSegment.getInterval().withEnd(defaultSegment.getInterval().getEnd().plusYears(1))
)
)
);
}
@Test
public void testDeleteDataSourceMetadata() throws IOException
{
coordinator.announceHistoricalSegments(
ImmutableSet.of(defaultSegment),
new ObjectMetadata(null),
new ObjectMetadata(ImmutableMap.of("foo", "bar"))
);
Assert.assertEquals(
new ObjectMetadata(ImmutableMap.of("foo", "bar")),
coordinator.getDataSourceMetadata("fooDataSource")
);
Assert.assertFalse("deleteInvalidDataSourceMetadata", coordinator.deleteDataSourceMetadata("nonExistentDS"));
Assert.assertTrue("deleteValidDataSourceMetadata", coordinator.deleteDataSourceMetadata("fooDataSource"));
Assert.assertNull("getDataSourceMetadataNullAfterDelete", coordinator.getDataSourceMetadata("fooDataSource"));
}
@Test
public void testSingleAdditionalNumberedShardWithNoCorePartitions() throws IOException
{
additionalNumberedShardTest(ImmutableSet.of(numberedSegment0of0));
}
@Test
public void testMultipleAdditionalNumberedShardsWithNoCorePartitions() throws IOException
{
additionalNumberedShardTest(ImmutableSet.of(numberedSegment0of0, numberedSegment1of0, numberedSegment2of0));
}
@Test
public void testSingleAdditionalNumberedShardWithOneCorePartition() throws IOException
{
additionalNumberedShardTest(ImmutableSet.of(numberedSegment2of1));
}
@Test
public void testMultipleAdditionalNumberedShardsWithOneCorePartition() throws IOException
{
additionalNumberedShardTest(ImmutableSet.of(numberedSegment2of1, numberedSegment3of1));
}
private void additionalNumberedShardTest(Set<DataSegment> segments) throws IOException
{
coordinator.announceHistoricalSegments(segments);
for (DataSegment segment : segments) {
Assert.assertArrayEquals(
mapper.writeValueAsString(segment).getBytes("UTF-8"),
derbyConnector.lookup(
derbyConnectorRule.metadataTablesConfigSupplier().get().getSegmentsTable(),
"id",
"payload",
segment.getIdentifier()
)
);
}
Assert.assertEquals(
segments.stream().map(DataSegment::getIdentifier).collect(Collectors.toList()),
getUsedIdentifiers()
);
// Should not update dataSource metadata.
Assert.assertEquals(0, metadataUpdateCounter.get());
}
}
| 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.sis.util;
import java.util.Arrays;
import java.nio.CharBuffer;
import org.opengis.metadata.citation.Citation; // For javadoc
import org.opengis.referencing.IdentifiedObject; // For javadoc
import static java.lang.Character.*;
/**
* Static methods working with {@link CharSequence} instances. Some methods defined in this
* class duplicate the functionalities already provided in the standard {@link String} class,
* but works on a generic {@code CharSequence} instance instead of {@code String}.
*
* <h2>Unicode support</h2>
* Every methods defined in this class work on <cite>code points</cite> instead of characters
* when appropriate. Consequently those methods should behave correctly with characters outside
* the <cite>Basic Multilingual Plane</cite> (BMP).
*
* <h2>Policy on space characters</h2>
* Java defines two methods for testing if a character is a white space:
* {@link Character#isWhitespace(int)} and {@link Character#isSpaceChar(int)}.
* Those two methods differ in the way they handle {@linkplain Characters#NO_BREAK_SPACE
* no-break spaces}, tabulations and line feeds. The general policy in the SIS library is:
*
* <ul>
* <li>Use {@code isWhitespace(…)} when separating entities (words, numbers, tokens, <i>etc.</i>)
* in a list. Using that method, characters separated by a no-break space are considered as
* part of the same entity.</li>
* <li>Use {@code isSpaceChar(…)} when parsing a single entity, for example a single word.
* Using this method, no-break spaces are considered as part of the entity while line
* feeds or tabulations are entity boundaries.</li>
* </ul>
*
* <div class="note"><b>Example:</b>
* Numbers formatted in the French locale use no-break spaces as group separators. When parsing a list of numbers,
* ordinary spaces around the numbers may need to be ignored, but no-break spaces shall be considered as part of the
* numbers. Consequently {@code isWhitespace(…)} is appropriate for skipping spaces <em>between</em> the numbers.
* But if there is spaces to skip <em>inside</em> a single number, then {@code isSpaceChar(…)} is a good choice
* for accepting no-break spaces and for stopping the parse operation at tabulations or line feed character.
* A tabulation or line feed between two characters is very likely to separate two distinct values.</div>
*
* In practice, the {@link java.text.Format} implementations in the SIS library typically use
* {@code isSpaceChar(…)} while most of the rest of the SIS library, including this
* {@code CharSequences} class, consistently uses {@code isWhitespace(…)}.
*
* <p>Note that the {@link String#trim()} method doesn't follow any of those policies and should
* generally be avoided. That {@code trim()} method removes every ISO control characters without
* distinction about whether the characters are space or not, and ignore all Unicode spaces.
* The {@link #trimWhitespaces(String)} method defined in this class can be used as an alternative.</p>
*
* <h2>Handling of null values</h2>
* Most methods in this class accept a {@code null} {@code CharSequence} argument. In such cases
* the method return value is either a {@code null} {@code CharSequence}, an empty array, or a
* {@code 0} or {@code false} primitive type calculated as if the input was an empty string.
*
* @author Martin Desruisseaux (Geomatys)
* @version 1.1
*
* @see StringBuilders
*
* @since 0.3
* @module
*/
public final class CharSequences extends Static {
/**
* An array of zero-length. This constant play a role equivalents to
* {@link java.util.Collections#EMPTY_LIST}.
*/
public static final String[] EMPTY_ARRAY = new String[0];
/**
* An array of strings containing only white spaces. String lengths are equal to their
* index in the {@code spaces} array. For example, {@code spaces[4]} contains a string
* of length 4. Strings are constructed only when first needed.
*/
private static final String[] SPACES = new String[10];
/**
* Do not allow instantiation of this class.
*/
private CharSequences() {
}
/**
* Returns the code point after the given index. This method completes
* {@link Character#codePointBefore(CharSequence, int)} but is rarely used because slightly
* inefficient (in most cases, the code point at {@code index} is known together with the
* corresponding {@code charCount(int)} value, so the method calls should be unnecessary).
*/
private static int codePointAfter(final CharSequence text, final int index) {
return codePointAt(text, index + charCount(codePointAt(text, index)));
}
/**
* Returns a character sequence of the specified length filled with white spaces.
*
* <h4>Use case</h4>
* This method is typically invoked for performing right-alignment of text on the
* {@linkplain java.io.Console console} or other device using monospaced font.
* Callers compute a value for the {@code length} argument by (<var>desired width</var> - <var>used width</var>).
* Since the <var>used width</var> value may be greater than expected, this method handle negative {@code length}
* values as if the value was zero.
*
* @param length the string length. Negative values are clamped to 0.
* @return a string of length {@code length} filled with white spaces.
*/
public static CharSequence spaces(final int length) {
/*
* No need to synchronize. In the unlikely event of two threads calling this method
* at the same time and the two calls creating a new string, the String.intern() call
* will take care of canonicalizing the strings.
*/
if (length <= 0) {
return "";
}
if (length < SPACES.length) {
String s = SPACES[length - 1];
if (s == null) {
final char[] spaces = new char[length];
Arrays.fill(spaces, ' ');
s = new String(spaces).intern();
SPACES[length - 1] = s;
}
return s;
}
return new CharSequence() {
@Override public int length() {
return length;
}
@Override public char charAt(int index) {
ArgumentChecks.ensureValidIndex(length, index);
return ' ';
}
@Override public CharSequence subSequence(final int start, final int end) {
ArgumentChecks.ensureValidIndexRange(length, start, end);
final int n = end - start;
return (n == length) ? this : spaces(n);
}
@Override public String toString() {
final char[] array = new char[length];
Arrays.fill(array, ' ');
return new String(array);
}
};
}
/**
* Returns the {@linkplain CharSequence#length() length} of the given characters sequence,
* or 0 if {@code null}.
*
* @param text the character sequence from which to get the length, or {@code null}.
* @return the length of the character sequence, or 0 if the argument is {@code null}.
*/
public static int length(final CharSequence text) {
return (text != null) ? text.length() : 0;
}
/**
* Returns the number of Unicode code points in the given characters sequence,
* or 0 if {@code null}. Unpaired surrogates within the text count as one code
* point each.
*
* @param text the character sequence from which to get the count, or {@code null}.
* @return the number of Unicode code points, or 0 if the argument is {@code null}.
*
* @see #codePointCount(CharSequence, int, int)
*/
public static int codePointCount(final CharSequence text) {
return (text != null) ? codePointCount(text, 0, text.length()) : 0;
}
/**
* Returns the number of Unicode code points in the given characters sub-sequence,
* or 0 if {@code null}. Unpaired surrogates within the text count as one code
* point each.
*
* <p>This method performs the same work than the standard
* {@link Character#codePointCount(CharSequence, int, int)} method, except that it tries
* to delegate to the optimized methods from the {@link String}, {@link StringBuilder},
* {@link StringBuffer} or {@link CharBuffer} classes if possible.</p>
*
* @param text the character sequence from which to get the count, or {@code null}.
* @param fromIndex the index from which to start the computation.
* @param toIndex the index after the last character to take in account.
* @return the number of Unicode code points, or 0 if the argument is {@code null}.
*
* @see Character#codePointCount(CharSequence, int, int)
* @see String#codePointCount(int, int)
* @see StringBuilder#codePointCount(int, int)
*/
public static int codePointCount(final CharSequence text, final int fromIndex, final int toIndex) {
if (text == null) return 0;
if (text instanceof String) return ((String) text).codePointCount(fromIndex, toIndex);
if (text instanceof StringBuilder) return ((StringBuilder) text).codePointCount(fromIndex, toIndex);
if (text instanceof StringBuffer) return ((StringBuffer) text).codePointCount(fromIndex, toIndex);
if (text instanceof CharBuffer) {
final CharBuffer buffer = (CharBuffer) text;
if (buffer.hasArray() && !buffer.isReadOnly()) {
final int position = buffer.position();
return Character.codePointCount(buffer.array(), position + fromIndex, position + toIndex);
}
}
return Character.codePointCount(text, fromIndex, toIndex);
}
/**
* Returns the number of occurrences of the {@code toSearch} string in the given {@code text}.
* The search is case-sensitive.
*
* @param text the character sequence to count occurrences, or {@code null}.
* @param toSearch the string to search in the given {@code text}.
* It shall contain at least one character.
* @return the number of occurrences of {@code toSearch} in {@code text},
* or 0 if {@code text} was null or empty.
* @throws NullArgumentException if the {@code toSearch} argument is null.
* @throws IllegalArgumentException if the {@code toSearch} argument is empty.
*/
public static int count(final CharSequence text, final String toSearch) {
ArgumentChecks.ensureNonEmpty("toSearch", toSearch);
final int length = toSearch.length();
if (length == 1) {
// Implementation working on a single character is faster.
return count(text, toSearch.charAt(0));
}
int n = 0;
if (text != null) {
int i = 0;
while ((i = indexOf(text, toSearch, i, text.length())) >= 0) {
n++;
i += length;
}
}
return n;
}
/**
* Counts the number of occurrence of the given character in the given character sequence.
*
* @param text the character sequence to count occurrences, or {@code null}.
* @param toSearch the character to count.
* @return the number of occurrences of the given character, or 0 if the {@code text} is null.
*/
public static int count(final CharSequence text, final char toSearch) {
int n = 0;
if (text != null) {
if (text instanceof String) {
final String s = (String) text;
for (int i=s.indexOf(toSearch); ++i != 0; i=s.indexOf(toSearch, i)) {
n++;
}
} else {
// No need to use the code point API here, since we are looking for exact matches.
for (int i=text.length(); --i>=0;) {
if (text.charAt(i) == toSearch) {
n++;
}
}
}
}
return n;
}
/**
* Returns the index within the given strings of the first occurrence of the specified part,
* starting at the specified index. This method is equivalent to the following method call,
* except that this method works on arbitrary {@link CharSequence} objects instead of
* {@link String}s only, and that the upper limit can be specified:
*
* {@preformat java
* return text.indexOf(part, fromIndex);
* }
*
* There is no restriction on the value of {@code fromIndex}. If negative or greater
* than {@code toIndex}, then the behavior of this method is as if the search started
* from 0 or {@code toIndex} respectively. This is consistent with the
* {@link String#indexOf(String, int)} behavior.
*
* @param text the string in which to perform the search.
* @param toSearch the substring for which to search.
* @param fromIndex the index from which to start the search.
* @param toIndex the index after the last character where to perform the search.
* @return the index within the text of the first occurrence of the specified part, starting at the specified index,
* or -1 if no occurrence has been found or if the {@code text} argument is null.
* @throws NullArgumentException if the {@code toSearch} argument is null.
* @throws IllegalArgumentException if the {@code toSearch} argument is empty.
*
* @see String#indexOf(String, int)
* @see StringBuilder#indexOf(String, int)
* @see StringBuffer#indexOf(String, int)
*/
public static int indexOf(final CharSequence text, final CharSequence toSearch, int fromIndex, int toIndex) {
ArgumentChecks.ensureNonEmpty("toSearch", toSearch);
if (text != null) {
int length = text.length();
if (toIndex > length) {
toIndex = length;
}
if (toSearch instanceof String && toIndex == length) {
if (text instanceof String) {
return ((String) text).indexOf((String) toSearch, fromIndex);
}
if (text instanceof StringBuilder) {
return ((StringBuilder) text).indexOf((String) toSearch, fromIndex);
}
if (text instanceof StringBuffer) {
return ((StringBuffer) text).indexOf((String) toSearch, fromIndex);
}
}
if (fromIndex < 0) {
fromIndex = 0;
}
length = toSearch.length();
toIndex -= length;
search: for (; fromIndex <= toIndex; fromIndex++) {
for (int i=0; i<length; i++) {
// No need to use the codePointAt API here, since we are looking for exact matches.
if (text.charAt(fromIndex + i) != toSearch.charAt(i)) {
continue search;
}
}
return fromIndex;
}
}
return -1;
}
/**
* Returns the index within the given character sequence of the first occurrence of the
* specified character, starting the search at the specified index. If the character is
* not found, then this method returns -1.
*
* <p>There is no restriction on the value of {@code fromIndex}. If negative or greater
* than {@code toIndex}, then the behavior of this method is as if the search started
* from 0 or {@code toIndex} respectively. This is consistent with the behavior documented
* in {@link String#indexOf(int, int)}.</p>
*
* @param text the character sequence in which to perform the search, or {@code null}.
* @param toSearch the Unicode code point of the character to search.
* @param fromIndex the index to start the search from.
* @param toIndex the index after the last character where to perform the search.
* @return the index of the first occurrence of the given character in the specified sub-sequence,
* or -1 if no occurrence has been found or if the {@code text} argument is null.
*
* @see String#indexOf(int, int)
*/
public static int indexOf(final CharSequence text, final int toSearch, int fromIndex, int toIndex) {
if (text != null) {
final int length = text.length();
if (toIndex >= length) {
if (text instanceof String) {
// String provides a faster implementation.
return ((String) text).indexOf(toSearch, fromIndex);
}
toIndex = length;
}
if (fromIndex < 0) {
fromIndex = 0;
}
char head = (char) toSearch;
char tail = (char) 0;
if (head != toSearch) { // Outside BMP plane?
head = highSurrogate(toSearch);
tail = lowSurrogate (toSearch);
toIndex--;
}
while (fromIndex < toIndex) {
if (text.charAt(fromIndex) == head) {
if (tail == 0 || text.charAt(fromIndex+1) == tail) {
return fromIndex;
}
}
fromIndex++;
}
}
return -1;
}
/**
* Returns the index within the given character sequence of the last occurrence of the
* specified character, searching backward in the given index range.
* If the character is not found, then this method returns -1.
*
* <p>There is no restriction on the value of {@code toIndex}. If greater than the text length
* or less than {@code fromIndex}, then the behavior of this method is as if the search started
* from {@code length} or {@code fromIndex} respectively. This is consistent with the behavior
* documented in {@link String#lastIndexOf(int, int)}.</p>
*
* @param text the character sequence in which to perform the search, or {@code null}.
* @param toSearch the Unicode code point of the character to search.
* @param fromIndex the index of the first character in the range where to perform the search.
* @param toIndex the index after the last character in the range where to perform the search.
* @return the index of the last occurrence of the given character in the specified sub-sequence,
* or -1 if no occurrence has been found or if the {@code text} argument is null.
*
* @see String#lastIndexOf(int, int)
*/
public static int lastIndexOf(final CharSequence text, final int toSearch, int fromIndex, int toIndex) {
if (text != null) {
if (fromIndex <= 0) {
if (text instanceof String) {
// String provides a faster implementation.
return ((String) text).lastIndexOf(toSearch, toIndex - 1);
}
fromIndex = 0;
}
final int length = text.length();
if (toIndex > length) {
toIndex = length;
}
char tail = (char) toSearch;
char head = (char) 0;
if (tail != toSearch) { // Outside BMP plane?
tail = lowSurrogate (toSearch);
head = highSurrogate(toSearch);
fromIndex++;
}
while (toIndex > fromIndex) {
if (text.charAt(--toIndex) == tail) {
if (head == 0 || text.charAt(--toIndex) == head) {
return toIndex;
}
}
}
}
return -1;
}
/**
* Returns the index of the first character after the given number of lines.
* This method counts the number of occurrence of {@code '\n'}, {@code '\r'}
* or {@code "\r\n"} starting from the given position. When {@code numLines}
* occurrences have been found, the index of the first character after the last
* occurrence is returned.
*
* <p>If the {@code numLines} argument is positive, this method searches forward.
* If negative, this method searches backward. If 0, this method returns the
* beginning of the current line.</p>
*
* <p>If this method reaches the end of {@code text} while searching forward, then
* {@code text.length()} is returned. If this method reaches the beginning of
* {@code text} while searching backward, then 0 is returned.</p>
*
* @param text the string in which to skip a determined amount of lines.
* @param numLines the number of lines to skip. Can be positive, zero or negative.
* @param fromIndex index at which to start the search, from 0 to {@code text.length()} inclusive.
* @return index of the first character after the last skipped line.
* @throws NullPointerException if the {@code text} argument is null.
* @throws IndexOutOfBoundsException if {@code fromIndex} is out of bounds.
*/
public static int indexOfLineStart(final CharSequence text, int numLines, int fromIndex) {
final int length = text.length();
/*
* Go backward if the number of lines is negative.
* No need to use the codePoint API because we are
* looking only for characters in the BMP plane.
*/
if (numLines <= 0) {
do {
char c;
do {
if (fromIndex == 0) {
return fromIndex;
}
c = text.charAt(--fromIndex);
if (c == '\n') {
if (fromIndex != 0 && text.charAt(fromIndex - 1) == '\r') {
--fromIndex;
}
break;
}
} while (c != '\r');
} while (++numLines != 1);
// Execute the forward code below for skipping the "end of line" characters.
}
/*
* Skips forward the given amount of lines.
*/
while (--numLines >= 0) {
char c;
do {
if (fromIndex == length) {
return fromIndex;
}
c = text.charAt(fromIndex++);
if (c == '\r') {
if (fromIndex != length && text.charAt(fromIndex) == '\n') {
fromIndex++;
}
break;
}
} while (c != '\n');
}
return fromIndex;
}
/**
* Returns the index of the first non-white character in the given range.
* If the given range contains only space characters, then this method returns the index of the
* first character after the given range, which is always equals or greater than {@code toIndex}.
* Note that this character may not exist if {@code toIndex} is equals to the text length.
*
* <p>Special cases:</p>
* <ul>
* <li>If {@code fromIndex} is greater than {@code toIndex},
* then this method unconditionally returns {@code fromIndex}.</li>
* <li>If the given range contains only space characters and the character at {@code toIndex-1}
* is the high surrogate of a valid supplementary code point, then this method returns
* {@code toIndex+1}, which is the index of the next code point.</li>
* <li>If {@code fromIndex} is negative or {@code toIndex} is greater than the text length,
* then the behavior of this method is undefined.</li>
* </ul>
*
* Space characters are identified by the {@link Character#isWhitespace(int)} method.
*
* @param text the string in which to perform the search (can not be null).
* @param fromIndex the index from which to start the search (can not be negative).
* @param toIndex the index after the last character where to perform the search.
* @return the index within the text of the first occurrence of a non-space character, starting
* at the specified index, or a value equals or greater than {@code toIndex} if none.
* @throws NullPointerException if the {@code text} argument is null.
*
* @see #skipTrailingWhitespaces(CharSequence, int, int)
* @see #trimWhitespaces(CharSequence)
* @see String#stripLeading()
*/
public static int skipLeadingWhitespaces(final CharSequence text, int fromIndex, final int toIndex) {
while (fromIndex < toIndex) {
final int c = codePointAt(text, fromIndex);
if (!isWhitespace(c)) break;
fromIndex += charCount(c);
}
return fromIndex;
}
/**
* Returns the index <em>after</em> the last non-white character in the given range.
* If the given range contains only space characters, then this method returns the index of the
* first character in the given range, which is always equals or lower than {@code fromIndex}.
*
* <p>Special cases:</p>
* <ul>
* <li>If {@code fromIndex} is lower than {@code toIndex},
* then this method unconditionally returns {@code toIndex}.</li>
* <li>If the given range contains only space characters and the character at {@code fromIndex}
* is the low surrogate of a valid supplementary code point, then this method returns
* {@code fromIndex-1}, which is the index of the code point.</li>
* <li>If {@code fromIndex} is negative or {@code toIndex} is greater than the text length,
* then the behavior of this method is undefined.</li>
* </ul>
*
* Space characters are identified by the {@link Character#isWhitespace(int)} method.
*
* @param text the string in which to perform the search (can not be null).
* @param fromIndex the index from which to start the search (can not be negative).
* @param toIndex the index after the last character where to perform the search.
* @return the index within the text of the last occurrence of a non-space character, starting
* at the specified index, or a value equals or lower than {@code fromIndex} if none.
* @throws NullPointerException if the {@code text} argument is null.
*
* @see #skipLeadingWhitespaces(CharSequence, int, int)
* @see #trimWhitespaces(CharSequence)
* @see String#stripTrailing()
*/
public static int skipTrailingWhitespaces(final CharSequence text, final int fromIndex, int toIndex) {
while (toIndex > fromIndex) {
final int c = codePointBefore(text, toIndex);
if (!isWhitespace(c)) break;
toIndex -= charCount(c);
}
return toIndex;
}
/**
* Allocates the array to be returned by the {@code split(…)} methods. If the given {@code text} argument is
* an instance of {@link String}, {@link StringBuilder} or {@link StringBuffer}, then this method returns a
* {@code String[]} array instead of {@code CharSequence[]}. This is possible because the specification of
* their {@link CharSequence#subSequence(int, int)} method guarantees to return {@code String} instances.
* Some Apache SIS code will cast the {@code split(…)} return value based on this knowledge.
*
* <p>Note that this is a undocumented SIS features. There is currently no commitment that this implementation
* details will not change in future version.</p>
*
* @param text the text to be splitted.
* @return an array where to store the result of splitting the given {@code text}.
*/
private static CharSequence[] createSplitArray(final CharSequence text) {
return (text instanceof String ||
text instanceof StringBuilder ||
text instanceof StringBuffer) ? new String[8] : new CharSequence[8];
}
/**
* Splits a text around the given character. The array returned by this method contains all
* subsequences of the given text that is terminated by the given character or is terminated
* by the end of the text. The subsequences in the array are in the order in which they occur
* in the given text. If the character is not found in the input, then the resulting array has
* just one element, which is the whole given text.
*
* <p>This method is similar to the standard {@link String#split(String)} method except for the
* following:</p>
*
* <ul>
* <li>It accepts generic character sequences.</li>
* <li>It accepts {@code null} argument, in which case an empty array is returned.</li>
* <li>The separator is a simple character instead of a regular expression.</li>
* <li>If the {@code separator} argument is {@code '\n'} or {@code '\r'}, then this method
* splits around any of {@code "\r"}, {@code "\n"} or {@code "\r\n"} characters sequences.
* <li>The leading and trailing spaces of each subsequences are trimmed.</li>
* </ul>
*
* @param text the text to split, or {@code null}.
* @param separator the delimiting character (typically the coma).
* @return the array of subsequences computed by splitting the given text around the given
* character, or an empty array if {@code text} was null.
*
* @see String#split(String)
*/
@SuppressWarnings("ReturnOfCollectionOrArrayField")
public static CharSequence[] split(final CharSequence text, final char separator) {
if (text == null) {
return EMPTY_ARRAY;
}
if (separator == '\n' || separator == '\r') {
final CharSequence[] splitted = splitOnEOL(text);
for (int i=0; i < splitted.length; i++) {
// For consistency with the rest of this method.
splitted[i] = trimWhitespaces(splitted[i]);
}
return splitted;
}
// 'excludeEmpty' must use the same criterion than trimWhitespaces(…).
final boolean excludeEmpty = isWhitespace(separator);
CharSequence[] splitted = createSplitArray(text);
final int length = text.length();
int count = 0, last = 0, i = 0;
while ((i = indexOf(text, separator, i, length)) >= 0) {
final CharSequence item = trimWhitespaces(text, last, i);
if (!excludeEmpty || item.length() != 0) {
if (count == splitted.length) {
splitted = Arrays.copyOf(splitted, count << 1);
}
splitted[count++] = item;
}
last = ++i;
}
// Add the last element.
final CharSequence item = trimWhitespaces(text, last, length);
if (!excludeEmpty || item.length() != 0) {
if (count == splitted.length) {
splitted = Arrays.copyOf(splitted, count + 1);
}
splitted[count++] = item;
}
return ArraysExt.resize(splitted, count);
}
/**
* Splits a text around the <cite>End Of Line</cite> (EOL) characters.
* EOL characters can be any of {@code "\r"}, {@code "\n"} or {@code "\r\n"} sequences.
* Each element in the returned array will be a single line. If the given text is already
* a single line, then this method returns a singleton containing only the given text.
*
* <p>Notes:</p>
* <ul>
* <li>At the difference of <code>{@linkplain #split split}(toSplit, '\n’)</code>,
* this method does not remove whitespaces.</li>
* <li>This method does not check for Unicode
* {@linkplain Characters#LINE_SEPARATOR line separator} and
* {@linkplain Characters#PARAGRAPH_SEPARATOR paragraph separator}.</li>
* </ul>
*
* <div class="note"><b>Performance note:</b>
* Prior JDK8 this method was usually cheap because all string instances created by
* {@link String#substring(int,int)} shared the same {@code char[]} internal array.
* However since JDK8, the new {@code String} implementation copies the data in new arrays.
* Consequently it is better to use index rather than this method for splitting large {@code String}s.
* However this method still useful for other {@link CharSequence} implementations providing an efficient
* {@code subSequence(int,int)} method.</div>
*
* @param text the multi-line text from which to get the individual lines, or {@code null}.
* @return the lines in the text, or an empty array if the given text was null.
*
* @see #indexOfLineStart(CharSequence, int, int)
*/
@SuppressWarnings("ReturnOfCollectionOrArrayField")
public static CharSequence[] splitOnEOL(final CharSequence text) {
if (text == null) {
return EMPTY_ARRAY;
}
/*
* This method is implemented on top of String.indexOf(int,int),
* assuming that it will be faster for String and StringBuilder.
*/
final int length = text.length();
int lf = indexOf(text, '\n', 0, length);
int cr = indexOf(text, '\r', 0, length);
if (lf < 0 && cr < 0) {
return new CharSequence[] {
text
};
}
int count = 0;
CharSequence[] splitted = createSplitArray(text);
int last = 0;
boolean hasMore;
do {
int skip = 1;
final int splitAt;
if (cr < 0) {
// There is no "\r" character in the whole text, only "\n".
splitAt = lf;
hasMore = (lf = indexOf(text, '\n', lf+1, length)) >= 0;
} else if (lf < 0) {
// There is no "\n" character in the whole text, only "\r".
splitAt = cr;
hasMore = (cr = indexOf(text, '\r', cr+1, length)) >= 0;
} else if (lf < cr) {
// There is both "\n" and "\r" characters with "\n" first.
splitAt = lf;
hasMore = true;
lf = indexOf(text, '\n', lf+1, length);
} else {
// There is both "\r" and "\n" characters with "\r" first.
// We need special care for the "\r\n" sequence.
splitAt = cr;
if (lf == ++cr) {
cr = indexOf(text, '\r', cr+1, length);
lf = indexOf(text, '\n', lf+1, length);
hasMore = (cr >= 0 || lf >= 0);
skip = 2;
} else {
cr = indexOf(text, '\r', cr+1, length);
hasMore = true; // Because there is lf.
}
}
if (count >= splitted.length) {
splitted = Arrays.copyOf(splitted, count*2);
}
splitted[count++] = text.subSequence(last, splitAt);
last = splitAt + skip;
} while (hasMore);
/*
* Add the remaining string and we are done.
*/
if (count >= splitted.length) {
splitted = Arrays.copyOf(splitted, count+1);
}
splitted[count++] = text.subSequence(last, text.length());
return ArraysExt.resize(splitted, count);
}
/**
* Returns {@code true} if {@link #split(CharSequence, char)} parsed an empty string.
*/
private static boolean isEmpty(final CharSequence[] tokens) {
switch (tokens.length) {
case 0: return true;
case 1: return tokens[0].length() == 0;
default: return false;
}
}
/**
* {@linkplain #split(CharSequence, char) Splits} the given text around the given character,
* then {@linkplain Double#parseDouble(String) parses} each item as a {@code double}.
* Empty sub-sequences are parsed as {@link Double#NaN}.
*
* @param values the text containing the values to parse, or {@code null}.
* @param separator the delimiting character (typically the coma).
* @return the array of numbers parsed from the given text,
* or an empty array if {@code values} was null.
* @throws NumberFormatException if at least one number can not be parsed.
*/
public static double[] parseDoubles(final CharSequence values, final char separator)
throws NumberFormatException
{
final CharSequence[] tokens = split(values, separator);
if (isEmpty(tokens)) return ArraysExt.EMPTY_DOUBLE;
final double[] parsed = new double[tokens.length];
for (int i=0; i<tokens.length; i++) {
final String token = trimWhitespaces(tokens[i]).toString();
parsed[i] = token.isEmpty() ? Double.NaN : Double.parseDouble(token);
}
return parsed;
}
/**
* {@linkplain #split(CharSequence, char) Splits} the given text around the given character,
* then {@linkplain Float#parseFloat(String) parses} each item as a {@code float}.
* Empty sub-sequences are parsed as {@link Float#NaN}.
*
* @param values the text containing the values to parse, or {@code null}.
* @param separator the delimiting character (typically the coma).
* @return the array of numbers parsed from the given text,
* or an empty array if {@code values} was null.
* @throws NumberFormatException if at least one number can not be parsed.
*/
public static float[] parseFloats(final CharSequence values, final char separator)
throws NumberFormatException
{
final CharSequence[] tokens = split(values, separator);
if (isEmpty(tokens)) return ArraysExt.EMPTY_FLOAT;
final float[] parsed = new float[tokens.length];
for (int i=0; i<tokens.length; i++) {
final String token = trimWhitespaces(tokens[i]).toString();
parsed[i] = token.isEmpty() ? Float.NaN : Float.parseFloat(token);
}
return parsed;
}
/**
* {@linkplain #split(CharSequence, char) Splits} the given text around the given character,
* then {@linkplain Long#parseLong(String) parses} each item as a {@code long}.
*
* @param values the text containing the values to parse, or {@code null}.
* @param separator the delimiting character (typically the coma).
* @param radix the radix to be used for parsing. This is usually 10.
* @return the array of numbers parsed from the given text,
* or an empty array if {@code values} was null.
* @throws NumberFormatException if at least one number can not be parsed.
*/
public static long[] parseLongs(final CharSequence values, final char separator, final int radix)
throws NumberFormatException
{
final CharSequence[] tokens = split(values, separator);
if (isEmpty(tokens)) return ArraysExt.EMPTY_LONG;
final long[] parsed = new long[tokens.length];
for (int i=0; i<tokens.length; i++) {
parsed[i] = Long.parseLong(trimWhitespaces(tokens[i]).toString(), radix);
}
return parsed;
}
/**
* {@linkplain #split(CharSequence, char) Splits} the given text around the given character,
* then {@linkplain Integer#parseInt(String) parses} each item as an {@code int}.
*
* @param values the text containing the values to parse, or {@code null}.
* @param separator the delimiting character (typically the coma).
* @param radix the radix to be used for parsing. This is usually 10.
* @return the array of numbers parsed from the given text,
* or an empty array if {@code values} was null.
* @throws NumberFormatException if at least one number can not be parsed.
*/
public static int[] parseInts(final CharSequence values, final char separator, final int radix)
throws NumberFormatException
{
final CharSequence[] tokens = split(values, separator);
if (isEmpty(tokens)) return ArraysExt.EMPTY_INT;
final int[] parsed = new int[tokens.length];
for (int i=0; i<tokens.length; i++) {
parsed[i] = Integer.parseInt(trimWhitespaces(tokens[i]).toString(), radix);
}
return parsed;
}
/**
* {@linkplain #split(CharSequence, char) Splits} the given text around the given character,
* then {@linkplain Short#parseShort(String) parses} each item as a {@code short}.
*
* @param values the text containing the values to parse, or {@code null}.
* @param separator the delimiting character (typically the coma).
* @param radix the radix to be used for parsing. This is usually 10.
* @return the array of numbers parsed from the given text,
* or an empty array if {@code values} was null.
* @throws NumberFormatException if at least one number can not be parsed.
*/
public static short[] parseShorts(final CharSequence values, final char separator, final int radix)
throws NumberFormatException
{
final CharSequence[] tokens = split(values, separator);
if (isEmpty(tokens)) return ArraysExt.EMPTY_SHORT;
final short[] parsed = new short[tokens.length];
for (int i=0; i<tokens.length; i++) {
parsed[i] = Short.parseShort(trimWhitespaces(tokens[i]).toString(), radix);
}
return parsed;
}
/**
* {@linkplain #split(CharSequence, char) Splits} the given text around the given character,
* then {@linkplain Byte#parseByte(String) parses} each item as a {@code byte}.
*
* @param values the text containing the values to parse, or {@code null}.
* @param separator the delimiting character (typically the coma).
* @param radix the radix to be used for parsing. This is usually 10.
* @return the array of numbers parsed from the given text,
* or an empty array if {@code values} was null.
* @throws NumberFormatException if at least one number can not be parsed.
*/
public static byte[] parseBytes(final CharSequence values, final char separator, final int radix)
throws NumberFormatException
{
final CharSequence[] tokens = split(values, separator);
if (isEmpty(tokens)) return ArraysExt.EMPTY_BYTE;
final byte[] parsed = new byte[tokens.length];
for (int i=0; i<tokens.length; i++) {
parsed[i] = Byte.parseByte(trimWhitespaces(tokens[i]).toString(), radix);
}
return parsed;
}
/**
* Replaces some Unicode characters by ASCII characters on a "best effort basis".
* For example the “ é ” character is replaced by “ e ” (without accent),
* the “ ″ ” symbol for minutes of angle is replaced by straight double quotes “ " ”,
* and combined characters like ㎏, ㎎, ㎝, ㎞, ㎢, ㎦, ㎖, ㎧, ㎩, ㎐, <i>etc.</i> are replaced
* by the corresponding sequences of characters.
*
* <div class="note"><b>Note:</b>
* the replacement of Greek letters is a more complex task than what this method can do,
* since it depends on the context. For example if the Greek letters are abbreviations
* for coordinate system axes like φ and λ, then the replacements depend on the enclosing
* coordinate system. See {@link org.apache.sis.io.wkt.Transliterator} for more information.</div>
*
* @param text the text to scan for Unicode characters to replace by ASCII characters, or {@code null}.
* @return the given text with substitutions applied, or {@code text} if no replacement
* has been applied, or {@code null} if the given text was null.
*
* @see StringBuilders#toASCII(StringBuilder)
* @see org.apache.sis.io.wkt.Transliterator#filter(String)
* @see java.text.Normalizer
*/
public static CharSequence toASCII(final CharSequence text) {
return StringBuilders.toASCII(text, null);
}
/**
* Returns a string with leading and trailing whitespace characters omitted.
* This method is similar in purpose to {@link String#trim()}, except that the later considers
* every {@linkplain Character#isISOControl(int) ISO control codes} below 32 to be a whitespace.
* That {@code String.trim()} behavior has the side effect of removing the heading of ANSI escape
* sequences (a.k.a. X3.64), and to ignore Unicode spaces. This {@code trimWhitespaces(…)} method
* is built on the more accurate {@link Character#isWhitespace(int)} method instead.
*
* <p>This method performs the same work than {@link #trimWhitespaces(CharSequence)},
* but is overloaded for the {@code String} type because of its frequent use.</p>
*
* @param text the text from which to remove leading and trailing whitespaces, or {@code null}.
* @return a string with leading and trailing whitespaces removed, or {@code null} is the given
* text was null.
*
* @todo To be replaced by {@link String#strip()} in JDK 11.
*/
public static String trimWhitespaces(String text) {
if (text != null) {
final int length = text.length();
final int lower = skipLeadingWhitespaces(text, 0, length);
text = text.substring(lower, skipTrailingWhitespaces(text, lower, length));
}
return text;
}
/**
* Returns a text with leading and trailing whitespace characters omitted.
* Space characters are identified by the {@link Character#isWhitespace(int)} method.
*
* <p>This method is the generic version of {@link #trimWhitespaces(String)}.</p>
*
* @param text the text from which to remove leading and trailing whitespaces, or {@code null}.
* @return a characters sequence with leading and trailing whitespaces removed,
* or {@code null} is the given text was null.
*
* @see #skipLeadingWhitespaces(CharSequence, int, int)
* @see #skipTrailingWhitespaces(CharSequence, int, int)
* @see String#strip()
*/
public static CharSequence trimWhitespaces(CharSequence text) {
if (text != null) {
text = trimWhitespaces(text, 0, text.length());
}
return text;
}
/**
* Returns a sub-sequence with leading and trailing whitespace characters omitted.
* Space characters are identified by the {@link Character#isWhitespace(int)} method.
*
* <p>Invoking this method is functionally equivalent to the following code snippet,
* except that the {@link CharSequence#subSequence(int, int) subSequence} method is
* invoked only once instead of two times:</p>
*
* {@preformat java
* text = trimWhitespaces(text.subSequence(lower, upper));
* }
*
* @param text the text from which to remove leading and trailing white spaces.
* @param lower index of the first character to consider for inclusion in the sub-sequence.
* @param upper index after the last character to consider for inclusion in the sub-sequence.
* @return a characters sequence with leading and trailing white spaces removed, or {@code null}
* if the {@code text} argument is null.
* @throws IndexOutOfBoundsException if {@code lower} or {@code upper} is out of bounds.
*/
public static CharSequence trimWhitespaces(CharSequence text, int lower, int upper) {
final int length = length(text);
ArgumentChecks.ensureValidIndexRange(length, lower, upper);
if (text != null) {
lower = skipLeadingWhitespaces (text, lower, upper);
upper = skipTrailingWhitespaces(text, lower, upper);
if (lower != 0 || upper != length) { // Safety in case subSequence doesn't make the check.
text = text.subSequence(lower, upper);
}
}
return text;
}
/**
* Trims the fractional part of the given formatted number, provided that it doesn't change
* the value. This method assumes that the number is formatted in the US locale, typically
* by the {@link Double#toString(double)} method.
*
* <p>More specifically if the given value ends with a {@code '.'} character followed by a
* sequence of {@code '0'} characters, then those characters are omitted. Otherwise this
* method returns the text unchanged. This is a <cite>"all or nothing"</cite> method:
* either the fractional part is completely removed, or either it is left unchanged.</p>
*
* <h4>Examples</h4>
* This method returns {@code "4"} if the given value is {@code "4."}, {@code "4.0"} or
* {@code "4.00"}, but returns {@code "4.10"} unchanged (including the trailing {@code '0'}
* character) if the input is {@code "4.10"}.
*
* <h4>Use case</h4>
* This method is useful before to {@linkplain Integer#parseInt(String) parse a number}
* if that number should preferably be parsed as an integer before attempting to parse
* it as a floating point number.
*
* @param value the value to trim if possible, or {@code null}.
* @return the value without the trailing {@code ".0"} part (if any),
* or {@code null} if the given text was null.
*
* @see StringBuilders#trimFractionalPart(StringBuilder)
*/
public static CharSequence trimFractionalPart(final CharSequence value) {
if (value != null) {
for (int i=value.length(); i>0;) {
final int c = codePointBefore(value, i);
i -= charCount(c);
switch (c) {
case '0': continue;
case '.': return value.subSequence(0, i);
default : return value;
}
}
}
return value;
}
/**
* Makes sure that the {@code text} string is not longer than {@code maxLength} characters.
* If {@code text} is not longer, then it is returned unchanged. Otherwise this method returns
* a copy of {@code text} with some characters substituted by the {@code "(…)"} string.
*
* <p>If the text needs to be shortened, then this method tries to apply the above-cited
* substitution between two words. For example, the following text:</p>
*
* <blockquote>
* "This sentence given as an example is way too long to be included in a short name."
* </blockquote>
*
* May be shortened to something like this:
*
* <blockquote>
* "This sentence given (…) in a short name."
* </blockquote>
*
* @param text the sentence to reduce if it is too long, or {@code null}.
* @param maxLength the maximum length allowed for {@code text}.
* @return a sentence not longer than {@code maxLength}, or {@code null} if the given text was null.
*/
public static CharSequence shortSentence(CharSequence text, final int maxLength) {
ArgumentChecks.ensureStrictlyPositive("maxLength", maxLength);
if (text != null) {
final int length = text.length();
int toRemove = length - maxLength;
if (toRemove > 0) {
toRemove += 5; // Space needed for the " (…) " string.
/*
* We will remove characters from 'lower' to 'upper' both exclusive. We try to
* adjust 'lower' and 'upper' in such a way that the first and last characters
* to be removed will be spaces or punctuation characters.
*/
int lower = length >>> 1;
if (lower != 0 && isLowSurrogate(text.charAt(lower))) {
lower--;
}
int upper = lower;
boolean forward = false;
do { // To be run as long as we need to remove more characters.
int nc=0, type=UNASSIGNED;
forward = !forward;
searchWordBreak: while (true) {
final int c;
if (forward) {
if ((upper += nc) == length) break;
c = codePointAt(text, upper);
} else {
if ((lower -= nc) == 0) break;
c = codePointBefore(text, lower);
}
nc = charCount(c);
if (isWhitespace(c)) {
if (type != UNASSIGNED) {
type = SPACE_SEPARATOR;
}
} else switch (type) {
// After we skipped white, then non-white, then white characters, stop.
case SPACE_SEPARATOR: {
break searchWordBreak;
}
// For the first non-white character, just remember its type.
// Arbitrarily use UPPERCASE_LETTER for any kind of identifier
// part (which include UPPERCASE_LETTER anyway).
case UNASSIGNED: {
type = isUnicodeIdentifierPart(c) ? UPPERCASE_LETTER : getType(c);
break;
}
// If we expected an identifier, stop at the first other char.
case UPPERCASE_LETTER: {
if (!isUnicodeIdentifierPart(c)) {
break searchWordBreak;
}
break;
}
// For all other kind of character, break when the type change.
default: {
if (getType(c) != type) {
break searchWordBreak;
}
break;
}
}
toRemove -= nc;
}
} while (toRemove > 0);
text = new StringBuilder(lower + (length-upper) + 5) // 5 is the length of " (…) "
.append(text, 0, lower).append(" (…) ").append(text, upper, length);
}
}
return text;
}
/**
* Given a string in upper cases (typically a Java constant), returns a string formatted
* like an English sentence. This heuristic method performs the following steps:
*
* <ol>
* <li>Replace all occurrences of {@code '_'} by spaces.</li>
* <li>Converts all letters except the first one to lower case letters using
* {@link Character#toLowerCase(int)}. Note that this method does not use
* the {@link String#toLowerCase()} method. Consequently the system locale
* is ignored. This method behaves as if the conversion were done in the
* {@linkplain java.util.Locale#ROOT root} locale.</li>
* </ol>
*
* <p>Note that those heuristic rules may be modified in future SIS versions,
* depending on the practical experience gained.</p>
*
* @param identifier the name of a Java constant, or {@code null}.
* @return the identifier like an English sentence, or {@code null}
* if the given {@code identifier} argument was null.
*/
public static CharSequence upperCaseToSentence(final CharSequence identifier) {
if (identifier == null) {
return null;
}
final StringBuilder buffer = new StringBuilder(identifier.length());
final int length = identifier.length();
for (int i=0; i<length;) {
int c = codePointAt(identifier, i);
if (i != 0) {
if (c == '_') {
c = ' ';
} else {
c = toLowerCase(c);
}
}
buffer.appendCodePoint(c);
i += charCount(c);
}
return buffer;
}
/**
* Given a string in camel cases (typically an identifier), returns a string formatted
* like an English sentence. This heuristic method performs the following steps:
*
* <ol>
* <li>Invoke {@link #camelCaseToWords(CharSequence, boolean)}, which separate the words
* on the basis of character case. For example {@code "transferFunctionType"} become
* <cite>"transfer function type"</cite>. This works fine for ISO 19115 identifiers.</li>
*
* <li>Next replace all occurrence of {@code '_'} by spaces in order to take in account
* an other common naming convention, which uses {@code '_'} as a word separator. This
* convention is used by netCDF attributes like {@code "project_name"}.</li>
*
* <li>Finally ensure that the first character is upper-case.</li>
* </ol>
*
* <h4>Exception to the above rules</h4>
* If the given identifier contains only upper-case letters, digits and the {@code '_'} character,
* then the identifier is returned "as is" except for the {@code '_'} characters which are replaced by {@code '-'}.
* This work well for identifiers like {@code "UTF-8"} or {@code "ISO-LATIN-1"} for instance.
*
* <p>Note that those heuristic rules may be modified in future SIS versions,
* depending on the practical experience gained.</p>
*
* @param identifier an identifier with no space, words begin with an upper-case character, or {@code null}.
* @return the identifier with spaces inserted after what looks like words, or {@code null}
* if the given {@code identifier} argument was null.
*/
public static CharSequence camelCaseToSentence(final CharSequence identifier) {
if (identifier == null) {
return null;
}
final StringBuilder buffer;
if (isCode(identifier)) {
if (identifier instanceof String) {
return ((String) identifier).replace('_', '-');
}
buffer = new StringBuilder(identifier);
StringBuilders.replace(buffer, '_', '-');
} else {
buffer = (StringBuilder) camelCaseToWords(identifier, true);
final int length = buffer.length();
if (length != 0) {
StringBuilders.replace(buffer, '_', ' ');
final int c = buffer.codePointAt(0);
final int up = toUpperCase(c);
if (c != up) {
StringBuilders.replace(buffer, 0, charCount(c), toChars(up));
}
}
}
return buffer;
}
/**
* Given a string in camel cases, returns a string with the same words separated by spaces.
* A word begins with a upper-case character following a lower-case character. For example
* if the given string is {@code "PixelInterleavedSampleModel"}, then this method returns
* <cite>"Pixel Interleaved Sample Model"</cite> or <cite>"Pixel interleaved sample model"</cite>
* depending on the value of the {@code toLowerCase} argument.
*
* <p>If {@code toLowerCase} is {@code false}, then this method inserts spaces but does not change
* the case of characters. If {@code toLowerCase} is {@code true}, then this method changes
* {@linkplain Character#toLowerCase(int) to lower case} the first character after each spaces
* inserted by this method (note that this intentionally exclude the very first character in
* the given string), except if the second character {@linkplain Character#isUpperCase(int)
* is upper case}, in which case the word is assumed an acronym.</p>
*
* <p>The given string is usually a programmatic identifier like a class name or a method name.</p>
*
* @param identifier an identifier with no space, words begin with an upper-case character.
* @param toLowerCase {@code true} for changing the first character of words to lower case,
* except for the first word and acronyms.
* @return the identifier with spaces inserted after what looks like words, or {@code null}
* if the given {@code identifier} argument was null.
*/
public static CharSequence camelCaseToWords(final CharSequence identifier, final boolean toLowerCase) {
if (identifier == null) {
return null;
}
/*
* Implementation note: the 'camelCaseToSentence' method needs
* this method to unconditionally returns a new StringBuilder.
*/
final int length = identifier.length();
final StringBuilder buffer = new StringBuilder(length + 8);
final int lastIndex = (length != 0) ? length - charCount(codePointBefore(identifier, length)) : 0;
int last = 0;
for (int i=1; i<=length;) {
final int cp;
final boolean doAppend;
if (i == length) {
cp = 0;
doAppend = true;
} else {
cp = codePointAt(identifier, i);
doAppend = Character.isUpperCase(cp) && isLowerCase(codePointBefore(identifier, i));
}
if (doAppend) {
final int pos = buffer.length();
buffer.append(identifier, last, i).append(' ');
if (toLowerCase && pos!=0 && last<lastIndex && isLowerCase(codePointAfter(identifier, last))) {
final int c = buffer.codePointAt(pos);
final int low = toLowerCase(c);
if (c != low) {
StringBuilders.replace(buffer, pos, pos + charCount(c), toChars(low));
}
}
last = i;
}
i += charCount(cp);
}
/*
* Removes the trailing space, if any.
*/
final int lg = buffer.length();
if (lg != 0) {
final int cp = buffer.codePointBefore(lg);
if (isWhitespace(cp)) {
buffer.setLength(lg - charCount(cp));
}
}
return buffer;
}
/**
* Creates an acronym from the given text. This method returns a string containing the first character of each word,
* where the words are separated by the camel case convention, the {@code '_'} character, or any character which is
* not a {@linkplain Character#isUnicodeIdentifierPart(int) Unicode identifier part} (including spaces).
*
* <p>An exception to the above rule happens if the given text is a Unicode identifier without the {@code '_'}
* character, and every characters are upper case. In such case the text is returned unchanged on the assumption
* that it is already an acronym.</p>
*
* <p><b>Examples:</b> given {@code "northEast"}, this method returns {@code "NE"}.
* Given {@code "Open Geospatial Consortium"}, this method returns {@code "OGC"}.</p>
*
* @param text the text for which to create an acronym, or {@code null}.
* @return the acronym, or {@code null} if the given text was null.
*/
public static CharSequence camelCaseToAcronym(CharSequence text) {
text = trimWhitespaces(text);
if (text != null && !isAcronym(text)) {
final int length = text.length();
final StringBuilder buffer = new StringBuilder(8); // Acronyms are usually short.
boolean wantChar = true;
for (int i=0; i<length;) {
final int c = codePointAt(text, i);
if (wantChar) {
if (isUnicodeIdentifierStart(c)) {
buffer.appendCodePoint(c);
wantChar = false;
}
} else if (!isUnicodeIdentifierPart(c) || c == '_') {
wantChar = true;
} else if (Character.isUpperCase(c)) {
// Test for mixed-case (e.g. "northEast").
// Note that i is guaranteed to be greater than 0 here.
if (!Character.isUpperCase(codePointBefore(text, i))) {
buffer.appendCodePoint(c);
}
}
i += charCount(c);
}
final int acrlg = buffer.length();
if (acrlg != 0) {
/*
* If every characters except the first one are upper-case, ensure that the
* first one is upper-case as well. This is for handling the identifiers which
* are compliant to Java-Beans convention (e.g. "northEast").
*/
if (isUpperCase(buffer, 1, acrlg, true)) {
final int c = buffer.codePointAt(0);
final int up = toUpperCase(c);
if (c != up) {
StringBuilders.replace(buffer, 0, charCount(c), toChars(up));
}
}
if (!equals(text, buffer)) {
text = buffer;
}
}
}
return text;
}
/**
* Returns {@code true} if the first string is likely to be an acronym of the second string.
* An acronym is a sequence of {@linkplain Character#isLetterOrDigit(int) letters or digits}
* built from at least one character of each word in the {@code words} string. More than
* one character from the same word may appear in the acronym, but they must always
* be the first consecutive characters. The comparison is case-insensitive.
*
* <div class="note"><b>Example:</b>
* Given the {@code "Open Geospatial Consortium"} words, the following strings are recognized as acronyms:
* {@code "OGC"}, {@code "ogc"}, {@code "O.G.C."}, {@code "OpGeoCon"}.</div>
*
* If any of the given arguments is {@code null}, this method returns {@code false}.
*
* @param acronym a possible acronym of the sequence of words, or {@code null}.
* @param words the sequence of words, or {@code null}.
* @return {@code true} if the first string is an acronym of the second one.
*/
public static boolean isAcronymForWords(final CharSequence acronym, final CharSequence words) {
final int lga = length(acronym);
int ia=0, ca;
do {
if (ia >= lga) return false;
ca = codePointAt(acronym, ia);
ia += charCount(ca);
} while (!isLetterOrDigit(ca));
final int lgc = length(words);
int ic=0, cc;
do {
if (ic >= lgc) return false;
cc = codePointAt(words, ic);
ic += charCount(cc);
}
while (!isLetterOrDigit(cc));
if (toUpperCase(ca) != toUpperCase(cc)) {
// The first letter must match.
return false;
}
cmp: while (ia < lga) {
if (ic >= lgc) {
// There is more letters in the acronym than in the complete name.
return false;
}
ca = codePointAt(acronym, ia); ia += charCount(ca);
cc = codePointAt(words, ic); ic += charCount(cc);
if (isLetterOrDigit(ca)) {
if (toUpperCase(ca) == toUpperCase(cc)) {
// Acronym letter matches the letter from the complete name.
// Continue the comparison with next letter of both strings.
continue;
}
// Will search for the next word after the 'else' block.
} else do {
if (ia >= lga) break cmp;
ca = codePointAt(acronym, ia);
ia += charCount(ca);
} while (!isLetterOrDigit(ca));
/*
* At this point, 'ca' is the next acronym letter to compare and we
* need to search for the next word in the complete name. We first
* skip remaining letters, then we skip non-letter characters.
*/
boolean skipLetters = true;
do while (isLetterOrDigit(cc) == skipLetters) {
if (ic >= lgc) {
return false;
}
cc = codePointAt(words, ic);
ic += charCount(cc);
} while ((skipLetters = !skipLetters) == false);
// Now that we are aligned on a new word, the first letter must match.
if (toUpperCase(ca) != toUpperCase(cc)) {
return false;
}
}
/*
* Now that we have processed all acronym letters, the complete name can not have
* any additional word. We can only finish the current word and skip trailing non-
* letter characters.
*/
boolean skipLetters = true;
do {
do {
if (ic >= lgc) return true;
cc = codePointAt(words, ic);
ic += charCount(cc);
} while (isLetterOrDigit(cc) == skipLetters);
} while ((skipLetters = !skipLetters) == false);
return false;
}
/**
* Returns {@code true} if the given string contains only upper case letters or digits.
* A few punctuation characters like {@code '_'} and {@code '.'} are also accepted.
*
* <p>This method is used for identifying character strings that are likely to be code
* like {@code "UTF-8"} or {@code "ISO-LATIN-1"}.</p>
*
* @see #isUnicodeIdentifier(CharSequence)
*/
private static boolean isCode(final CharSequence identifier) {
for (int i=identifier.length(); --i>=0;) {
final char c = identifier.charAt(i);
// No need to use the code point API here, since the conditions
// below are requiring the characters to be in the basic plane.
if (!((c >= 'A' && c <= 'Z') || (c >= '-' && c <= ':') || c == '_')) {
return false;
}
}
return true;
}
/**
* Returns {@code true} if the given text is presumed to be an acronym. Acronyms are presumed
* to be valid Unicode identifiers in all upper-case letters and without the {@code '_'} character.
*
* @see #camelCaseToAcronym(CharSequence)
*/
private static boolean isAcronym(final CharSequence text) {
return isUpperCase(text) && indexOf(text, '_', 0, text.length()) < 0 && isUnicodeIdentifier(text);
}
/**
* Returns {@code true} if the given identifier is a legal Unicode identifier.
* This method returns {@code true} if the identifier length is greater than zero,
* the first character is a {@linkplain Character#isUnicodeIdentifierStart(int)
* Unicode identifier start} and all remaining characters (if any) are
* {@linkplain Character#isUnicodeIdentifierPart(int) Unicode identifier parts}.
*
* <h4>Relationship with legal XML identifiers</h4>
* Most legal Unicode identifiers are also legal XML identifiers, but the converse is not true.
* The most noticeable differences are the ‘{@code :}’, ‘{@code -}’ and ‘{@code .}’ characters,
* which are legal in XML identifiers but not in Unicode.
*
* <table class="sis">
* <caption>Characters legal in one set but not in the other</caption>
* <tr><th colspan="2">Not legal in Unicode</th> <th class="sep" colspan="2">Not legal in XML</th></tr>
* <tr><td>{@code :}</td><td>(colon)</td> <td class="sep">{@code µ}</td><td>(micro sign)</td></tr>
* <tr><td>{@code -}</td><td>(hyphen or minus)</td> <td class="sep">{@code ª}</td><td>(feminine ordinal indicator)</td></tr>
* <tr><td>{@code .}</td><td>(dot)</td> <td class="sep">{@code º}</td><td>(masculine ordinal indicator)</td></tr>
* <tr><td>{@code ·}</td><td>(middle dot)</td> <td class="sep">{@code ⁔}</td><td>(inverted undertie)</td></tr>
* <tr>
* <td colspan="2">Many punctuation, symbols, <i>etc</i>.</td>
* <td colspan="2" class="sep">{@linkplain Character#isIdentifierIgnorable(int) Identifier ignorable} characters.</td>
* </tr>
* </table>
*
* Note that the ‘{@code _}’ (underscore) character is legal according both Unicode and XML, while spaces,
* ‘{@code !}’, ‘{@code #}’, ‘{@code *}’, ‘{@code /}’, ‘{@code ?}’ and most other punctuation characters are not.
*
* <h4>Usage in Apache SIS</h4>
* In its handling of {@linkplain org.apache.sis.referencing.ImmutableIdentifier identifiers}, Apache SIS favors
* Unicode identifiers without {@linkplain Character#isIdentifierIgnorable(int) ignorable} characters since those
* identifiers are legal XML identifiers except for the above-cited rarely used characters. As a side effect,
* this policy excludes ‘{@code :}’, ‘{@code -}’ and ‘{@code .}’ which would normally be legal XML identifiers.
* But since those characters could easily be confused with
* {@linkplain org.apache.sis.util.iso.DefaultNameSpace#DEFAULT_SEPARATOR namespace separators},
* this exclusion is considered desirable.
*
* @param identifier the character sequence to test, or {@code null}.
* @return {@code true} if the given character sequence is a legal Unicode identifier.
*
* @see org.apache.sis.referencing.ImmutableIdentifier
* @see org.apache.sis.metadata.iso.citation.Citations#toCodeSpace(Citation)
* @see org.apache.sis.referencing.IdentifiedObjects#getSimpleNameOrIdentifier(IdentifiedObject)
*/
public static boolean isUnicodeIdentifier(final CharSequence identifier) {
final int length = length(identifier);
if (length == 0) {
return false;
}
int c = codePointAt(identifier, 0);
if (!isUnicodeIdentifierStart(c)) {
return false;
}
for (int i=0; (i += charCount(c)) < length;) {
c = codePointAt(identifier, i);
if (!isUnicodeIdentifierPart(c)) {
return false;
}
}
return true;
}
/**
* Returns {@code true} if the given text is non-null, contains at least one upper-case character and
* no lower-case character. Space and punctuation are ignored.
*
* @param text the character sequence to test (may be {@code null}).
* @return {@code true} if non-null, contains at least one upper-case character and no lower-case character.
*
* @see String#toUpperCase()
*
* @since 0.7
*/
public static boolean isUpperCase(final CharSequence text) {
return isUpperCase(text, 0, length(text), false);
}
/**
* Returns {@code true} if the given sub-sequence is non-null, contains at least one upper-case character and
* no lower-case character. Space and punctuation are ignored.
*
* @param text the character sequence to test.
* @param lower index of the first character to check, inclusive.
* @param upper index of the last character to check, exclusive.
* @param hasUpperCase {@code true} if this method should behave as if the given text already had
* at least one upper-case character (not necessarily in the portion given by the indices).
* @return {@code true} if contains at least one upper-case character and no lower-case character.
*/
private static boolean isUpperCase(final CharSequence text, int lower, final int upper, boolean hasUpperCase) {
while (lower < upper) {
final int c = codePointAt(text, lower);
if (Character.isLowerCase(c)) {
return false;
}
if (!hasUpperCase) {
hasUpperCase = Character.isUpperCase(c);
}
lower += charCount(c);
}
return hasUpperCase;
}
/**
* Returns {@code true} if the given texts are equal, optionally ignoring case and filtered-out characters.
* This method is sometime used for comparing identifiers in a lenient way.
*
* <p><b>Example:</b> the following call compares the two strings ignoring case and any
* characters which are not {@linkplain Character#isLetterOrDigit(int) letter or digit}.
* In particular, spaces and punctuation characters like {@code '_'} and {@code '-'} are
* ignored:</p>
*
* {@preformat java
* assert equalsFiltered("WGS84", "WGS_84", Characters.Filter.LETTERS_AND_DIGITS, true) == true;
* }
*
* @param s1 the first characters sequence to compare, or {@code null}.
* @param s2 the second characters sequence to compare, or {@code null}.
* @param filter the subset of characters to compare, or {@code null} for comparing all characters.
* @param ignoreCase {@code true} for ignoring cases, or {@code false} for requiring exact match.
* @return {@code true} if both arguments are {@code null} or if the two given texts are equal,
* optionally ignoring case and filtered-out characters.
*/
public static boolean equalsFiltered(final CharSequence s1, final CharSequence s2,
final Characters.Filter filter, final boolean ignoreCase)
{
if (s1 == s2) {
return true;
}
if (s1 == null || s2 == null) {
return false;
}
if (filter == null) {
return ignoreCase ? equalsIgnoreCase(s1, s2) : equals(s1, s2);
}
final int lg1 = s1.length();
final int lg2 = s2.length();
int i1 = 0, i2 = 0;
while (i1 < lg1) {
int c1 = codePointAt(s1, i1);
final int n = charCount(c1);
if (filter.contains(c1)) {
int c2; // Fetch the next significant character from the second string.
do {
if (i2 >= lg2) {
return false; // The first string has more significant characters than expected.
}
c2 = codePointAt(s2, i2);
i2 += charCount(c2);
} while (!filter.contains(c2));
// Compare the characters in the same way than String.equalsIgnoreCase(String).
if (c1 != c2 && !(ignoreCase && equalsIgnoreCase(c1, c2))) {
return false;
}
}
i1 += n;
}
while (i2 < lg2) {
final int s = codePointAt(s2, i2);
if (filter.contains(s)) {
return false; // The first string has less significant characters than expected.
}
i2 += charCount(s);
}
return true;
}
/**
* Returns {@code true} if the given code points are equal, ignoring case.
* This method implements the same comparison algorithm than String#equalsIgnoreCase(String).
*
* <p>This method does not verify if {@code c1 == c2}. This check should have been done
* by the caller, since the caller code is a more optimal place for this check.</p>
*/
private static boolean equalsIgnoreCase(int c1, int c2) {
c1 = toUpperCase(c1);
c2 = toUpperCase(c2);
if (c1 == c2) {
return true;
}
// Need this check for Georgian alphabet.
return toLowerCase(c1) == toLowerCase(c2);
}
/**
* Returns {@code true} if the two given texts are equal, ignoring case.
* This method is similar to {@link String#equalsIgnoreCase(String)}, except
* it works on arbitrary character sequences and compares <cite>code points</cite>
* instead of characters.
*
* @param s1 the first string to compare, or {@code null}.
* @param s2 the second string to compare, or {@code null}.
* @return {@code true} if the two given texts are equal, ignoring case,
* or if both arguments are {@code null}.
*
* @see String#equalsIgnoreCase(String)
*/
public static boolean equalsIgnoreCase(final CharSequence s1, final CharSequence s2) {
if (s1 == s2) {
return true;
}
if (s1 == null || s2 == null) {
return false;
}
// Do not check for String cases. We do not want to delegate to String.equalsIgnoreCase
// because we compare code points while String.equalsIgnoreCase compares characters.
final int lg1 = s1.length();
final int lg2 = s2.length();
int i1 = 0, i2 = 0;
while (i1<lg1 && i2<lg2) {
final int c1 = codePointAt(s1, i1);
final int c2 = codePointAt(s2, i2);
if (c1 != c2 && !equalsIgnoreCase(c1, c2)) {
return false;
}
i1 += charCount(c1);
i2 += charCount(c2);
}
return i1 == i2;
}
/**
* Returns {@code true} if the two given texts are equal. This method delegates to
* {@link String#contentEquals(CharSequence)} if possible. This method never invoke
* {@link CharSequence#toString()} in order to avoid a potentially large copy of data.
*
* @param s1 the first string to compare, or {@code null}.
* @param s2 the second string to compare, or {@code null}.
* @return {@code true} if the two given texts are equal, or if both arguments are {@code null}.
*
* @see String#contentEquals(CharSequence)
*/
public static boolean equals(final CharSequence s1, final CharSequence s2) {
if (s1 == s2) {
return true;
}
if (s1 != null && s2 != null) {
if (s1 instanceof String) return ((String) s1).contentEquals(s2);
if (s2 instanceof String) return ((String) s2).contentEquals(s1);
final int length = s1.length();
if (s2.length() == length) {
for (int i=0; i<length; i++) {
if (s1.charAt(i) != s2.charAt(i)) {
return false;
}
}
return true;
}
}
return false;
}
/**
* Returns {@code true} if the given text at the given offset contains the given part,
* in a case-sensitive comparison. This method is equivalent to the following code,
* except that this method works on arbitrary {@link CharSequence} objects instead of
* {@link String}s only:
*
* {@preformat java
* return text.regionMatches(offset, part, 0, part.length());
* }
*
* This method does not thrown {@code IndexOutOfBoundsException}. Instead if
* {@code fromIndex < 0} or {@code fromIndex + part.length() > text.length()},
* then this method returns {@code false}.
*
* @param text the character sequence for which to tests for the presence of {@code part}.
* @param fromIndex the offset in {@code text} where to test for the presence of {@code part}.
* @param part the part which may be present in {@code text}.
* @return {@code true} if {@code text} contains {@code part} at the given {@code offset}.
* @throws NullPointerException if any of the arguments is null.
*
* @see String#regionMatches(int, String, int, int)
*/
public static boolean regionMatches(final CharSequence text, final int fromIndex, final CharSequence part) {
if (text instanceof String && part instanceof String) {
// It is okay to delegate to String implementation since we do not ignore cases.
return ((String) text).startsWith((String) part, fromIndex);
}
final int length;
if (fromIndex < 0 || fromIndex + (length = part.length()) > text.length()) {
return false;
}
for (int i=0; i<length; i++) {
// No need to use the code point API here, since we are looking for exact matches.
if (text.charAt(fromIndex + i) != part.charAt(i)) {
return false;
}
}
return true;
}
/**
* Returns {@code true} if the given text at the given offset contains the given part,
* optionally in a case-insensitive way. This method is equivalent to the following code,
* except that this method works on arbitrary {@link CharSequence} objects instead of
* {@link String}s only:
*
* {@preformat java
* return text.regionMatches(ignoreCase, offset, part, 0, part.length());
* }
*
* This method does not thrown {@code IndexOutOfBoundsException}. Instead if
* {@code fromIndex < 0} or {@code fromIndex + part.length() > text.length()},
* then this method returns {@code false}.
*
* @param text the character sequence for which to tests for the presence of {@code part}.
* @param fromIndex the offset in {@code text} where to test for the presence of {@code part}.
* @param part the part which may be present in {@code text}.
* @param ignoreCase {@code true} if the case should be ignored.
* @return {@code true} if {@code text} contains {@code part} at the given {@code offset}.
* @throws NullPointerException if any of the arguments is null.
*
* @see String#regionMatches(boolean, int, String, int, int)
*
* @since 0.4
*/
public static boolean regionMatches(final CharSequence text, int fromIndex, final CharSequence part, final boolean ignoreCase) {
if (!ignoreCase) {
return regionMatches(text, fromIndex, part);
}
// Do not check for String cases. We do not want to delegate to String.regionMatches
// because we compare code points while String.regionMatches(…) compares characters.
final int limit = text.length();
final int length = part.length();
if (fromIndex < 0) { // Not checked before because we want NullPointerException if an argument is null.
return false;
}
for (int i=0; i<length;) {
if (fromIndex >= limit) {
return false;
}
final int c1 = codePointAt(part, i);
final int c2 = codePointAt(text, fromIndex);
if (c1 != c2 && !equalsIgnoreCase(c1, c2)) {
return false;
}
fromIndex += charCount(c2);
i += charCount(c1);
}
return true;
}
/**
* Returns {@code true} if the given character sequence starts with the given prefix.
*
* @param text the characters sequence to test.
* @param prefix the expected prefix.
* @param ignoreCase {@code true} if the case should be ignored.
* @return {@code true} if the given sequence starts with the given prefix.
* @throws NullPointerException if any of the arguments is null.
*/
public static boolean startsWith(final CharSequence text, final CharSequence prefix, final boolean ignoreCase) {
return regionMatches(text, 0, prefix, ignoreCase);
}
/**
* Returns {@code true} if the given character sequence ends with the given suffix.
*
* @param text the characters sequence to test.
* @param suffix the expected suffix.
* @param ignoreCase {@code true} if the case should be ignored.
* @return {@code true} if the given sequence ends with the given suffix.
* @throws NullPointerException if any of the arguments is null.
*/
public static boolean endsWith(final CharSequence text, final CharSequence suffix, final boolean ignoreCase) {
int is = text.length();
int ip = suffix.length();
while (ip > 0) {
if (is <= 0) {
return false;
}
final int cs = codePointBefore(text, is);
final int cp = codePointBefore(suffix, ip);
if (cs != cp && (!ignoreCase || !equalsIgnoreCase(cs, cp))) {
return false;
}
is -= charCount(cs);
ip -= charCount(cp);
}
return true;
}
/**
* Returns the longest sequence of characters which is found at the beginning of the two given texts.
* If one of those texts is {@code null}, then the other text is returned.
* If there is no common prefix, then this method returns an empty string.
*
* @param s1 the first text, or {@code null}.
* @param s2 the second text, or {@code null}.
* @return the common prefix of both texts (may be empty), or {@code null} if both texts are null.
*/
public static CharSequence commonPrefix(final CharSequence s1, final CharSequence s2) {
if (s1 == null) return s2;
if (s2 == null) return s1;
final CharSequence shortest;
final int lg1 = s1.length();
final int lg2 = s2.length();
final int length;
if (lg1 <= lg2) {
shortest = s1;
length = lg1;
} else {
shortest = s2;
length = lg2;
}
int i = 0;
while (i < length) {
// No need to use the codePointAt API here, since we are looking for exact matches.
if (s1.charAt(i) != s2.charAt(i)) {
break;
}
i++;
}
return shortest.subSequence(0, i);
}
/**
* Returns the longest sequence of characters which is found at the end of the two given texts.
* If one of those texts is {@code null}, then the other text is returned.
* If there is no common suffix, then this method returns an empty string.
*
* @param s1 the first text, or {@code null}.
* @param s2 the second text, or {@code null}.
* @return the common suffix of both texts (may be empty), or {@code null} if both texts are null.
*/
public static CharSequence commonSuffix(final CharSequence s1, final CharSequence s2) {
if (s1 == null) return s2;
if (s2 == null) return s1;
final CharSequence shortest;
final int lg1 = s1.length();
final int lg2 = s2.length();
final int length;
if (lg1 <= lg2) {
shortest = s1;
length = lg1;
} else {
shortest = s2;
length = lg2;
}
int i = 0;
while (++i <= length) {
// No need to use the codePointAt API here, since we are looking for exact matches.
if (s1.charAt(lg1 - i) != s2.charAt(lg2 - i)) {
break;
}
}
i--;
return shortest.subSequence(length - i, shortest.length());
}
/**
* Returns the words found at the beginning and end of both texts.
* The returned string is the concatenation of the {@linkplain #commonPrefix common prefix}
* with the {@linkplain #commonSuffix common suffix}, with prefix and suffix eventually made
* shorter for avoiding to cut in the middle of a word.
*
* <p>The purpose of this method is to create a global identifier from a list of component identifiers.
* The later are often eastward and northward components of a vector, in which case this method provides
* an identifier for the vector as a whole.</p>
*
* <div class="note"><b>Example:</b>
* given the following inputs:
* <ul>
* <li>{@code "baroclinic_eastward_velocity"}</li>
* <li>{@code "baroclinic_northward_velocity"}</li>
* </ul>
* This method returns {@code "baroclinic_velocity"}. Note that the {@code "ward"} characters
* are a common suffix of both texts but nevertheless omitted because they cut a word.</div>
*
* <p>If one of those texts is {@code null}, then the other text is returned.
* If there is no common words, then this method returns an empty string.</p>
*
* <h4>Possible future evolution</h4>
* Current implementation searches only for a common prefix and a common suffix, ignoring any common words
* that may appear in the middle of the strings. A character is considered the beginning of a word if it is
* {@linkplain Character#isLetterOrDigit(int) a letter or digit} which is not preceded by another letter or
* digit (as leading "s" and "c" in "snake_case"), or if it is an {@linkplain Character#isUpperCase(int)
* upper case} letter preceded by a {@linkplain Character#isLowerCase(int) lower case} letter or no letter
* (as both "C" in "CamelCase").
*
* @param s1 the first text, or {@code null}.
* @param s2 the second text, or {@code null}.
* @return the common suffix of both texts (may be empty), or {@code null} if both texts are null.
*
* @since 1.1
*/
public static CharSequence commonWords(final CharSequence s1, final CharSequence s2) {
final int lg1 = length(s1);
final int lg2 = length(s2);
final int shortestLength = Math.min(lg1, lg2); // 0 if s1 or s2 is null, in which case prefix and suffix will have the other value.
final CharSequence prefix = commonPrefix(s1, s2); int prefixLength = length(prefix); if (prefixLength >= shortestLength) return prefix;
final CharSequence suffix = commonSuffix(s1, s2); int suffixLength = length(suffix); if (suffixLength >= shortestLength) return suffix;
final int length = prefixLength + suffixLength;
if (length >= lg1) return s1; // Check if one of the strings is already equal to prefix + suffix.
if (length >= lg2) return s2;
/*
* At this point `s1` and `s2` contain at least one character between the prefix and the suffix.
* If the prefix or the suffix seems to stop in the middle of a word, skip the remaining of that word.
* For example if `s1` and `s2` are "eastward_velocity" and "northward_velocity", the common suffix is
* "ward_velocity" but we want to retain only "velocity".
*
* The first condition below (before the loop) checks the character after the common prefix (for example "e"
* in "baroclinic_eastward_velocity" if the prefix is "baroclinic_"). The intent is to handle the case where
* the word separator is not the same (e.g. "baroclinic_eastward_velocity" and "baroclinic northward velocity",
* in which case the '_' or ' ' character would not appear in the prefix).
*/
if (!isWordBoundary(s1, prefixLength, codePointAt(s1, prefixLength)) &&
!isWordBoundary(s2, prefixLength, codePointAt(s2, prefixLength)))
{
while (prefixLength > 0) {
final int c = codePointBefore(prefix, prefixLength);
final int n = charCount(c);
prefixLength -= n;
if (isWordBoundary(prefix, prefixLength, c)) {
if (!isLetterOrDigit(c)) prefixLength += n; // Keep separator character.
break;
}
}
}
/*
* Same process than for the prefix above. The condition before the loop checks the character before suffix
* for the same reason than above, but using only `isLetterOrDigit` ignoring camel-case. The reason is that
* if the character before was a word separator according camel-case convention (i.e. an upper-case letter),
* we would need to include it in the common suffix.
*/
int suffixStart = 0;
if (isLetterOrDigit(codePointBefore(s1, lg1 - suffixLength)) &&
isLetterOrDigit(codePointBefore(s2, lg2 - suffixLength)))
{
while (suffixStart < suffixLength) {
final int c = codePointAt(suffix, suffixStart);
if (isWordBoundary(suffix, suffixStart, c)) break;
suffixStart += charCount(c);
}
}
/*
* At this point we got the final prefix and suffix to use. If the prefix or suffix is empty,
* trim whitespaces or '_' character. For example if the suffix is "_velocity" and no prefix,
* return "velocity" without leading "_" character.
*/
if (prefixLength == 0) {
while (suffixStart < suffixLength) {
final int c = codePointAt(suffix, suffixStart);
if (isLetterOrDigit(c)) {
return suffix.subSequence(suffixStart, suffixLength); // Skip leading ignorable characters in suffix.
}
suffixStart += charCount(c);
}
return "";
}
if (suffixStart >= suffixLength) {
while (prefixLength > 0) {
final int c = codePointBefore(prefix, prefixLength);
if (isLetterOrDigit(c)) {
return prefix.subSequence(0, prefixLength); // Skip trailing ignorable characters in prefix.
}
prefixLength -= charCount(c);
}
return "";
}
/*
* All special cases have been examined. Return the concatenation of (possibly shortened)
* common prefix and suffix.
*/
final StringBuilder buffer = new StringBuilder(prefixLength + suffixLength).append(prefix);
final int c1 = codePointBefore(prefix, prefixLength);
final int c2 = codePointAt(suffix, suffixStart);
if (isLetterOrDigit(c1) && isLetterOrDigit(c2)) {
if (!Character.isUpperCase(c2) || !isLowerCase(c1)) {
buffer.append(' '); // Keep a separator between two words (except if CamelCase is used).
}
} else if (c1 == c2) {
suffixStart += charCount(c2); // Avoid repeating '_' in e.g. "baroclinic_<removed>_velocity".
}
return buffer.append(suffix, suffixStart, suffixLength).toString();
}
/**
* Returns {@code true} if the character {@code c} is the beginning of a word or a non-word character.
* For example this method returns {@code true} if {@code c} is {@code '_'} in {@code "snake_case"} or
* {@code "C"} in {@code "CamelCase"}.
*
* @param s the character sequence from which the {@code c} character has been obtained.
* @param i the index in {@code s} where the {@code c} character has been obtained.
* @param c the code point in {@code s} as index {@code i}.
* @return whether the given character is the beginning of a word or a non-word character.
*/
private static boolean isWordBoundary(final CharSequence s, final int i, final int c) {
if (!isLetterOrDigit(c)) return true;
if (!Character.isUpperCase(c)) return false;
return (i <= 0 || isLowerCase(codePointBefore(s, i)));
}
/**
* Returns the token starting at the given offset in the given text. For the purpose of this
* method, a "token" is any sequence of consecutive characters of the same type, as defined
* below.
*
* <p>Let define <var>c</var> as the first non-blank character located at an index equals or
* greater than the given offset. Then the characters that are considered of the same type
* are:</p>
*
* <ul>
* <li>If <var>c</var> is a
* {@linkplain Character#isUnicodeIdentifierStart(int) Unicode identifier start},
* then any following characters that are
* {@linkplain Character#isUnicodeIdentifierPart(int) Unicode identifier part}.</li>
* <li>Otherwise any character for which {@link Character#getType(int)} returns
* the same value than for <var>c</var>.</li>
* </ul>
*
* @param text the text for which to get the token.
* @param fromIndex index of the fist character to consider in the given text.
* @return a sub-sequence of {@code text} starting at the given offset, or an empty string
* if there is no non-blank character at or after the given offset.
* @throws NullPointerException if the {@code text} argument is null.
*/
public static CharSequence token(final CharSequence text, int fromIndex) {
final int length = text.length();
int upper = fromIndex;
/*
* Skip whitespaces. At the end of this loop,
* 'c' will be the first non-blank character.
*/
int c;
do {
if (upper >= length) return "";
c = codePointAt(text, upper);
fromIndex = upper;
upper += charCount(c);
}
while (isWhitespace(c));
/*
* Advance over all characters "of the same type".
*/
if (isUnicodeIdentifierStart(c)) {
while (upper<length && isUnicodeIdentifierPart(c = codePointAt(text, upper))) {
upper += charCount(c);
}
} else {
final int type = getType(codePointAt(text, fromIndex));
while (upper<length && getType(c = codePointAt(text, upper)) == type) {
upper += charCount(c);
}
}
return text.subSequence(fromIndex, upper);
}
/**
* Replaces all occurrences of a given string in the given character sequence. If no occurrence of
* {@code toSearch} is found in the given text or if {@code toSearch} is equal to {@code replaceBy},
* then this method returns the {@code text} unchanged.
* Otherwise this method returns a new character sequence with all occurrences replaced by {@code replaceBy}.
*
* <p>This method is similar to {@link String#replace(CharSequence, CharSequence)} except that is accepts
* arbitrary {@code CharSequence} objects. As of Java 10, another difference is that this method does not
* create a new {@code String} if {@code toSearch} is equals to {@code replaceBy}.</p>
*
* @param text the character sequence in which to perform the replacements, or {@code null}.
* @param toSearch the string to replace.
* @param replaceBy the replacement for the searched string.
* @return the given text with replacements applied, or {@code text} if no replacement has been applied,
* or {@code null} if the given text was null
*
* @see String#replace(char, char)
* @see StringBuilders#replace(StringBuilder, String, String)
* @see String#replace(CharSequence, CharSequence)
*
* @since 0.4
*/
public static CharSequence replace(final CharSequence text, final CharSequence toSearch, final CharSequence replaceBy) {
ArgumentChecks.ensureNonEmpty("toSearch", toSearch);
ArgumentChecks.ensureNonNull ("replaceBy", replaceBy);
if (text != null && !toSearch.equals(replaceBy)) {
if (text instanceof String) {
return ((String) text).replace(toSearch, replaceBy);
}
final int length = text.length();
int i = indexOf(text, toSearch, 0, length);
if (i >= 0) {
int p = 0;
final int sl = toSearch.length();
final StringBuilder buffer = new StringBuilder(length + (replaceBy.length() - sl));
do {
buffer.append(text, p, i).append(replaceBy);
i = indexOf(text, toSearch, p = i + sl, length);
} while (i >= 0);
return buffer.append(text, p, length);
}
}
return text;
}
/**
* Copies a sequence of characters in the given {@code char[]} array.
*
* @param src the characters sequence from which to copy characters.
* @param srcOffset index of the first character from {@code src} to copy.
* @param dst the array where to copy the characters.
* @param dstOffset index where to write the first character in {@code dst}.
* @param length number of characters to copy.
*
* @see String#getChars(int, int, char[], int)
* @see StringBuilder#getChars(int, int, char[], int)
* @see StringBuffer#getChars(int, int, char[], int)
* @see CharBuffer#get(char[], int, int)
* @see javax.swing.text.Segment#array
*/
public static void copyChars(final CharSequence src, int srcOffset,
final char[] dst, int dstOffset, int length)
{
ArgumentChecks.ensurePositive("length", length);
if (src instanceof String) {
((String) src).getChars(srcOffset, srcOffset + length, dst, dstOffset);
} else if (src instanceof StringBuilder) {
((StringBuilder) src).getChars(srcOffset, srcOffset + length, dst, dstOffset);
} else if (src instanceof StringBuffer) {
((StringBuffer) src).getChars(srcOffset, srcOffset + length, dst, dstOffset);
} else if (src instanceof CharBuffer) {
((CharBuffer) src).subSequence(srcOffset, srcOffset + length).get(dst, dstOffset, length);
} else {
/*
* Another candidate could be `javax.swing.text.Segment`, but it
* is probably not worth to introduce a Swing dependency for it.
*/
while (length != 0) {
dst[dstOffset++] = src.charAt(srcOffset++);
length--;
}
}
}
}
| Java |
// Copyright 2006-2009 Google 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.
// ========================================================================
#include "omaha/mi_exe_stub/process.h"
namespace omaha {
namespace {
bool run_and_wait(const CString& command_line,
DWORD* exit_code,
bool wait,
int cmd_show) {
CString cmd_line(command_line);
STARTUPINFO si = {};
PROCESS_INFORMATION pi = {};
GetStartupInfo(&si);
si.dwFlags |= STARTF_FORCEOFFFEEDBACK | STARTF_USESHOWWINDOW;
si.wShowWindow = static_cast<WORD>(cmd_show);
BOOL create_process_result = CreateProcess(NULL,
cmd_line.GetBuffer(),
NULL,
NULL,
FALSE,
CREATE_UNICODE_ENVIRONMENT,
NULL,
NULL,
&si,
&pi);
if (!create_process_result) {
*exit_code = GetLastError();
return false;
}
if (wait) {
WaitForSingleObject(pi.hProcess, INFINITE);
}
bool result = true;
if (exit_code) {
result = !!GetExitCodeProcess(pi.hProcess, exit_code);
}
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return result;
}
} // namespace
bool RunAndWaitHidden(const CString& command_line, DWORD *exit_code) {
return run_and_wait(command_line, exit_code, true, SW_HIDE);
}
bool RunAndWait(const CString& command_line, DWORD *exit_code) {
return run_and_wait(command_line, exit_code, true, SW_SHOWNORMAL);
}
bool Run(const CString& command_line) {
return run_and_wait(command_line, NULL, false, SW_SHOWNORMAL);
}
} // namespace omaha
| Java |
---
title: Cordova 3.1.0 Now on PhoneGap Build
date: 2013-10-24 11:00:05 Z
categories:
- build
tags:
- PhoneGap Build
author: Ryan Willoughby
---
[PhoneGap Build](http://build.phonegap.com) is happy to announce that we now support Cordova 3.1.0. For more info on what's included in
this update, check out the [Cordova 3.1.0 release blog post](http://cordova.apache.org/blog/releases/2013/10/02/cordova-31.html).
You may have noticed that lately we've been deprecating older versions of Cordova with many of our releases. Thats not happening on
this particular release, but we want to remind you to update your app to the latest version of Cordova as often as possible. Be aware
that letting an app lie dormant on PhoneGap Build for too long will likely see its Cordova version become deprecated. The mobile
development world evolves rapidly, and PhoneGap Build, and the applications created on it, need to evolve with it.
As always, if you have problems uprgrading, or any other questions, [just ask](http://community.phonegap.com/nitobi). | 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.river.test.spec.config.configurationprovider;
import net.jini.config.Configuration;
import net.jini.config.ConfigurationProvider;
import net.jini.config.ConfigurationException;
import net.jini.config.ConfigurationNotFoundException;
/**
* Some Configuration that can be instantiated but can not be
* really used. This configuration provider doesn't have default
* for options
*/
public class ValidConfigurationWithoutDefaults implements Configuration {
public static boolean wasCalled = false;
public ValidConfigurationWithoutDefaults(String[] options)
throws ConfigurationException {
this(options, null);
wasCalled = true;
}
public ValidConfigurationWithoutDefaults(String[] options, ClassLoader cl)
throws ConfigurationException {
wasCalled = true;
if (options == null) {
throw new ConfigurationNotFoundException(
"default options are not supplied");
}
}
public Object getEntry(String component, String name, Class type)
throws ConfigurationException {
throw new AssertionError();
};
public Object getEntry(String component, String name, Class type,
Object defaultValue) throws ConfigurationException {
throw new AssertionError();
};
public Object getEntry(String component, String name, Class type,
Object defaultValue, Object data) throws ConfigurationException {
throw new AssertionError();
};
}
| Java |
<pm-header></pm-header>
<div class="container">
<legalMenu></legalMenu>
<div class="body">
<h1>Extension to the slamby api commercial license for royalty free distribution (oem)</h1>
<h2>1. Definitions</h2>
<p>When used in this Agreement, the following terms shall have the respective meanings indicated, such meanings to be applicable to both the singular and plural forms of the terms defined:</p>
<ul>
<li>“We” or “Us” or “Slamby” or “Our” or the “Company” refers to Slamby-Semantics Ltd.</li>
<li>“You” and “Your” and “User” refers to the entity and/or individual person, natural or legal, consenting to, and entering into, this Agreement.</li>
<li>"Licensor" means Slamby.</li>
<li>"Software" means (a) all of the contents of the files, disk(s), disk image(s), Docker containers or other media with which this Agreement is provided, including but not limited to ((i) digital images (ii) related explanatory written materials or files ("Documentation"); and (iii) fonts; and (b) upgrades, modified versions, updates, additions, and copies of the Software, if any, licensed to you by Slamby (collectively, "Updates").</li>
<li>"Use" or "Using" means to access, install, download, copy or otherwise benefit from using the functionality of the Software.</li>
<li>"Licensee" means You or Your Company, unless otherwise indicated.</li>
<li>"System" means Windows OS, GNU/Linux or Mac OS X, Docker or any virtual machine.</li>
</ul>
<h2>2. General Use</h2>
<p>As long as the Licensee complies with the terms of this extension of End User License Agreement (the "Agreement") and the Agreement itself, the Licensor grants the Licensee a non-exclusive right to install and Use the Software for the purposes described in the Documentation under the following conditions:</p>
<p>The Software may be installed and used by the Licensee for business, commercial and money-earning purposes.</p>
<p>This License can be deployed on any number of systems.</p>
<p>The Software under this License may be incorporated into software/hardware projects sold by the Licensee.</p>
<p>The Licensee may physically or electronically distribute the Software to his manufacturing and service partners but only as an intermediary product, requiring incorporation of the Software into the software or hardware developed by the Licensee in cases when the manufacturing process involves the Licensee's partner's job to complete the project before distributing it to end-users.</p>
<p>The Licensee or his manufacturing and service partners may reproduce and physically or electronically distribute the Software only as an integral part of or incorporated into their software or hardware product.</p>
<p>This License entitles the Licensee to the unlimited redistribution of the Licensor's technology as a part of the Licensee's product.</p>
<p>This License is royalty-free, i.e. the Licensee does not need to pay a fee per every order of his product with the incorporated Licensor's technology.</p>
<p>This License cannot be used by the Licensee to develop a software application that would compete with products marketed by the Licensor.</p>
<h2>3. Intellectual Property Rights</h2>
<p>3.1 This License does not transmit any intellectual rights on the Software. The Software and any copies that the Licensee is authorized by the Licensor to make are the intellectual property of and are owned by the Licensor.</p>
<p>3.2 The Software is protected by copyright, including without limitation by Copyright Law and international treaty provisions.</p>
<p>3.3 Any copies that the Licensee is permitted to make pursuant to this Agreement must contain the same copyright and other proprietary notices that appear on or in the Software.</p>
<p>3.4 Any information supplied by the Licensor or obtained by the Licensee, as permitted hereunder, may only be used by the Licensee for the purpose described herein and may not be disclosed to any third party or used to create any software which is substantially similar to the expression of the Software.</p>
<p>3.5 Trademarks shall be used in accordance with accepted trademark practice, including identification of trademarks owners' names. Trademarks can only be used to identify printed output produced by the Software and such use of any trademark does not give the Licensee any rights of ownership in that trademark.</p>
<h2>License Transfer</h2>
<p>4.1 This License is non-transferable. The Licensee may not transfer the rights to Use the Software to third parties (another person or legal entity).</p>
<p>4.2 The Licensee may not rent, lease, sub-license, lend or transfer any versions or copies of the Software to third parties (another person or legal entity).</p>
<p>4.3 The Licensee may make a back-up copy of the Software, provided a backup copy is not installed or used on any system not belonging to the Licensee. The Licensee may not transfer the rights to install or use a backup copy of the Software to third parties (another person or legal entity).</p>
</div>
</div> | 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.camel.component.netty4;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import org.apache.camel.util.concurrent.CamelThreadFactory;
/**
* A builder to create Netty {@link io.netty.channel.EventLoopGroup} which can be used for sharing worker pools
* with multiple Netty {@link NettyServerBootstrapFactory} server bootstrap configurations.
*/
public final class NettyWorkerPoolBuilder {
private String name = "NettyWorker";
private String pattern;
private int workerCount;
private boolean nativeTransport;
private volatile EventLoopGroup workerPool;
public void setName(String name) {
this.name = name;
}
public void setPattern(String pattern) {
this.pattern = pattern;
}
public void setWorkerCount(int workerCount) {
this.workerCount = workerCount;
}
public void setNativeTransport(boolean nativeTransport) {
this.nativeTransport = nativeTransport;
}
public NettyWorkerPoolBuilder withName(String name) {
setName(name);
return this;
}
public NettyWorkerPoolBuilder withPattern(String pattern) {
setPattern(pattern);
return this;
}
public NettyWorkerPoolBuilder withWorkerCount(int workerCount) {
setWorkerCount(workerCount);
return this;
}
public NettyWorkerPoolBuilder withNativeTransport(boolean nativeTransport) {
setNativeTransport(nativeTransport);
return this;
}
/**
* Creates a new worker pool.
*/
public EventLoopGroup build() {
int count = workerCount > 0 ? workerCount : NettyHelper.DEFAULT_IO_THREADS;
if (nativeTransport) {
workerPool = new EpollEventLoopGroup(count, new CamelThreadFactory(pattern, name, false));
} else {
workerPool = new NioEventLoopGroup(count, new CamelThreadFactory(pattern, name, false));
}
return workerPool;
}
/**
* Shutdown the created worker pool
*/
public void destroy() {
if (workerPool != null) {
workerPool.shutdownGracefully();
workerPool = null;
}
}
}
| Java |
using J2N.Text;
using Lucene.Net.Documents;
using Lucene.Net.QueryParsers.Flexible.Core.Config;
using Lucene.Net.QueryParsers.Flexible.Core.Nodes;
using Lucene.Net.QueryParsers.Flexible.Core.Processors;
using Lucene.Net.QueryParsers.Flexible.Standard.Config;
using Lucene.Net.QueryParsers.Flexible.Standard.Nodes;
using System;
using System.Collections.Generic;
using System.Globalization;
namespace Lucene.Net.QueryParsers.Flexible.Standard.Processors
{
/*
* 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.
*/
/// <summary>
/// This processors process <see cref="TermRangeQueryNode"/>s. It reads the lower and
/// upper bounds value from the <see cref="TermRangeQueryNode"/> object and try
/// to parse their values using a <c>dateFormat</c>. If the values cannot be
/// parsed to a date value, it will only create the <see cref="TermRangeQueryNode"/>
/// using the non-parsed values.
/// <para/>
/// If a <see cref="ConfigurationKeys.LOCALE"/> is defined in the
/// <see cref="QueryConfigHandler"/> it will be used to parse the date, otherwise
/// <see cref="CultureInfo.CurrentCulture"/> will be used.
/// <para/>
/// If a <see cref="ConfigurationKeys.DATE_RESOLUTION"/> is defined and the
/// <see cref="DateResolution"/> is not <c>null</c> it will also be used to parse the
/// date value.
/// </summary>
/// <seealso cref="ConfigurationKeys.DATE_RESOLUTION"/>
/// <seealso cref="ConfigurationKeys.LOCALE"/>
/// <seealso cref="TermRangeQueryNode"/>
public class TermRangeQueryNodeProcessor : QueryNodeProcessor
{
public TermRangeQueryNodeProcessor()
{
// empty constructor
}
protected override IQueryNode PostProcessNode(IQueryNode node)
{
if (node is TermRangeQueryNode termRangeNode)
{
FieldQueryNode upper = (FieldQueryNode)termRangeNode.UpperBound;
FieldQueryNode lower = (FieldQueryNode)termRangeNode.LowerBound;
// LUCENENET specific - set to 0 (instead of null), since it doesn't correspond to any valid setting
DateResolution dateRes = 0/* = null*/;
bool inclusive = false;
CultureInfo locale = GetQueryConfigHandler().Get(ConfigurationKeys.LOCALE);
if (locale is null)
{
locale = CultureInfo.CurrentCulture; //Locale.getDefault();
}
TimeZoneInfo timeZone = GetQueryConfigHandler().Get(ConfigurationKeys.TIMEZONE);
if (timeZone is null)
{
timeZone = TimeZoneInfo.Local; //TimeZone.getDefault();
}
string field = termRangeNode.Field;
string fieldStr = null;
if (field != null)
{
fieldStr = field.ToString();
}
FieldConfig fieldConfig = GetQueryConfigHandler()
.GetFieldConfig(fieldStr);
if (fieldConfig != null)
{
dateRes = fieldConfig.Get(ConfigurationKeys.DATE_RESOLUTION);
}
if (termRangeNode.IsUpperInclusive)
{
inclusive = true;
}
string part1 = lower.GetTextAsString();
string part2 = upper.GetTextAsString();
try
{
string shortDateFormat = locale.DateTimeFormat.ShortDatePattern;
if (DateTime.TryParseExact(part1, shortDateFormat, locale, DateTimeStyles.None, out DateTime d1))
{
part1 = DateTools.DateToString(d1, timeZone, dateRes);
lower.Text = new StringCharSequence(part1);
}
if (DateTime.TryParseExact(part2, shortDateFormat, locale, DateTimeStyles.None, out DateTime d2))
{
if (inclusive)
{
// The user can only specify the date, not the time, so make sure
// the time is set to the latest possible time of that date to
// really
// include all documents:
//Calendar cal = Calendar.getInstance(timeZone, locale);
//cal.setTime(d2);
//cal.set(Calendar.HOUR_OF_DAY, 23);
//cal.set(Calendar.MINUTE, 59);
//cal.set(Calendar.SECOND, 59);
//cal.set(Calendar.MILLISECOND, 999);
//d2 = cal.getTime();
d2 = TimeZoneInfo.ConvertTime(d2, timeZone);
var cal = locale.Calendar;
d2 = cal.AddHours(d2, 23);
d2 = cal.AddMinutes(d2, 59);
d2 = cal.AddSeconds(d2, 59);
d2 = cal.AddMilliseconds(d2, 999);
}
part2 = DateTools.DateToString(d2, timeZone, dateRes);
upper.Text = new StringCharSequence(part2);
}
}
catch (Exception e) when (e.IsException())
{
// do nothing
}
}
return node;
}
protected override IQueryNode PreProcessNode(IQueryNode node)
{
return node;
}
protected override IList<IQueryNode> SetChildrenOrder(IList<IQueryNode> children)
{
return children;
}
}
}
| 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.solr.common.params;
import java.util.EnumSet;
import java.util.Locale;
import org.apache.solr.common.SolrException;
/** Facet parameters */
public interface FacetParams {
/** Should facet counts be calculated? */
public static final String FACET = "facet";
/**
* Numeric option indicating the maximum number of threads to be used in counting facet field
* vales
*/
public static final String FACET_THREADS = FACET + ".threads";
/** What method should be used to do the faceting */
public static final String FACET_METHOD = FACET + ".method";
/**
* Value for FACET_METHOD param to indicate that Solr should enumerate over terms in a field to
* calculate the facet counts.
*/
public static final String FACET_METHOD_enum = "enum";
/**
* Value for FACET_METHOD param to indicate that Solr should enumerate over documents and count up
* terms by consulting an uninverted representation of the field values (such as the FieldCache
* used for sorting).
*/
public static final String FACET_METHOD_fc = "fc";
/** Value for FACET_METHOD param, like FACET_METHOD_fc but counts per-segment. */
public static final String FACET_METHOD_fcs = "fcs";
/** Value for FACET_METHOD param to indicate that Solr should use an UnInvertedField */
public static final String FACET_METHOD_uif = "uif";
/**
* Any lucene formated queries the user would like to use for Facet Constraint Counts
* (multi-value)
*/
public static final String FACET_QUERY = FACET + ".query";
/**
* Any field whose terms the user wants to enumerate over for Facet Constraint Counts
* (multi-value)
*/
public static final String FACET_FIELD = FACET + ".field";
/** The offset into the list of facets. Can be overridden on a per field basis. */
public static final String FACET_OFFSET = FACET + ".offset";
/**
* Numeric option indicating the maximum number of facet field counts be included in the response
* for each field - in descending order of count. Can be overridden on a per field basis.
*/
public static final String FACET_LIMIT = FACET + ".limit";
/**
* Numeric option indicating the minimum number of hits before a facet should be included in the
* response. Can be overridden on a per field basis.
*/
public static final String FACET_MINCOUNT = FACET + ".mincount";
/**
* Boolean option indicating whether facet field counts of "0" should be included in the response.
* Can be overridden on a per field basis.
*/
public static final String FACET_ZEROS = FACET + ".zeros";
/**
* Boolean option indicating whether the response should include a facet field count for all
* records which have no value for the facet field. Can be overridden on a per field basis.
*/
public static final String FACET_MISSING = FACET + ".missing";
static final String FACET_OVERREQUEST = FACET + ".overrequest";
/**
* The percentage to over-request by when performing initial distributed requests.
*
* <p>default value is 1.5
*/
public static final String FACET_OVERREQUEST_RATIO = FACET_OVERREQUEST + ".ratio";
/**
* An additional amount to over-request by when performing initial distributed requests. This
* value will be added after accounting for the over-request ratio.
*
* <p>default value is 10
*/
public static final String FACET_OVERREQUEST_COUNT = FACET_OVERREQUEST + ".count";
/**
* Comma separated list of fields to pivot
*
* <p>example: author,type (for types by author / types within author)
*/
public static final String FACET_PIVOT = FACET + ".pivot";
/**
* Minimum number of docs that need to match to be included in the sublist
*
* <p>default value is 1
*/
public static final String FACET_PIVOT_MINCOUNT = FACET_PIVOT + ".mincount";
/**
* String option: "count" causes facets to be sorted by the count, "index" results in index order.
*/
public static final String FACET_SORT = FACET + ".sort";
public static final String FACET_SORT_COUNT = "count";
public static final String FACET_SORT_COUNT_LEGACY = "true";
public static final String FACET_SORT_INDEX = "index";
public static final String FACET_SORT_INDEX_LEGACY = "false";
/** Only return constraints of a facet field with the given prefix. */
public static final String FACET_PREFIX = FACET + ".prefix";
/** Only return constraints of a facet field containing the given string. */
public static final String FACET_CONTAINS = FACET + ".contains";
/** Only return constraints of a facet field containing the given string. */
public static final String FACET_MATCHES = FACET + ".matches";
/** If using facet contains, ignore case when comparing values. */
public static final String FACET_CONTAINS_IGNORE_CASE = FACET_CONTAINS + ".ignoreCase";
/** Only return constraints of a facet field excluding the given string. */
public static final String FACET_EXCLUDETERMS = FACET + ".excludeTerms";
/**
* When faceting by enumerating the terms in a field, only use the filterCache for terms with a df
* >= to this parameter.
*/
public static final String FACET_ENUM_CACHE_MINDF = FACET + ".enum.cache.minDf";
/**
* A boolean parameter that caps the facet counts at 1. With this set, a returned count will only
* be 0 or 1. For apps that don't need the count, this should be an optimization
*/
public static final String FACET_EXISTS = FACET + ".exists";
/**
* Any field whose terms the user wants to enumerate over for Facet Contraint Counts (multi-value)
*/
public static final String FACET_DATE = FACET + ".date";
/**
* Date string indicating the starting point for a date facet range. Can be overridden on a per
* field basis.
*/
public static final String FACET_DATE_START = FACET_DATE + ".start";
/**
* Date string indicating the ending point for a date facet range. Can be overridden on a per
* field basis.
*/
public static final String FACET_DATE_END = FACET_DATE + ".end";
/**
* Date Math string indicating the interval of sub-ranges for a date facet range. Can be
* overridden on a per field basis.
*/
public static final String FACET_DATE_GAP = FACET_DATE + ".gap";
/**
* Boolean indicating how counts should be computed if the range between 'start' and 'end' is not
* evenly divisible by 'gap'. If this value is true, then all counts of ranges involving the 'end'
* point will use the exact endpoint specified -- this includes the 'between' and 'after' counts
* as well as the last range computed using the 'gap'. If the value is false, then 'gap' is used
* to compute the effective endpoint closest to the 'end' param which results in the range between
* 'start' and 'end' being evenly divisible by 'gap'.
*
* <p>The default is false.
*
* <p>Can be overridden on a per field basis.
*/
public static final String FACET_DATE_HARD_END = FACET_DATE + ".hardend";
/**
* String indicating what "other" ranges should be computed for a date facet range (multi-value).
*
* <p>Can be overridden on a per field basis.
*
* @see FacetRangeOther
*/
public static final String FACET_DATE_OTHER = FACET_DATE + ".other";
/**
* Multivalued string indicating what rules should be applied to determine when the ranges
* generated for date faceting should be inclusive or exclusive of their end points.
*
* <p>The default value if none are specified is: [lower,upper,edge] <i>(NOTE: This is different
* then FACET_RANGE_INCLUDE)</i>
*
* <p>Can be overridden on a per field basis.
*
* @see FacetRangeInclude
* @see #FACET_RANGE_INCLUDE
*/
public static final String FACET_DATE_INCLUDE = FACET_DATE + ".include";
/**
* Any numerical field whose terms the user wants to enumerate over Facet Contraint Counts for
* selected ranges.
*/
public static final String FACET_RANGE = FACET + ".range";
/**
* Number indicating the starting point for a numerical range facet. Can be overridden on a per
* field basis.
*/
public static final String FACET_RANGE_START = FACET_RANGE + ".start";
/**
* Number indicating the ending point for a numerical range facet. Can be overridden on a per
* field basis.
*/
public static final String FACET_RANGE_END = FACET_RANGE + ".end";
/**
* Number indicating the interval of sub-ranges for a numerical facet range. Can be overridden on
* a per field basis.
*/
public static final String FACET_RANGE_GAP = FACET_RANGE + ".gap";
/**
* Boolean indicating how counts should be computed if the range between 'start' and 'end' is not
* evenly divisible by 'gap'. If this value is true, then all counts of ranges involving the 'end'
* point will use the exact endpoint specified -- this includes the 'between' and 'after' counts
* as well as the last range computed using the 'gap'. If the value is false, then 'gap' is used
* to compute the effective endpoint closest to the 'end' param which results in the range between
* 'start' and 'end' being evenly divisible by 'gap'.
*
* <p>The default is false.
*
* <p>Can be overridden on a per field basis.
*/
public static final String FACET_RANGE_HARD_END = FACET_RANGE + ".hardend";
/**
* String indicating what "other" ranges should be computed for a numerical range facet
* (multi-value). Can be overridden on a per field basis.
*/
public static final String FACET_RANGE_OTHER = FACET_RANGE + ".other";
/**
* Multivalued string indicating what rules should be applied to determine when the ranges
* generated for numeric faceting should be inclusive or exclusive of their end points.
*
* <p>The default value if none are specified is: lower
*
* <p>Can be overridden on a per field basis.
*
* @see FacetRangeInclude
*/
public static final String FACET_RANGE_INCLUDE = FACET_RANGE + ".include";
/**
* String indicating the method to use to resolve range facets.
*
* <p>Can be overridden on a per field basis.
*
* @see FacetRangeMethod
*/
public static final String FACET_RANGE_METHOD = FACET_RANGE + ".method";
/** Any field whose values the user wants to enumerate as explicit intervals of terms. */
public static final String FACET_INTERVAL = FACET + ".interval";
/** Set of terms for a single interval to facet on. */
public static final String FACET_INTERVAL_SET = FACET_INTERVAL + ".set";
/**
* A spatial RPT field to generate a 2D "heatmap" (grid of facet counts) on. Just like the other
* faceting types, this may include a 'key' or local-params to facet multiple times. All
* parameters with this suffix can be overridden on a per-field basis.
*/
public static final String FACET_HEATMAP = "facet.heatmap";
/** The format of the heatmap: either png or ints2D (default). */
public static final String FACET_HEATMAP_FORMAT = FACET_HEATMAP + ".format";
/**
* The region the heatmap should minimally enclose. It defaults to the world if not set. The
* format can either be a minimum to maximum point range format:
*
* <pre>["-150 10" TO "-100 30"]</pre>
*
* (the first is bottom-left and second is bottom-right, both of which are parsed as points are
* parsed). OR, any WKT can be provided and it's bounding box will be taken.
*/
public static final String FACET_HEATMAP_GEOM = FACET_HEATMAP + ".geom";
/**
* Specify the heatmap grid level explicitly, instead of deriving it via distErr or distErrPct.
*/
public static final String FACET_HEATMAP_LEVEL = FACET_HEATMAP + ".gridLevel";
/**
* Used to determine the heatmap grid level to compute, defaulting to 0.15. It has the same
* interpretation of distErrPct when searching on RPT, but relative to the shape in 'bbox'. It's a
* fraction (not a %) of the radius of the shape that grid squares must fit into without
* exceeding. > 0 and <= 0.5. Mutually exclusive with distErr & gridLevel.
*/
public static final String FACET_HEATMAP_DIST_ERR_PCT = FACET_HEATMAP + ".distErrPct";
/**
* Used to determine the heatmap grid level to compute (optional). It has the same interpretation
* of maxDistErr or distErr with RPT. It's an absolute distance (in units of what's specified on
* the field type) that a grid square must maximally fit into (width & height). It can be used
* to to more explicitly specify the maximum grid square size without knowledge of what particular
* grid levels translate to. This can in turn be used with knowledge of the size of 'bbox' to get
* a target minimum number of grid cells. Mutually exclusive with distErrPct & gridLevel.
*/
public static final String FACET_HEATMAP_DIST_ERR = FACET_HEATMAP + ".distErr";
/**
* The maximum number of cells (grid squares) the client is willing to handle. If this limit would
* be exceeded, we throw an error instead. Defaults to 100k.
*/
public static final String FACET_HEATMAP_MAX_CELLS = FACET_HEATMAP + ".maxCells";
/**
* An enumeration of the legal values for {@link #FACET_RANGE_OTHER} and {@link #FACET_DATE_OTHER}
* ...
*
* <ul>
* <li>before = the count of matches before the start
* <li>after = the count of matches after the end
* <li>between = the count of all matches between start and end
* <li>all = all of the above (default value)
* <li>none = no additional info requested
* </ul>
*
* @see #FACET_RANGE_OTHER
* @see #FACET_DATE_OTHER
*/
public enum FacetRangeOther {
BEFORE,
AFTER,
BETWEEN,
ALL,
NONE;
@Override
public String toString() {
return super.toString().toLowerCase(Locale.ROOT);
}
public static FacetRangeOther get(String label) {
try {
return valueOf(label.toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException e) {
throw new SolrException(
SolrException.ErrorCode.BAD_REQUEST,
label + " is not a valid type of 'other' range facet information",
e);
}
}
}
/**
* An enumeration of the legal values for {@link #FACET_DATE_INCLUDE} and {@link
* #FACET_RANGE_INCLUDE} <br>
*
* <ul>
* <li>lower = all gap based ranges include their lower bound
* <li>upper = all gap based ranges include their upper bound
* <li>edge = the first and last gap ranges include their edge bounds (ie: lower for the first
* one, upper for the last one) even if the corresponding upper/lower option is not
* specified
* <li>outer = the BEFORE and AFTER ranges should be inclusive of their bounds, even if the
* first or last ranges already include those boundaries.
* <li>all = shorthand for lower, upper, edge, and outer
* </ul>
*
* @see #FACET_DATE_INCLUDE
* @see #FACET_RANGE_INCLUDE
*/
public enum FacetRangeInclude {
ALL,
LOWER,
UPPER,
EDGE,
OUTER;
@Override
public String toString() {
return super.toString().toLowerCase(Locale.ROOT);
}
public static FacetRangeInclude get(String label) {
try {
return valueOf(label.toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException e) {
throw new SolrException(
SolrException.ErrorCode.BAD_REQUEST,
label + " is not a valid type of for range 'include' information",
e);
}
}
/**
* Convinience method for parsing the param value according to the correct semantics and
* applying the default of "LOWER"
*/
public static EnumSet<FacetRangeInclude> parseParam(final String[] param) {
// short circut for default behavior
if (null == param || 0 == param.length) return EnumSet.of(LOWER);
// build up set containing whatever is specified
final EnumSet<FacetRangeInclude> include = EnumSet.noneOf(FacetRangeInclude.class);
for (final String o : param) {
include.add(FacetRangeInclude.get(o));
}
// if set contains all, then we're back to short circuting
if (include.contains(FacetRangeInclude.ALL)) return EnumSet.allOf(FacetRangeInclude.class);
// use whatever we've got.
return include;
}
}
/**
* An enumeration of the legal values for {@link #FACET_RANGE_METHOD}
*
* <ul>
* <li>filter =
* <li>dv =
* </ul>
*
* @see #FACET_RANGE_METHOD
*/
public enum FacetRangeMethod {
FILTER,
DV;
@Override
public String toString() {
return super.toString().toLowerCase(Locale.ROOT);
}
public static FacetRangeMethod get(String label) {
try {
return valueOf(label.toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException e) {
throw new SolrException(
SolrException.ErrorCode.BAD_REQUEST,
label + " is not a valid method for range faceting",
e);
}
}
public static FacetRangeMethod getDefault() {
return FILTER;
}
}
}
| Java |
# USE COLUMN TYPE FOR COLUMN "DATA" FOR THE RELEVANT DATABASE
#Mysql LONGTEXT
#SQLServer TEXT
#Postgres TEXT
#Oracle CLOB
#H2 CLOB
#Derby CLOB
#HSQL LONGVARCHAR
#Hibernate MYSQL Script
ALTER TABLE STORE_PROCESS_PROP ADD COLUMN DATA LONGTEXT;
CREATE TABLE STORE_PROCESS_PROP_TEST SELECT * FROM STORE_PROCESS_PROP;
UPDATE STORE_PROCESS_PROP A SET A.DATA=(SELECT VALUE FROM STORE_PROCESS_PROP_TEST WHERE PROPID=A.PROPID AND NAME=A.NAME);
DROP TABLE STORE_PROCESS_PROP_TEST;
ALTER TABLE STORE_PROCESS_PROP DROP COLUMN VALUE;
#OpenJPA MYSQL Script
ALTER TABLE STORE_PROCESS_PROP ADD COLUMN DATA LONGTEXT;
CREATE TABLE STORE_PROCESS_PROP_TEST SELECT * FROM STORE_PROCESS_PROP;
UPDATE STORE_PROCESS_PROP A SET A.DATA=(SELECT PROP_VAL FROM STORE_PROCESS_PROP_TEST WHERE ID=A.ID);
DROP TABLE STORE_PROCESS_PROP_TEST;
ALTER TABLE STORE_PROCESS_PROP DROP COLUMN PROP_VAL;
| Java |
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Rename.ConflictEngine
Imports Microsoft.CodeAnalysis.Simplification
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Simplification
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions
Friend Module ExpressionSyntaxExtensions
Public ReadOnly typeNameFormatWithGenerics As New SymbolDisplayFormat(
globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Included,
genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters,
memberOptions:=SymbolDisplayMemberOptions.IncludeContainingType,
localOptions:=SymbolDisplayLocalOptions.IncludeType,
miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers,
typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces)
Public ReadOnly typeNameFormatWithoutGenerics As New SymbolDisplayFormat(
globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Included,
genericsOptions:=SymbolDisplayGenericsOptions.None,
memberOptions:=SymbolDisplayMemberOptions.IncludeContainingType,
localOptions:=SymbolDisplayLocalOptions.IncludeType,
miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers,
typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces)
<Extension()>
Public Function WalkUpParentheses(expression As ExpressionSyntax) As ExpressionSyntax
While expression.IsParentKind(SyntaxKind.ParenthesizedExpression)
expression = DirectCast(expression.Parent, ExpressionSyntax)
End While
Return expression
End Function
<Extension()>
Public Function WalkDownParentheses(expression As ExpressionSyntax) As ExpressionSyntax
While expression.IsKind(SyntaxKind.ParenthesizedExpression)
expression = DirectCast(expression, ParenthesizedExpressionSyntax).Expression
End While
Return expression
End Function
<Extension()>
Public Function Parenthesize(expression As ExpressionSyntax) As ParenthesizedExpressionSyntax
Dim leadingTrivia = expression.GetLeadingTrivia()
Dim trailingTrivia = expression.GetTrailingTrivia()
Dim strippedExpression = expression.WithoutLeadingTrivia().WithoutTrailingTrivia()
Return SyntaxFactory.ParenthesizedExpression(strippedExpression) _
.WithLeadingTrivia(leadingTrivia) _
.WithTrailingTrivia(trailingTrivia) _
.WithAdditionalAnnotations(Simplifier.Annotation)
End Function
<Extension()>
Public Function IsAliasReplaceableExpression(expression As ExpressionSyntax) As Boolean
If expression.Kind = SyntaxKind.IdentifierName OrElse
expression.Kind = SyntaxKind.QualifiedName Then
Return True
End If
If expression.Kind = SyntaxKind.SimpleMemberAccessExpression Then
Dim memberAccess = DirectCast(expression, MemberAccessExpressionSyntax)
Return memberAccess.Expression IsNot Nothing AndAlso memberAccess.Expression.IsAliasReplaceableExpression()
End If
Return False
End Function
<Extension()>
Public Function IsMemberAccessExpressionName(expression As ExpressionSyntax) As Boolean
Return expression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) AndAlso
DirectCast(expression.Parent, MemberAccessExpressionSyntax).Name Is expression
End Function
<Extension()>
Public Function IsAnyMemberAccessExpressionName(expression As ExpressionSyntax) As Boolean
Return expression IsNot Nothing AndAlso
TypeOf expression.Parent Is MemberAccessExpressionSyntax AndAlso
DirectCast(expression.Parent, MemberAccessExpressionSyntax).Name Is expression
End Function
<Extension()>
Public Function IsRightSideOfDotOrBang(expression As ExpressionSyntax) As Boolean
Return expression.IsAnyMemberAccessExpressionName() OrElse expression.IsRightSideOfQualifiedName()
End Function
<Extension()>
Public Function IsRightSideOfDot(expression As ExpressionSyntax) As Boolean
Return expression.IsMemberAccessExpressionName() OrElse expression.IsRightSideOfQualifiedName()
End Function
<Extension()>
Public Function IsRightSideOfQualifiedName(expression As ExpressionSyntax) As Boolean
Return expression.IsParentKind(SyntaxKind.QualifiedName) AndAlso
DirectCast(expression.Parent, QualifiedNameSyntax).Right Is expression
End Function
<Extension()>
Public Function IsLeftSideOfQualifiedName(expression As ExpressionSyntax) As Boolean
Return expression.IsParentKind(SyntaxKind.QualifiedName) AndAlso
DirectCast(expression.Parent, QualifiedNameSyntax).Left Is expression
End Function
<Extension()>
Public Function IsAnyLiteralExpression(expression As ExpressionSyntax) As Boolean
Return expression.IsKind(SyntaxKind.CharacterLiteralExpression) OrElse
expression.IsKind(SyntaxKind.DateLiteralExpression) OrElse
expression.IsKind(SyntaxKind.FalseLiteralExpression) OrElse
expression.IsKind(SyntaxKind.NothingLiteralExpression) OrElse
expression.IsKind(SyntaxKind.NumericLiteralExpression) OrElse
expression.IsKind(SyntaxKind.StringLiteralExpression) OrElse
expression.IsKind(SyntaxKind.TrueLiteralExpression)
End Function
''' <summary>
''' Decompose a name or member access expression into its component parts.
''' </summary>
''' <param name="expression">The name or member access expression.</param>
''' <param name="qualifier">The qualifier (or left-hand-side) of the name expression. This may be null if there is no qualifier.</param>
''' <param name="name">The name of the expression.</param>
''' <param name="arity">The number of generic type parameters.</param>
<Extension()>
Public Sub DecomposeName(expression As ExpressionSyntax, ByRef qualifier As ExpressionSyntax, ByRef name As String, ByRef arity As Integer)
Select Case expression.Kind
Case SyntaxKind.SimpleMemberAccessExpression
Dim memberAccess = DirectCast(expression, MemberAccessExpressionSyntax)
qualifier = memberAccess.Expression
name = memberAccess.Name.Identifier.ValueText
arity = memberAccess.Name.Arity
Case SyntaxKind.QualifiedName
Dim qualifiedName = DirectCast(expression, QualifiedNameSyntax)
qualifier = qualifiedName.Left
name = qualifiedName.Right.Identifier.ValueText
arity = qualifiedName.Arity
Case SyntaxKind.GenericName
Dim genericName = DirectCast(expression, GenericNameSyntax)
qualifier = Nothing
name = genericName.Identifier.ValueText
arity = genericName.Arity
Case SyntaxKind.IdentifierName
Dim identifierName = DirectCast(expression, IdentifierNameSyntax)
qualifier = Nothing
name = identifierName.Identifier.ValueText
arity = 0
Case Else
qualifier = Nothing
name = Nothing
arity = 0
End Select
End Sub
<Extension()>
Public Function TryGetNameParts(expression As ExpressionSyntax, ByRef parts As IList(Of String)) As Boolean
Dim partsList = New List(Of String)
If Not expression.TryGetNameParts(partsList) Then
parts = Nothing
Return False
End If
parts = partsList
Return True
End Function
<Extension()>
Public Function TryGetNameParts(expression As ExpressionSyntax, parts As List(Of String)) As Boolean
If expression.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then
Dim memberAccess = DirectCast(expression, MemberAccessExpressionSyntax)
If Not memberAccess.Name.TryGetNameParts(parts) Then
Return False
End If
Return AddSimpleName(memberAccess.Name, parts)
ElseIf expression.IsKind(SyntaxKind.QualifiedName) Then
Dim qualifiedName = DirectCast(expression, QualifiedNameSyntax)
If Not qualifiedName.Left.TryGetNameParts(parts) Then
Return False
End If
Return AddSimpleName(qualifiedName.Right, parts)
ElseIf TypeOf expression Is SimpleNameSyntax Then
Return AddSimpleName(DirectCast(expression, SimpleNameSyntax), parts)
Else
Return False
End If
End Function
Private Function AddSimpleName(simpleName As SimpleNameSyntax, parts As List(Of String)) As Boolean
If Not simpleName.IsKind(SyntaxKind.IdentifierName) Then
Return False
End If
parts.Add(simpleName.Identifier.ValueText)
Return True
End Function
<Extension()>
Public Function IsLeftSideOfDot(expression As ExpressionSyntax) As Boolean
Return _
(expression.IsParentKind(SyntaxKind.QualifiedName) AndAlso DirectCast(expression.Parent, QualifiedNameSyntax).Left Is expression) OrElse
(expression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) AndAlso DirectCast(expression.Parent, MemberAccessExpressionSyntax).Expression Is expression)
End Function
<Extension()>
Public Function Cast(
expression As ExpressionSyntax,
targetType As ITypeSymbol,
<Out> ByRef isResultPredefinedCast As Boolean) As ExpressionSyntax
' Parenthesize the expression, except for collection initializer where parenthesizing changes the semantics.
Dim parenthesized = If(expression.Kind = SyntaxKind.CollectionInitializer,
expression,
expression.Parenthesize())
Dim leadingTrivia = parenthesized.GetLeadingTrivia()
Dim trailingTrivia = parenthesized.GetTrailingTrivia()
Dim stripped = parenthesized.WithoutLeadingTrivia().WithoutTrailingTrivia()
Dim castKeyword = targetType.SpecialType.GetPredefinedCastKeyword()
If castKeyword = SyntaxKind.None Then
isResultPredefinedCast = False
Return SyntaxFactory.CTypeExpression(
expression:=stripped,
type:=targetType.GenerateTypeSyntax()) _
.WithLeadingTrivia(leadingTrivia) _
.WithTrailingTrivia(trailingTrivia) _
.WithAdditionalAnnotations(Simplifier.Annotation)
Else
isResultPredefinedCast = True
Return SyntaxFactory.PredefinedCastExpression(
keyword:=SyntaxFactory.Token(castKeyword),
expression:=stripped) _
.WithLeadingTrivia(leadingTrivia) _
.WithTrailingTrivia(trailingTrivia) _
.WithAdditionalAnnotations(Simplifier.Annotation)
End If
End Function
<Extension()>
Public Function CastIfPossible(
expression As ExpressionSyntax,
targetType As ITypeSymbol,
position As Integer,
semanticModel As SemanticModel,
<Out> ByRef wasCastAdded As Boolean
) As ExpressionSyntax
wasCastAdded = False
If targetType.ContainsAnonymousType() OrElse expression.IsParentKind(SyntaxKind.AsNewClause) Then
Return expression
End If
Dim typeSyntax = targetType.GenerateTypeSyntax()
Dim type = semanticModel.GetSpeculativeTypeInfo(
position,
typeSyntax,
SpeculativeBindingOption.BindAsTypeOrNamespace).Type
If Not targetType.Equals(type) Then
Return expression
End If
Dim isResultPredefinedCast As Boolean = False
Dim castExpression = expression.Cast(targetType, isResultPredefinedCast)
' Ensure that inserting the cast doesn't change the semantics.
Dim specAnalyzer = New SpeculationAnalyzer(expression, castExpression, semanticModel, CancellationToken.None)
Dim speculativeSemanticModel = specAnalyzer.SpeculativeSemanticModel
If speculativeSemanticModel Is Nothing Then
Return expression
End If
Dim speculatedCastExpression = specAnalyzer.ReplacedExpression
Dim speculatedCastInnerExpression = If(isResultPredefinedCast,
DirectCast(speculatedCastExpression, PredefinedCastExpressionSyntax).Expression,
DirectCast(speculatedCastExpression, CastExpressionSyntax).Expression)
If Not CastAnalyzer.IsUnnecessary(speculatedCastExpression, speculatedCastInnerExpression, speculativeSemanticModel, True, CancellationToken.None) Then
Return expression
End If
wasCastAdded = True
Return castExpression
End Function
<Extension()>
Public Function IsNewOnRightSideOfDotOrBang(expression As ExpressionSyntax) As Boolean
Dim identifierName = TryCast(expression, IdentifierNameSyntax)
If identifierName Is Nothing Then
Return False
End If
If String.Compare(identifierName.Identifier.ToString(), "New", StringComparison.OrdinalIgnoreCase) <> 0 Then
Return False
End If
Return identifierName.IsRightSideOfDotOrBang()
End Function
<Extension()>
Public Function IsObjectCreationWithoutArgumentList(expression As ExpressionSyntax) As Boolean
Return _
TypeOf expression Is ObjectCreationExpressionSyntax AndAlso
DirectCast(expression, ObjectCreationExpressionSyntax).ArgumentList Is Nothing
End Function
<Extension()>
Public Function IsInOutContext(expression As ExpressionSyntax, semanticModel As SemanticModel, cancellationToken As CancellationToken) As Boolean
' NOTE(cyrusn): VB has no concept of an out context. Even when a parameter has an
' '<Out>' attribute on it, it's still treated as ref by VB. So we always return false
' here.
Return False
End Function
<Extension()>
Public Function IsInRefContext(expression As ExpressionSyntax, semanticModel As SemanticModel, cancellationToken As CancellationToken) As Boolean
Dim simpleArgument = TryCast(expression.Parent, SimpleArgumentSyntax)
If simpleArgument Is Nothing Then
Return False
ElseIf simpleArgument.IsNamed Then
Dim info = semanticModel.GetSymbolInfo(simpleArgument.NameColonEquals.Name, cancellationToken)
Dim parameter = TryCast(info.GetAnySymbol(), IParameterSymbol)
Return parameter IsNot Nothing AndAlso parameter.RefKind <> RefKind.None
Else
Dim argumentList = TryCast(simpleArgument.Parent, ArgumentListSyntax)
If argumentList IsNot Nothing Then
Dim parent = argumentList.Parent
Dim index = argumentList.Arguments.IndexOf(simpleArgument)
Dim info = semanticModel.GetSymbolInfo(parent, cancellationToken)
Dim symbol = info.GetAnySymbol()
If TypeOf symbol Is IMethodSymbol Then
Dim method = DirectCast(symbol, IMethodSymbol)
If index < method.Parameters.Length Then
Return method.Parameters(index).RefKind <> RefKind.None
End If
ElseIf TypeOf symbol Is IPropertySymbol Then
Dim prop = DirectCast(symbol, IPropertySymbol)
If index < prop.Parameters.Length Then
Return prop.Parameters(index).RefKind <> RefKind.None
End If
End If
End If
End If
Return False
End Function
<Extension()>
Public Function IsOnlyWrittenTo(expression As ExpressionSyntax, semanticModel As SemanticModel, cancellationToken As CancellationToken) As Boolean
If expression.IsRightSideOfDot() Then
expression = TryCast(expression.Parent, ExpressionSyntax)
End If
If expression IsNot Nothing Then
If expression.IsInOutContext(semanticModel, cancellationToken) Then
Return True
End If
If expression.IsParentKind(SyntaxKind.SimpleAssignmentStatement) Then
Dim assignmentStatement = DirectCast(expression.Parent, AssignmentStatementSyntax)
If expression Is assignmentStatement.Left Then
Return True
End If
End If
If expression.IsChildNode(Of NamedFieldInitializerSyntax)(Function(n) n.Name) Then
Return True
End If
Return False
End If
Return False
End Function
<Extension()>
Public Function IsWrittenTo(expression As ExpressionSyntax, semanticModel As SemanticModel, cancellationToken As CancellationToken) As Boolean
If IsOnlyWrittenTo(expression, semanticModel, cancellationToken) Then
Return True
End If
If expression.IsRightSideOfDot() Then
expression = TryCast(expression.Parent, ExpressionSyntax)
End If
If expression IsNot Nothing Then
If expression.IsInRefContext(semanticModel, cancellationToken) Then
Return True
End If
If TypeOf expression.Parent Is AssignmentStatementSyntax Then
Dim assignmentStatement = DirectCast(expression.Parent, AssignmentStatementSyntax)
If expression Is assignmentStatement.Left Then
Return True
End If
End If
If expression.IsChildNode(Of NamedFieldInitializerSyntax)(Function(n) n.Name) Then
Return True
End If
Return False
End If
Return False
End Function
<Extension()>
Public Function IsMeMyBaseOrMyClass(expression As ExpressionSyntax) As Boolean
If expression Is Nothing Then
Return False
End If
Return expression.Kind = SyntaxKind.MeExpression OrElse
expression.Kind = SyntaxKind.MyBaseExpression OrElse
expression.Kind = SyntaxKind.MyClassExpression
End Function
<Extension()>
Public Function IsFirstStatementInCtor(expression As ExpressionSyntax) As Boolean
Dim statement = expression.FirstAncestorOrSelf(Of StatementSyntax)()
If statement Is Nothing Then
Return False
End If
If Not statement.IsParentKind(SyntaxKind.ConstructorBlock) Then
Return False
End If
Return DirectCast(statement.Parent, ConstructorBlockSyntax).Statements(0) Is statement
End Function
<Extension()>
Public Function IsNamedArgumentIdentifier(expression As ExpressionSyntax) As Boolean
Dim simpleArgument = TryCast(expression.Parent, SimpleArgumentSyntax)
Return simpleArgument IsNot Nothing AndAlso simpleArgument.NameColonEquals.Name Is expression
End Function
Private Function IsUnnecessaryCast(
castNode As ExpressionSyntax,
castExpressionNode As ExpressionSyntax,
semanticModel As SemanticModel,
assumeCallKeyword As Boolean,
cancellationToken As CancellationToken
) As Boolean
Return CastAnalyzer.IsUnnecessary(castNode, castExpressionNode, semanticModel, assumeCallKeyword, cancellationToken)
End Function
<Extension>
Public Function IsUnnecessaryCast(
node As CastExpressionSyntax,
semanticModel As SemanticModel,
cancellationToken As CancellationToken,
Optional assumeCallKeyword As Boolean = False
) As Boolean
Return IsUnnecessaryCast(node, node.Expression, semanticModel, assumeCallKeyword, cancellationToken)
End Function
<Extension>
Public Function IsUnnecessaryCast(
node As PredefinedCastExpressionSyntax,
semanticModel As SemanticModel,
cancellationToken As CancellationToken,
Optional assumeCallKeyword As Boolean = False
) As Boolean
Return IsUnnecessaryCast(node, node.Expression, semanticModel, assumeCallKeyword, cancellationToken)
End Function
Private Function CanReplace(symbol As ISymbol) As Boolean
Select Case symbol.Kind
Case SymbolKind.Field,
SymbolKind.Local,
SymbolKind.Method,
SymbolKind.Parameter,
SymbolKind.Property,
SymbolKind.RangeVariable
Return True
End Select
Return False
End Function
<Extension>
Public Function CanReplaceWithRValue(expression As ExpressionSyntax, semanticModel As SemanticModel, cancellationToken As CancellationToken) As Boolean
Return expression IsNot Nothing AndAlso
Not expression.IsWrittenTo(semanticModel, cancellationToken) AndAlso
expression.CanReplaceWithLValue(semanticModel, cancellationToken)
End Function
<Extension>
Public Function CanReplaceWithLValue(expression As ExpressionSyntax, semanticModel As SemanticModel, cancellationToken As CancellationToken) As Boolean
#If False Then
' Things that are definitely illegal to replace
If ContainsImplicitMemberAccess(expression) Then
Return False
End If
#End If
If expression.IsKind(SyntaxKind.MyBaseExpression) OrElse
expression.IsKind(SyntaxKind.MyClassExpression) Then
Return False
End If
If Not (TypeOf expression Is ObjectCreationExpressionSyntax) AndAlso
Not (TypeOf expression Is AnonymousObjectCreationExpressionSyntax) Then
Dim symbolInfo = semanticModel.GetSymbolInfo(expression, cancellationToken)
If Not symbolInfo.GetBestOrAllSymbols().All(AddressOf CanReplace) Then
' If the expression is actually a reference to a type, then it can't be replaced
' with an arbitrary expression.
Return False
End If
End If
' Technically, you could introduce an LValue for "Foo" in "Foo()" even if "Foo" binds
' to a method. (i.e. by assigning to a Func<...> type). However, this is so contrived
' and none of the features that use this extension consider this replacable.
If TypeOf expression.Parent Is InvocationExpressionSyntax Then
' If someting is being invoked, then it's either something like Foo(), Foo.Bar(), or
' SomeExpr() (i.e. Blah[1]()). In the first and second case, we only allow
' replacement if Foo and Foo.Bar didn't bind to a method. If we can't bind it, we'll
' assume it's a method and we don't allow it to be replaced either. However, if it's
' an arbitrary expression, we do allow replacement.
If expression.IsKind(SyntaxKind.IdentifierName) OrElse expression.IsKind(SyntaxKind.SimpleMemberAccessExpression) Then
Dim symbolInfo = semanticModel.GetSymbolInfo(expression, cancellationToken)
If Not symbolInfo.GetBestOrAllSymbols().Any() Then
Return False
End If
' don't allow it to be replaced if it is bound to an indexed property
Return Not symbolInfo.GetBestOrAllSymbols().OfType(Of IMethodSymbol)().Any() AndAlso
Not symbolInfo.GetBestOrAllSymbols().OfType(Of IPropertySymbol)().Any()
Else
Return True
End If
End If
' expression in next statement's control variables should match one in the head
Dim nextStatement = expression.FirstAncestorOrSelf(Of NextStatementSyntax)()
If nextStatement IsNot Nothing Then
Return False
End If
' Direct parent kind checks.
If expression.IsParentKind(SyntaxKind.EqualsValue) OrElse
expression.IsParentKind(SyntaxKind.ParenthesizedExpression) OrElse
expression.IsParentKind(SyntaxKind.SelectStatement) OrElse
expression.IsParentKind(SyntaxKind.SyncLockStatement) OrElse
expression.IsParentKind(SyntaxKind.CollectionInitializer) OrElse
expression.IsParentKind(SyntaxKind.InferredFieldInitializer) OrElse
expression.IsParentKind(SyntaxKind.BinaryConditionalExpression) OrElse
expression.IsParentKind(SyntaxKind.TernaryConditionalExpression) OrElse
expression.IsParentKind(SyntaxKind.ReturnStatement) OrElse
expression.IsParentKind(SyntaxKind.YieldStatement) OrElse
expression.IsParentKind(SyntaxKind.XmlEmbeddedExpression) OrElse
expression.IsParentKind(SyntaxKind.ThrowStatement) OrElse
expression.IsParentKind(SyntaxKind.IfStatement) OrElse
expression.IsParentKind(SyntaxKind.WhileStatement) OrElse
expression.IsParentKind(SyntaxKind.ElseIfStatement) OrElse
expression.IsParentKind(SyntaxKind.ForEachStatement) OrElse
expression.IsParentKind(SyntaxKind.ForStatement) OrElse
expression.IsParentKind(SyntaxKind.ConditionalAccessExpression) OrElse
expression.IsParentKind(SyntaxKind.TypeOfIsExpression) Then
Return True
End If
' Parent type checks
If TypeOf expression.Parent Is BinaryExpressionSyntax OrElse
TypeOf expression.Parent Is AssignmentStatementSyntax OrElse
TypeOf expression.Parent Is WhileOrUntilClauseSyntax OrElse
TypeOf expression.Parent Is SingleLineLambdaExpressionSyntax OrElse
TypeOf expression.Parent Is AwaitExpressionSyntax Then
Return True
End If
' Specific child checks.
If expression.CheckParent(Of NamedFieldInitializerSyntax)(Function(n) n.Expression Is expression) OrElse
expression.CheckParent(Of MemberAccessExpressionSyntax)(Function(m) m.Expression Is expression) OrElse
expression.CheckParent(Of TryCastExpressionSyntax)(Function(t) t.Expression Is expression) OrElse
expression.CheckParent(Of CatchFilterClauseSyntax)(Function(c) c.Filter Is expression) OrElse
expression.CheckParent(Of SimpleArgumentSyntax)(Function(n) n.Expression Is expression) OrElse
expression.CheckParent(Of DirectCastExpressionSyntax)(Function(d) d.Expression Is expression) OrElse
expression.CheckParent(Of FunctionAggregationSyntax)(Function(f) f.Argument Is expression) OrElse
expression.CheckParent(Of RangeArgumentSyntax)(Function(r) r.UpperBound Is expression) Then
Return True
End If
' Misc checks
If TypeOf expression.Parent Is ExpressionRangeVariableSyntax AndAlso
TypeOf expression.Parent.Parent Is QueryClauseSyntax Then
Dim rangeVariable = DirectCast(expression.Parent, ExpressionRangeVariableSyntax)
Dim selectClause = TryCast(rangeVariable.Parent, SelectClauseSyntax)
' Can't replace the expression in a select unless its the last select clause *or*
' it's a select of the form "select a = <expr>"
If selectClause IsNot Nothing Then
If rangeVariable.NameEquals IsNot Nothing Then
Return True
End If
Dim queryExpression = TryCast(selectClause.Parent, QueryExpressionSyntax)
If queryExpression IsNot Nothing Then
Return queryExpression.Clauses.Last() Is selectClause
End If
Dim aggregateClause = TryCast(selectClause.Parent, AggregateClauseSyntax)
If aggregateClause IsNot Nothing Then
Return aggregateClause.AdditionalQueryOperators().Last() Is selectClause
End If
Return False
End If
' Any other query type is ok. Note(cyrusn): This may be too broad.
Return True
End If
Return False
End Function
<Extension>
Public Function ContainsImplicitMemberAccess(expression As ExpressionSyntax) As Boolean
Return ContainsImplicitMemberAccessWorker(expression)
End Function
<Extension>
Public Function ContainsImplicitMemberAccess(statement As StatementSyntax) As Boolean
Return ContainsImplicitMemberAccessWorker(statement)
End Function
<Extension>
Public Function GetImplicitMemberAccessExpressions(expression As SyntaxNode, span As TextSpan) As IEnumerable(Of ExpressionSyntax)
' We don't want to allow a variable to be introduced if the expression contains an
' implicit member access. i.e. ".Blah.ToString()" as that .Blah refers to the containing
' object creation or anonymous type and we can't make a local for it. So we get all the
' descendents and we suppress ourselves.
' Note: if we hit a with block or an anonymous type, then we do not look deeper. Any
' implicit member accesses will refer to that thing and we *can* introduce a variable
Dim descendentExpressions = expression.DescendantNodesAndSelf().OfType(Of ExpressionSyntax).Where(Function(e) span.Contains(e.Span)).ToSet()
Return descendentExpressions.OfType(Of MemberAccessExpressionSyntax).
Select(Function(m) m.GetExpressionOfMemberAccessExpression()).
Where(Function(e) Not descendentExpressions.Contains(e))
End Function
<Extension>
Public Function GetImplicitMemberAccessExpressions(expression As SyntaxNode) As IEnumerable(Of ExpressionSyntax)
Return GetImplicitMemberAccessExpressions(expression, expression.FullSpan)
End Function
Private Function ContainsImplicitMemberAccessWorker(expression As SyntaxNode) As Boolean
Return GetImplicitMemberAccessExpressions(expression).Any()
End Function
<Extension>
Public Function GetOperatorPrecedence(expression As ExpressionSyntax) As OperatorPrecedence
Select Case expression.Kind
Case SyntaxKind.ExponentiateExpression
Return OperatorPrecedence.PrecedenceExponentiate
Case SyntaxKind.UnaryMinusExpression,
SyntaxKind.UnaryPlusExpression
Return OperatorPrecedence.PrecedenceNegate
Case SyntaxKind.MultiplyExpression,
SyntaxKind.DivideExpression
Return OperatorPrecedence.PrecedenceMultiply
Case SyntaxKind.IntegerDivideExpression
Return OperatorPrecedence.PrecedenceIntegerDivide
Case SyntaxKind.ModuloExpression
Return OperatorPrecedence.PrecedenceModulus
Case SyntaxKind.AddExpression,
SyntaxKind.SubtractExpression
Return OperatorPrecedence.PrecedenceAdd
Case SyntaxKind.ConcatenateExpression
Return OperatorPrecedence.PrecedenceConcatenate
Case SyntaxKind.LeftShiftExpression,
SyntaxKind.RightShiftExpression
Return OperatorPrecedence.PrecedenceShift
Case SyntaxKind.EqualsExpression,
SyntaxKind.NotEqualsExpression,
SyntaxKind.LessThanExpression,
SyntaxKind.GreaterThanExpression,
SyntaxKind.LessThanOrEqualExpression,
SyntaxKind.GreaterThanOrEqualExpression,
SyntaxKind.LikeExpression,
SyntaxKind.IsExpression,
SyntaxKind.IsNotExpression
Return OperatorPrecedence.PrecedenceRelational
Case SyntaxKind.NotExpression
Return OperatorPrecedence.PrecedenceNot
Case SyntaxKind.AndExpression,
SyntaxKind.AndAlsoExpression
Return OperatorPrecedence.PrecedenceAnd
Case SyntaxKind.OrExpression,
SyntaxKind.OrElseExpression
Return OperatorPrecedence.PrecedenceOr
Case SyntaxKind.ExclusiveOrExpression
Return OperatorPrecedence.PrecedenceXor
Case Else
Return OperatorPrecedence.PrecedenceNone
End Select
End Function
<Extension()>
Public Function DetermineType(expression As ExpressionSyntax,
semanticModel As SemanticModel,
cancellationToken As CancellationToken) As ITypeSymbol
' If a parameter appears to have a void return type, then just use 'object' instead.
If expression IsNot Nothing Then
Dim typeInfo = semanticModel.GetTypeInfo(expression, cancellationToken)
Dim symbolInfo = semanticModel.GetSymbolInfo(expression, cancellationToken)
If typeInfo.Type IsNot Nothing AndAlso typeInfo.Type.SpecialType = SpecialType.System_Void Then
Return semanticModel.Compilation.ObjectType
End If
Dim symbol = If(typeInfo.Type, symbolInfo.GetAnySymbol())
If symbol IsNot Nothing Then
Return symbol.ConvertToType(semanticModel.Compilation)
End If
If TypeOf expression Is CollectionInitializerSyntax Then
Dim collectionInitializer = DirectCast(expression, CollectionInitializerSyntax)
Return DetermineType(collectionInitializer, semanticModel, cancellationToken)
End If
End If
Return semanticModel.Compilation.ObjectType
End Function
<Extension()>
Private Function DetermineType(collectionInitializer As CollectionInitializerSyntax,
semanticModel As SemanticModel,
cancellationToken As CancellationToken) As ITypeSymbol
Dim rank = 1
While collectionInitializer.Initializers.Count > 0 AndAlso
collectionInitializer.Initializers(0).Kind = SyntaxKind.CollectionInitializer
rank += 1
collectionInitializer = DirectCast(collectionInitializer.Initializers(0), CollectionInitializerSyntax)
End While
Dim type = collectionInitializer.Initializers.FirstOrDefault().DetermineType(semanticModel, cancellationToken)
Return semanticModel.Compilation.CreateArrayTypeSymbol(type, rank)
End Function
<Extension()>
Public Function TryReduceVariableDeclaratorWithoutType(
variableDeclarator As VariableDeclaratorSyntax,
semanticModel As SemanticModel,
<Out()> ByRef replacementNode As SyntaxNode,
<Out()> ByRef issueSpan As TextSpan,
optionSet As OptionSet,
cancellationToken As CancellationToken
) As Boolean
replacementNode = Nothing
issueSpan = Nothing
' Failfast Conditions
If Not optionSet.GetOption(SimplificationOptions.PreferImplicitTypeInLocalDeclaration) OrElse
variableDeclarator.AsClause Is Nothing OrElse
Not variableDeclarator.Parent.IsKind(
SyntaxKind.LocalDeclarationStatement,
SyntaxKind.UsingStatement,
SyntaxKind.ForStatement,
SyntaxKind.ForEachStatement,
SyntaxKind.FieldDeclaration) Then
Return False
End If
If variableDeclarator.Names.Count <> 1 Then
Return False
End If
Dim parent = variableDeclarator.Parent
Dim modifiedIdentifier = variableDeclarator.Names.Single()
Dim simpleAsClause = TryCast(variableDeclarator.AsClause, SimpleAsClauseSyntax)
If simpleAsClause Is Nothing Then
Return False
End If
If (parent.IsKind(SyntaxKind.LocalDeclarationStatement, SyntaxKind.UsingStatement, SyntaxKind.FieldDeclaration) AndAlso
variableDeclarator.Initializer IsNot Nothing) Then
' Type Check
Dim declaredSymbolType As ITypeSymbol = Nothing
If Not HasValidDeclaredTypeSymbol(modifiedIdentifier, semanticModel, declaredSymbolType) Then
Return False
End If
Dim initializerType As ITypeSymbol = Nothing
If declaredSymbolType.IsArrayType() AndAlso variableDeclarator.Initializer.Value.Kind() = SyntaxKind.CollectionInitializer Then
' Get type of the array literal in context without the target type
initializerType = semanticModel.GetSpeculativeTypeInfo(variableDeclarator.Initializer.Value.SpanStart, variableDeclarator.Initializer.Value, SpeculativeBindingOption.BindAsExpression).ConvertedType
Else
initializerType = semanticModel.GetTypeInfo(variableDeclarator.Initializer.Value).Type
End If
If Not declaredSymbolType.Equals(initializerType) Then
Return False
End If
Dim newModifiedIdentifier = SyntaxFactory.ModifiedIdentifier(modifiedIdentifier.Identifier) ' LeadingTrivia is copied here
replacementNode = SyntaxFactory.VariableDeclarator(SyntaxFactory.SingletonSeparatedList(newModifiedIdentifier.WithTrailingTrivia(variableDeclarator.AsClause.GetTrailingTrivia())),
asClause:=Nothing,
initializer:=variableDeclarator.Initializer) 'TrailingTrivia is copied here
issueSpan = variableDeclarator.Span
Return True
End If
If (parent.IsKind(SyntaxKind.ForEachStatement, SyntaxKind.ForStatement)) Then
' Type Check for ForStatement
If parent.IsKind(SyntaxKind.ForStatement) Then
Dim declaredSymbolType As ITypeSymbol = Nothing
If Not HasValidDeclaredTypeSymbol(modifiedIdentifier, semanticModel, declaredSymbolType) Then
Return False
End If
Dim valueType = semanticModel.GetTypeInfo(DirectCast(parent, ForStatementSyntax).ToValue).Type
If Not valueType.Equals(declaredSymbolType) Then
Return False
End If
End If
If parent.IsKind(SyntaxKind.ForEachStatement) Then
Dim forEachStatementInfo = semanticModel.GetForEachStatementInfo(DirectCast(parent, ForEachStatementSyntax))
If Not forEachStatementInfo.ElementConversion.IsIdentity Then
Return False
End If
End If
Dim newIdentifierName = SyntaxFactory.IdentifierName(modifiedIdentifier.Identifier) ' Leading Trivia is copied here
replacementNode = newIdentifierName.WithTrailingTrivia(variableDeclarator.AsClause.GetTrailingTrivia()) ' Trailing Trivia is copied here
issueSpan = variableDeclarator.Span
Return True
End If
Return False
End Function
Private Function HasValidDeclaredTypeSymbol(
modifiedIdentifier As ModifiedIdentifierSyntax,
semanticModel As SemanticModel,
<Out()> ByRef typeSymbol As ITypeSymbol) As Boolean
Dim declaredSymbol = semanticModel.GetDeclaredSymbol(modifiedIdentifier)
If declaredSymbol Is Nothing OrElse
(Not TypeOf declaredSymbol Is ILocalSymbol AndAlso Not TypeOf declaredSymbol Is IFieldSymbol) Then
Return False
End If
Dim localSymbol = TryCast(declaredSymbol, ILocalSymbol)
If localSymbol IsNot Nothing AndAlso TypeOf localSymbol IsNot IErrorTypeSymbol AndAlso TypeOf localSymbol.Type IsNot IErrorTypeSymbol Then
typeSymbol = localSymbol.Type
Return True
End If
Dim fieldSymbol = TryCast(declaredSymbol, IFieldSymbol)
If fieldSymbol IsNot Nothing AndAlso TypeOf fieldSymbol IsNot IErrorTypeSymbol AndAlso TypeOf fieldSymbol.Type IsNot IErrorTypeSymbol Then
typeSymbol = fieldSymbol.Type
Return True
End If
Return False
End Function
<Extension()>
Public Function TryReduceOrSimplifyExplicitName(
expression As ExpressionSyntax,
semanticModel As SemanticModel,
<Out()> ByRef replacementNode As ExpressionSyntax,
<Out()> ByRef issueSpan As TextSpan,
optionSet As OptionSet,
cancellationToken As CancellationToken
) As Boolean
If expression.TryReduceExplicitName(semanticModel, replacementNode, issueSpan, optionSet, cancellationToken) Then
Return True
End If
Return expression.TrySimplify(semanticModel, optionSet, replacementNode, issueSpan)
End Function
<Extension()>
Public Function TryReduceExplicitName(
expression As ExpressionSyntax,
semanticModel As SemanticModel,
<Out()> ByRef replacementNode As ExpressionSyntax,
<Out()> ByRef issueSpan As TextSpan,
optionSet As OptionSet,
cancellationToken As CancellationToken
) As Boolean
replacementNode = Nothing
issueSpan = Nothing
If expression.Kind = SyntaxKind.SimpleMemberAccessExpression Then
Dim memberAccess = DirectCast(expression, MemberAccessExpressionSyntax)
Return memberAccess.TryReduce(semanticModel,
replacementNode,
issueSpan,
optionSet,
cancellationToken)
ElseIf TypeOf (expression) Is NameSyntax Then
Dim name = DirectCast(expression, NameSyntax)
Return name.TryReduce(semanticModel,
replacementNode,
issueSpan,
optionSet,
cancellationToken)
End If
Return False
End Function
<Extension()>
Private Function TryReduce(
memberAccess As MemberAccessExpressionSyntax,
semanticModel As SemanticModel,
<Out()> ByRef replacementNode As ExpressionSyntax,
<Out()> ByRef issueSpan As TextSpan,
optionSet As OptionSet,
cancellationToken As CancellationToken
) As Boolean
If memberAccess.Expression Is Nothing OrElse memberAccess.Name Is Nothing Then
Return False
End If
If optionSet.GetOption(SimplificationOptions.QualifyMemberAccessWithThisOrMe, semanticModel.Language) AndAlso
memberAccess.Expression.Kind() = SyntaxKind.MeExpression Then
Return False
End If
If memberAccess.HasAnnotations(SpecialTypeAnnotation.Kind) Then
replacementNode = SyntaxFactory.PredefinedType(
SyntaxFactory.Token(
GetPredefinedKeywordKind(SpecialTypeAnnotation.GetSpecialType(memberAccess.GetAnnotations(SpecialTypeAnnotation.Kind).First())))) _
.WithLeadingTrivia(memberAccess.GetLeadingTrivia())
issueSpan = memberAccess.Span
Return True
Else
If Not memberAccess.IsRightSideOfDot() Then
Dim aliasReplacement As IAliasSymbol = Nothing
If memberAccess.TryReplaceWithAlias(semanticModel, aliasReplacement, optionSet.GetOption(SimplificationOptions.PreferAliasToQualification)) Then
Dim identifierToken = SyntaxFactory.Identifier(
memberAccess.GetLeadingTrivia(),
aliasReplacement.Name,
memberAccess.GetTrailingTrivia())
identifierToken = VisualBasicSimplificationService.TryEscapeIdentifierToken(
identifierToken,
semanticModel)
replacementNode = SyntaxFactory.IdentifierName(identifierToken)
issueSpan = memberAccess.Span
' In case the alias name is the same as the last name of the alias target, we only include
' the left part of the name in the unnecessary span to Not confuse uses.
If memberAccess.Name.Identifier.ValueText = identifierToken.ValueText Then
issueSpan = memberAccess.Expression.Span
End If
Return True
End If
If PreferPredefinedTypeKeywordInMemberAccess(memberAccess, optionSet) Then
Dim symbol = semanticModel.GetSymbolInfo(memberAccess).Symbol
If (symbol IsNot Nothing AndAlso symbol.IsKind(SymbolKind.NamedType)) Then
Dim keywordKind = GetPredefinedKeywordKind(DirectCast(symbol, INamedTypeSymbol).SpecialType)
If keywordKind <> SyntaxKind.None Then
replacementNode = SyntaxFactory.PredefinedType(
SyntaxFactory.Token(
memberAccess.GetLeadingTrivia(),
keywordKind,
memberAccess.GetTrailingTrivia()))
issueSpan = memberAccess.Span
Return True
End If
End If
End If
End If
' a module name was inserted by the name expansion, so removing this should be tried first.
If memberAccess.HasAnnotation(SimplificationHelpers.SimplifyModuleNameAnnotation) Then
If TryOmitModuleName(memberAccess, semanticModel, replacementNode, issueSpan, cancellationToken) Then
Return True
End If
End If
replacementNode = memberAccess.Name
replacementNode = DirectCast(replacementNode, SimpleNameSyntax) _
.WithIdentifier(VisualBasicSimplificationService.TryEscapeIdentifierToken(
memberAccess.Name.Identifier,
semanticModel)) _
.WithLeadingTrivia(memberAccess.GetLeadingTriviaForSimplifiedMemberAccess()) _
.WithTrailingTrivia(memberAccess.GetTrailingTrivia())
issueSpan = memberAccess.Expression.Span
If memberAccess.CanReplaceWithReducedName(replacementNode, semanticModel, cancellationToken) Then
Return True
End If
If optionSet.GetOption(SimplificationOptions.PreferOmittingModuleNamesInQualification) Then
If TryOmitModuleName(memberAccess, semanticModel, replacementNode, issueSpan, cancellationToken) Then
Return True
End If
End If
End If
Return False
End Function
<Extension>
Private Function GetLeadingTriviaForSimplifiedMemberAccess(memberAccess As MemberAccessExpressionSyntax) As SyntaxTriviaList
' We want to include any user-typed trivia that may be present between the 'Expression', 'OperatorToken' and 'Identifier' of the MemberAccessExpression.
' However, we don't want to include any elastic trivia that may have been introduced by the expander in these locations. This is to avoid triggering
' aggressive formatting. Otherwise, formatter will see this elastic trivia added by the expander And use that as a cue to introduce unnecessary blank lines
' etc. around the user's original code.
Return memberAccess.GetLeadingTrivia().
AddRange(memberAccess.Expression.GetTrailingTrivia().WithoutElasticTrivia()).
AddRange(memberAccess.OperatorToken.LeadingTrivia.WithoutElasticTrivia()).
AddRange(memberAccess.OperatorToken.TrailingTrivia.WithoutElasticTrivia()).
AddRange(memberAccess.Name.GetLeadingTrivia().WithoutElasticTrivia())
End Function
<Extension>
Private Function WithoutElasticTrivia(list As IEnumerable(Of SyntaxTrivia)) As IEnumerable(Of SyntaxTrivia)
Return list.Where(Function(t) Not t.IsElastic())
End Function
Private Function InsideCrefReference(expr As ExpressionSyntax) As Boolean
Dim crefAttribute = expr.FirstAncestorOrSelf(Of XmlCrefAttributeSyntax)()
Return crefAttribute IsNot Nothing
End Function
Private Function InsideNameOfExpression(expr As ExpressionSyntax) As Boolean
Dim nameOfExpression = expr.FirstAncestorOrSelf(Of NameOfExpressionSyntax)()
Return nameOfExpression IsNot Nothing
End Function
Private Function PreferPredefinedTypeKeywordInMemberAccess(memberAccess As ExpressionSyntax, optionSet As OptionSet) As Boolean
Return (((memberAccess.Parent IsNot Nothing) AndAlso (TypeOf memberAccess.Parent Is MemberAccessExpressionSyntax)) OrElse
(InsideCrefReference(memberAccess) AndAlso Not memberAccess.IsLeftSideOfQualifiedName)) AndAlso ' Bug 1012713: Compiler has a bug due to which it doesn't support <PredefinedType>.Member inside crefs (i.e. Sytem.Int32.MaxValue is supported but Integer.MaxValue isn't). Until this bug is fixed, we don't support simplifying types names like System.Int32.MaxValue to Integer.MaxValue.
(Not InsideNameOfExpression(memberAccess)) AndAlso
optionSet.GetOption(SimplificationOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, LanguageNames.VisualBasic)
End Function
Private Function PreferPredefinedTypeKeywordInDeclarations(name As NameSyntax, optionSet As OptionSet) As Boolean
Return (name.Parent IsNot Nothing) AndAlso (TypeOf name.Parent IsNot MemberAccessExpressionSyntax) AndAlso (Not InsideCrefReference(name)) AndAlso
(Not InsideNameOfExpression(name)) AndAlso
optionSet.GetOption(SimplificationOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, LanguageNames.VisualBasic)
End Function
<Extension>
Public Function GetRightmostName(node As ExpressionSyntax) As NameSyntax
Dim memberAccess = TryCast(node, MemberAccessExpressionSyntax)
If memberAccess IsNot Nothing AndAlso memberAccess.Name IsNot Nothing Then
Return memberAccess.Name
End If
Dim qualified = TryCast(node, QualifiedNameSyntax)
If qualified IsNot Nothing AndAlso qualified.Right IsNot Nothing Then
Return qualified.Right
End If
Dim simple = TryCast(node, SimpleNameSyntax)
If simple IsNot Nothing Then
Return simple
End If
Return Nothing
End Function
Private Function TryOmitModuleName(memberAccess As MemberAccessExpressionSyntax, semanticModel As SemanticModel, <Out()> ByRef replacementNode As ExpressionSyntax, <Out()> ByRef issueSpan As TextSpan, cancellationToken As CancellationToken) As Boolean
If memberAccess.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) Then
Dim symbolForMemberAccess = semanticModel.GetSymbolInfo(DirectCast(memberAccess.Parent, MemberAccessExpressionSyntax)).Symbol
If symbolForMemberAccess.IsModuleMember Then
replacementNode = memberAccess.Expression.WithLeadingTrivia(memberAccess.GetLeadingTrivia())
issueSpan = memberAccess.Name.Span
Dim parent = DirectCast(memberAccess.Parent, MemberAccessExpressionSyntax)
Dim parentReplacement = parent.ReplaceNode(parent.Expression, replacementNode)
If parent.CanReplaceWithReducedName(parentReplacement, semanticModel, cancellationToken) Then
Return True
End If
End If
End If
Return False
End Function
<Extension()>
Private Function CanReplaceWithReducedName(
memberAccess As MemberAccessExpressionSyntax,
reducedNode As ExpressionSyntax,
semanticModel As SemanticModel,
cancellationToken As CancellationToken
) As Boolean
If Not IsMeOrNamedTypeOrNamespace(memberAccess.Expression, semanticModel) Then
Return False
End If
' See if we can simplify a member access expression of the form E.M or E.M() to M or M()
Dim speculationAnalyzer = New SpeculationAnalyzer(memberAccess, reducedNode, semanticModel, cancellationToken)
If Not speculationAnalyzer.SymbolsForOriginalAndReplacedNodesAreCompatible() OrElse
speculationAnalyzer.ReplacementChangesSemantics() Then
Return False
End If
If memberAccess.Expression.IsKind(SyntaxKind.MyBaseExpression) Then
Dim enclosingNamedType = semanticModel.GetEnclosingNamedType(memberAccess.SpanStart, cancellationToken)
Dim symbol = semanticModel.GetSymbolInfo(memberAccess.Name).Symbol
If enclosingNamedType IsNot Nothing AndAlso
Not enclosingNamedType.IsSealed AndAlso
symbol IsNot Nothing AndAlso
symbol.IsOverridable() Then
Return False
End If
End If
Return True
End Function
<Extension()>
Private Function TryReduce(
name As NameSyntax,
semanticModel As SemanticModel,
<Out()> ByRef replacementNode As ExpressionSyntax,
<Out()> ByRef issueSpan As TextSpan,
optionSet As OptionSet,
cancellationToken As CancellationToken
) As Boolean
' do not simplify names of a namespace declaration
If IsPartOfNamespaceDeclarationName(name) Then
Return False
End If
' see whether binding the name binds to a symbol/type. if not, it is ambiguous and
' nothing we can do here.
Dim symbol = SimplificationHelpers.GetOriginalSymbolInfo(semanticModel, name)
If SimplificationHelpers.IsValidSymbolInfo(symbol) Then
If symbol.Kind = SymbolKind.Method AndAlso symbol.IsConstructor() Then
symbol = symbol.ContainingType
End If
If symbol.Kind = SymbolKind.Method AndAlso name.Kind = SyntaxKind.GenericName Then
If Not optionSet.GetOption(SimplificationOptions.PreferImplicitTypeInference) Then
Return False
End If
Dim genericName = DirectCast(name, GenericNameSyntax)
replacementNode = SyntaxFactory.IdentifierName(genericName.Identifier).WithLeadingTrivia(genericName.GetLeadingTrivia()).WithTrailingTrivia(genericName.GetTrailingTrivia())
issueSpan = name.Span
Return name.CanReplaceWithReducedName(replacementNode, semanticModel, cancellationToken)
End If
If Not TypeOf symbol Is INamespaceOrTypeSymbol Then
Return False
End If
Else
Return False
End If
If name.HasAnnotations(SpecialTypeAnnotation.Kind) Then
replacementNode = SyntaxFactory.PredefinedType(
SyntaxFactory.Token(name.GetLeadingTrivia(),
GetPredefinedKeywordKind(SpecialTypeAnnotation.GetSpecialType(name.GetAnnotations(SpecialTypeAnnotation.Kind).First())),
name.GetTrailingTrivia()))
issueSpan = name.Span
Return name.CanReplaceWithReducedNameInContext(replacementNode, semanticModel, cancellationToken)
Else
If Not name.IsRightSideOfDot() Then
Dim aliasReplacement As IAliasSymbol = Nothing
If name.TryReplaceWithAlias(semanticModel, aliasReplacement, optionSet.GetOption(SimplificationOptions.PreferAliasToQualification)) Then
Dim identifierToken = SyntaxFactory.Identifier(
name.GetLeadingTrivia(),
aliasReplacement.Name,
name.GetTrailingTrivia())
identifierToken = VisualBasicSimplificationService.TryEscapeIdentifierToken(
identifierToken,
semanticModel)
replacementNode = SyntaxFactory.IdentifierName(identifierToken)
Dim annotatedNodesOrTokens = name.GetAnnotatedNodesAndTokens(RenameAnnotation.Kind)
For Each annotatedNodeOrToken In annotatedNodesOrTokens
If annotatedNodeOrToken.IsToken Then
identifierToken = annotatedNodeOrToken.AsToken().CopyAnnotationsTo(identifierToken)
Else
replacementNode = annotatedNodeOrToken.AsNode().CopyAnnotationsTo(replacementNode)
End If
Next
annotatedNodesOrTokens = name.GetAnnotatedNodesAndTokens(AliasAnnotation.Kind)
For Each annotatedNodeOrToken In annotatedNodesOrTokens
If annotatedNodeOrToken.IsToken Then
identifierToken = annotatedNodeOrToken.AsToken().CopyAnnotationsTo(identifierToken)
Else
replacementNode = annotatedNodeOrToken.AsNode().CopyAnnotationsTo(replacementNode)
End If
Next
replacementNode = DirectCast(replacementNode, SimpleNameSyntax).WithIdentifier(identifierToken)
issueSpan = name.Span
' In case the alias name is the same as the last name of the alias target, we only include
' the left part of the name in the unnecessary span to Not confuse uses.
If name.Kind = SyntaxKind.QualifiedName Then
Dim qualifiedName As QualifiedNameSyntax = DirectCast(name, QualifiedNameSyntax)
If qualifiedName.Right.Identifier.ValueText = identifierToken.ValueText Then
issueSpan = qualifiedName.Left.Span
End If
End If
If name.CanReplaceWithReducedNameInContext(replacementNode, semanticModel, cancellationToken) Then
' check if the alias name ends with an Attribute suffic that can be omitted.
Dim replacementNodeWithoutAttributeSuffix As ExpressionSyntax = Nothing
Dim issueSpanWithoutAttributeSuffix As TextSpan = Nothing
If TryReduceAttributeSuffix(name, identifierToken, semanticModel, aliasReplacement IsNot Nothing, optionSet.GetOption(SimplificationOptions.PreferAliasToQualification), replacementNodeWithoutAttributeSuffix, issueSpanWithoutAttributeSuffix, cancellationToken) Then
If name.CanReplaceWithReducedName(replacementNodeWithoutAttributeSuffix, semanticModel, cancellationToken) Then
replacementNode = replacementNode.CopyAnnotationsTo(replacementNodeWithoutAttributeSuffix)
issueSpan = issueSpanWithoutAttributeSuffix
End If
End If
Return True
End If
Return False
End If
Dim nameHasNoAlias = False
If TypeOf name Is SimpleNameSyntax Then
Dim simpleName = DirectCast(name, SimpleNameSyntax)
If Not simpleName.Identifier.HasAnnotations(AliasAnnotation.Kind) Then
nameHasNoAlias = True
End If
End If
If TypeOf name Is QualifiedNameSyntax Then
Dim qualifiedNameSyntax = DirectCast(name, QualifiedNameSyntax)
If Not qualifiedNameSyntax.Right.Identifier.HasAnnotations(AliasAnnotation.Kind) Then
nameHasNoAlias = True
End If
End If
Dim aliasInfo = semanticModel.GetAliasInfo(name, cancellationToken)
If nameHasNoAlias AndAlso aliasInfo Is Nothing Then
If PreferPredefinedTypeKeywordInDeclarations(name, optionSet) OrElse
PreferPredefinedTypeKeywordInMemberAccess(name, optionSet) Then
Dim type = semanticModel.GetTypeInfo(name).Type
If type IsNot Nothing Then
Dim keywordKind = GetPredefinedKeywordKind(type.SpecialType)
If keywordKind <> SyntaxKind.None Then
replacementNode = SyntaxFactory.PredefinedType(
SyntaxFactory.Token(
name.GetLeadingTrivia(),
keywordKind,
name.GetTrailingTrivia()))
issueSpan = name.Span
Return name.CanReplaceWithReducedNameInContext(replacementNode, semanticModel, cancellationToken)
End If
End If
End If
End If
' Nullable rewrite: Nullable(Of Integer) -> Integer?
' Don't rewrite in the case where Nullable(Of Integer) is part of some qualified name like Nullable(Of Integer).Something
If (symbol.Kind = SymbolKind.NamedType) AndAlso (Not name.IsLeftSideOfQualifiedName) Then
Dim type = DirectCast(symbol, INamedTypeSymbol)
If aliasInfo Is Nothing AndAlso CanSimplifyNullable(type, name) Then
Dim genericName As GenericNameSyntax
If name.Kind = SyntaxKind.QualifiedName Then
genericName = DirectCast(DirectCast(name, QualifiedNameSyntax).Right, GenericNameSyntax)
Else
genericName = DirectCast(name, GenericNameSyntax)
End If
Dim oldType = genericName.TypeArgumentList.Arguments.First()
replacementNode = SyntaxFactory.NullableType(oldType).WithLeadingTrivia(name.GetLeadingTrivia())
issueSpan = name.Span
If name.CanReplaceWithReducedNameInContext(replacementNode, semanticModel, cancellationToken) Then
Return True
End If
End If
End If
End If
Select Case name.Kind
Case SyntaxKind.QualifiedName
' a module name was inserted by the name expansion, so removing this should be tried first.
Dim qualifiedName = DirectCast(name, QualifiedNameSyntax)
If qualifiedName.HasAnnotation(SimplificationHelpers.SimplifyModuleNameAnnotation) Then
If TryOmitModuleName(qualifiedName, semanticModel, replacementNode, issueSpan, cancellationToken) Then
Return True
End If
End If
replacementNode = qualifiedName.Right.WithLeadingTrivia(name.GetLeadingTrivia())
replacementNode = DirectCast(replacementNode, SimpleNameSyntax) _
.WithIdentifier(VisualBasicSimplificationService.TryEscapeIdentifierToken(
DirectCast(replacementNode, SimpleNameSyntax).Identifier,
semanticModel))
issueSpan = qualifiedName.Left.Span
If name.CanReplaceWithReducedName(replacementNode, semanticModel, cancellationToken) Then
Return True
End If
If optionSet.GetOption(SimplificationOptions.PreferOmittingModuleNamesInQualification) Then
If TryOmitModuleName(qualifiedName, semanticModel, replacementNode, issueSpan, cancellationToken) Then
Return True
End If
End If
Case SyntaxKind.IdentifierName
Dim identifier = DirectCast(name, IdentifierNameSyntax).Identifier
TryReduceAttributeSuffix(name, identifier, semanticModel, False, optionSet.GetOption(SimplificationOptions.PreferAliasToQualification), replacementNode, issueSpan, cancellationToken)
End Select
End If
If replacementNode Is Nothing Then
Return False
End If
Return name.CanReplaceWithReducedName(replacementNode, semanticModel, cancellationToken)
End Function
Private Function CanSimplifyNullable(type As INamedTypeSymbol, name As NameSyntax) As Boolean
If Not type.IsNullable Then
Return False
End If
If type.IsUnboundGenericType Then
' Don't simplify unbound generic type "Nullable(Of )".
Return False
End If
If Not InsideCrefReference(name) Then
' Nullable(Of T) can always be simplified to T? outside crefs.
Return True
End If
' Inside crefs, if the T in this Nullable(Of T) is being declared right here
' then this Nullable(Of T) is not a constructed generic type and we should
' not offer to simplify this to T?.
'
' For example, we should not offer the simplification in the following cases where
' T does not bind to an existing type / type parameter in the user's code.
' - <see cref="Nullable(Of T)"/>
' - <see cref="System.Nullable(Of T).Value"/>
'
' And we should offer the simplification in the following cases where SomeType and
' SomeMethod bind to a type and method declared elsewhere in the users code.
' - <see cref="SomeType.SomeMethod(Nullable(Of SomeType))"/>
If name.IsKind(SyntaxKind.GenericName) Then
If (name.IsParentKind(SyntaxKind.CrefReference)) OrElse ' cref="Nullable(Of T)"
(name.IsParentKind(SyntaxKind.QualifiedName) AndAlso name.Parent?.IsParentKind(SyntaxKind.CrefReference)) OrElse ' cref="System.Nullable(Of T)"
(name.IsParentKind(SyntaxKind.QualifiedName) AndAlso name.Parent?.IsParentKind(SyntaxKind.QualifiedName) AndAlso name.Parent?.Parent?.IsParentKind(SyntaxKind.CrefReference)) Then ' cref="System.Nullable(Of T).Value"
' Unfortunately, unlike in corresponding C# case, we need syntax based checking to detect these cases because of bugs in the VB SemanticModel.
' See https://github.com/dotnet/roslyn/issues/2196, https://github.com/dotnet/roslyn/issues/2197
Return False
End If
End If
Dim argument = type.TypeArguments.SingleOrDefault()
If argument Is Nothing OrElse argument.IsErrorType() Then
Return False
End If
Dim argumentDecl = argument.DeclaringSyntaxReferences.FirstOrDefault()
If argumentDecl Is Nothing Then
' The type argument is a type from metadata - so this is a constructed generic nullable type that can be simplified (e.g. Nullable(Of Integer)).
Return True
End If
Return Not name.Span.Contains(argumentDecl.Span)
End Function
Private Function TryReduceAttributeSuffix(
name As NameSyntax,
identifierToken As SyntaxToken,
semanticModel As SemanticModel,
isIdentifierNameFromAlias As Boolean,
preferAliasToQualification As Boolean,
<Out()> ByRef replacementNode As ExpressionSyntax,
<Out()> ByRef issueSpan As TextSpan,
cancellationToken As CancellationToken
) As Boolean
If SyntaxFacts.IsAttributeName(name) AndAlso Not isIdentifierNameFromAlias Then
' When the replacement is an Alias we don't want the "Attribute" Suffix to be removed because this will result in symbol change
Dim aliasSymbol = semanticModel.GetAliasInfo(name, cancellationToken)
If (aliasSymbol IsNot Nothing AndAlso preferAliasToQualification AndAlso
String.Compare(aliasSymbol.Name, identifierToken.ValueText, StringComparison.OrdinalIgnoreCase) = 0) Then
Return False
End If
If name.Parent.Kind = SyntaxKind.Attribute OrElse name.IsRightSideOfDot() Then
Dim newIdentifierText = String.Empty
' an attribute that should keep it (unnecessary "Attribute" suffix should be annotated with a DontSimplifyAnnotation
If identifierToken.HasAnnotation(SimplificationHelpers.DontSimplifyAnnotation) Then
newIdentifierText = identifierToken.ValueText + "Attribute"
ElseIf identifierToken.ValueText.TryReduceAttributeSuffix(newIdentifierText) Then
issueSpan = New TextSpan(name.Span.End - 9, 9)
Else
Return False
End If
' escape it (VB allows escaping even for abbreviated identifiers, C# does not!)
Dim newIdentifierToken = identifierToken.CopyAnnotationsTo(
SyntaxFactory.Identifier(
identifierToken.LeadingTrivia,
newIdentifierText,
identifierToken.TrailingTrivia))
newIdentifierToken = VisualBasicSimplificationService.TryEscapeIdentifierToken(newIdentifierToken, semanticModel)
replacementNode = SyntaxFactory.IdentifierName(newIdentifierToken).WithLeadingTrivia(name.GetLeadingTrivia())
Return True
End If
End If
Return False
End Function
''' <summary>
''' Checks if the SyntaxNode is a name of a namespace declaration. To be a namespace name, the syntax
''' must be parented by an namespace declaration and the node itself must be equal to the declaration's Name
''' property.
''' </summary>
Private Function IsPartOfNamespaceDeclarationName(node As SyntaxNode) As Boolean
Dim nextNode As SyntaxNode = node
Do While nextNode IsNot Nothing
Select Case nextNode.Kind
Case SyntaxKind.IdentifierName, SyntaxKind.QualifiedName
node = nextNode
nextNode = nextNode.Parent
Case SyntaxKind.NamespaceStatement
Dim namespaceStatement = DirectCast(nextNode, NamespaceStatementSyntax)
Return namespaceStatement.Name Is node
Case Else
Return False
End Select
Loop
Return False
End Function
Private Function TryOmitModuleName(name As QualifiedNameSyntax, semanticModel As SemanticModel, <Out()> ByRef replacementNode As ExpressionSyntax, <Out()> ByRef issueSpan As TextSpan, cancellationToken As CancellationToken) As Boolean
If name.IsParentKind(SyntaxKind.QualifiedName) Then
Dim symbolForName = semanticModel.GetSymbolInfo(DirectCast(name.Parent, QualifiedNameSyntax)).Symbol
' in case this QN is used in a "New NSName.ModuleName.MemberName()" expression
' the returned symbol is a constructor. Then we need to get the containing type.
If symbolForName.IsConstructor Then
symbolForName = symbolForName.ContainingType
End If
If symbolForName.IsModuleMember Then
replacementNode = name.Left.WithLeadingTrivia(name.GetLeadingTrivia())
issueSpan = name.Right.Span
Dim parent = DirectCast(name.Parent, QualifiedNameSyntax)
Dim parentReplacement = parent.ReplaceNode(parent.Left, replacementNode)
If parent.CanReplaceWithReducedName(parentReplacement, semanticModel, cancellationToken) Then
Return True
End If
End If
End If
Return False
End Function
<Extension()>
Private Function TrySimplify(
expression As ExpressionSyntax,
semanticModel As SemanticModel,
optionSet As OptionSet,
<Out()> ByRef replacementNode As ExpressionSyntax,
<Out()> ByRef issueSpan As TextSpan
) As Boolean
replacementNode = Nothing
issueSpan = Nothing
Select Case expression.Kind
Case SyntaxKind.SimpleMemberAccessExpression
If True Then
Dim memberAccess = DirectCast(expression, MemberAccessExpressionSyntax)
Dim newLeft As ExpressionSyntax = Nothing
If TrySimplifyMemberAccessOrQualifiedName(memberAccess.Expression, memberAccess.Name, semanticModel, optionSet, newLeft, issueSpan) Then
' replacement node might not be in it's simplest form, so add simplify annotation to it.
replacementNode = memberAccess.Update(memberAccess.Kind, newLeft, memberAccess.OperatorToken, memberAccess.Name).WithAdditionalAnnotations(Simplifier.Annotation)
' Ensure that replacement doesn't change semantics.
Return Not ReplacementChangesSemantics(memberAccess, replacementNode, semanticModel)
End If
Return False
End If
Case SyntaxKind.QualifiedName
If True Then
Dim qualifiedName = DirectCast(expression, QualifiedNameSyntax)
Dim newLeft As ExpressionSyntax = Nothing
If TrySimplifyMemberAccessOrQualifiedName(qualifiedName.Left, qualifiedName.Right, semanticModel, optionSet, newLeft, issueSpan) Then
If Not TypeOf newLeft Is NameSyntax Then
Contract.Fail("QualifiedName Left = " + qualifiedName.Left.ToString() + " and QualifiedName Right = " + qualifiedName.Right.ToString() + " . Left is tried to be replaced with the PredefinedType " + replacementNode.ToString())
End If
' replacement node might not be in it's simplest form, so add simplify annotation to it.
replacementNode = qualifiedName.Update(DirectCast(newLeft, NameSyntax), qualifiedName.DotToken, qualifiedName.Right).WithAdditionalAnnotations(Simplifier.Annotation)
' Ensure that replacement doesn't change semantics.
Return Not ReplacementChangesSemantics(qualifiedName, replacementNode, semanticModel)
End If
Return False
End If
End Select
Return False
End Function
Private Function ReplacementChangesSemantics(originalExpression As ExpressionSyntax, replacedExpression As ExpressionSyntax, semanticModel As SemanticModel) As Boolean
Dim speculationAnalyzer = New SpeculationAnalyzer(originalExpression, replacedExpression, semanticModel, CancellationToken.None)
Return speculationAnalyzer.ReplacementChangesSemantics()
End Function
' Note: The caller needs to verify that replacement doesn't change semantics of the original expression.
Private Function TrySimplifyMemberAccessOrQualifiedName(
left As ExpressionSyntax,
right As ExpressionSyntax,
semanticModel As SemanticModel,
optionSet As OptionSet,
<Out()> ByRef replacementNode As ExpressionSyntax,
<Out()> ByRef issueSpan As TextSpan
) As Boolean
replacementNode = Nothing
issueSpan = Nothing
If left IsNot Nothing AndAlso right IsNot Nothing Then
Dim leftSymbol = SimplificationHelpers.GetOriginalSymbolInfo(semanticModel, left)
If leftSymbol IsNot Nothing AndAlso leftSymbol.Kind = SymbolKind.NamedType Then
Dim rightSymbol = SimplificationHelpers.GetOriginalSymbolInfo(semanticModel, right)
If rightSymbol IsNot Nothing AndAlso (rightSymbol.IsStatic OrElse rightSymbol.Kind = SymbolKind.NamedType) Then
' Static member access or nested type member access.
Dim containingType As INamedTypeSymbol = rightSymbol.ContainingType
Dim isInCref = left.Ancestors(ascendOutOfTrivia:=True).OfType(Of CrefReferenceSyntax)().Any()
' Crefs in VB , irrespective of the expression are parsed as QualifiedName (no MemberAccessExpression)
' Hence the Left can never be a PredefinedType (or anything other than NameSyntax)
If isInCref AndAlso TypeOf rightSymbol Is IMethodSymbol AndAlso Not containingType.SpecialType = SpecialType.None Then
Return False
End If
If containingType IsNot Nothing AndAlso Not containingType.Equals(leftSymbol) Then
Dim namedType = TryCast(leftSymbol, INamedTypeSymbol)
If namedType IsNot Nothing Then
If ((namedType.GetBaseTypes().Contains(containingType) AndAlso
Not optionSet.GetOption(SimplificationOptions.AllowSimplificationToBaseType)) OrElse
(Not optionSet.GetOption(SimplificationOptions.AllowSimplificationToGenericType) AndAlso
containingType.TypeArguments.Count() <> 0)) Then
Return False
End If
End If
' We have a static member access or a nested type member access using a more derived type.
' Simplify syntax so as to use accessed member's most immediate containing type instead of the derived type.
replacementNode = containingType.GenerateTypeSyntax().WithLeadingTrivia(left.GetLeadingTrivia()).WithTrailingTrivia(left.GetTrailingTrivia()).WithAdditionalAnnotations(Simplifier.Annotation)
issueSpan = left.Span
Return True
End If
End If
End If
End If
Return False
End Function
<Extension>
Private Function TryReplaceWithAlias(
node As ExpressionSyntax,
semanticModel As SemanticModel,
<Out> ByRef aliasReplacement As IAliasSymbol,
Optional preferAliasToQualifiedName As Boolean = False) As Boolean
aliasReplacement = Nothing
If Not node.IsAliasReplaceableExpression() Then
Return False
End If
Dim symbol = semanticModel.GetSymbolInfo(node).Symbol
If (symbol.IsConstructor()) Then
symbol = symbol.ContainingType
End If
' The following condition checks if the user has used alias in the original code and
' if so the expression is replaced with the Alias
If TypeOf node Is QualifiedNameSyntax Then
Dim qualifiedNameNode = DirectCast(node, QualifiedNameSyntax)
If qualifiedNameNode.Right.Identifier.HasAnnotations(AliasAnnotation.Kind) Then
Dim aliasAnnotationInfo = qualifiedNameNode.Right.Identifier.GetAnnotations(AliasAnnotation.Kind).Single()
Dim aliasName = AliasAnnotation.GetAliasName(aliasAnnotationInfo)
Dim aliasIdentifier = SyntaxFactory.IdentifierName(aliasName)
Dim aliasTypeInfo = semanticModel.GetSpeculativeAliasInfo(node.SpanStart, aliasIdentifier, SpeculativeBindingOption.BindAsTypeOrNamespace)
If Not aliasTypeInfo Is Nothing Then
aliasReplacement = aliasTypeInfo
Return ValidateAliasForTarget(aliasReplacement, semanticModel, node, symbol)
End If
End If
End If
If node.Kind = SyntaxKind.IdentifierName AndAlso semanticModel.GetAliasInfo(DirectCast(node, IdentifierNameSyntax)) IsNot Nothing Then
Return False
End If
' an alias can only replace a type Or namespace
If symbol Is Nothing OrElse
(symbol.Kind <> SymbolKind.Namespace AndAlso symbol.Kind <> SymbolKind.NamedType) Then
Return False
End If
If symbol Is Nothing OrElse Not TypeOf (symbol) Is INamespaceOrTypeSymbol Then
Return False
End If
If TypeOf node Is QualifiedNameSyntax Then
Dim qualifiedName = DirectCast(node, QualifiedNameSyntax)
If Not qualifiedName.Right.HasAnnotation(Simplifier.SpecialTypeAnnotation) Then
Dim type = semanticModel.GetTypeInfo(node).Type
If Not type Is Nothing Then
Dim keywordKind = GetPredefinedKeywordKind(type.SpecialType)
If keywordKind <> SyntaxKind.None Then
preferAliasToQualifiedName = False
End If
End If
End If
End If
aliasReplacement = DirectCast(symbol, INamespaceOrTypeSymbol).GetAliasForSymbol(node, semanticModel)
If aliasReplacement IsNot Nothing And preferAliasToQualifiedName Then
Return ValidateAliasForTarget(aliasReplacement, semanticModel, node, symbol)
End If
Return False
End Function
' We must verify that the alias actually binds back to the thing it's aliasing.
' It's possible there is another symbol with the same name as the alias that binds first
Private Function ValidateAliasForTarget(aliasReplacement As IAliasSymbol, semanticModel As SemanticModel, node As ExpressionSyntax, symbol As ISymbol) As Boolean
Dim aliasName = aliasReplacement.Name
Dim boundSymbols = semanticModel.LookupNamespacesAndTypes(node.SpanStart, name:=aliasName)
If boundSymbols.Length = 1 Then
Dim boundAlias = TryCast(boundSymbols(0), IAliasSymbol)
If boundAlias IsNot Nothing And aliasReplacement.Target.Equals(symbol) Then
If symbol.IsAttribute Then
boundSymbols = semanticModel.LookupNamespacesAndTypes(node.Span.Start, name:=aliasName + "Attribute")
Return boundSymbols.IsEmpty
End If
Return True
End If
End If
Return False
End Function
<Extension()>
Private Function CanReplaceWithReducedName(
name As NameSyntax,
replacementNode As ExpressionSyntax,
semanticModel As SemanticModel,
cancellationToken As CancellationToken
) As Boolean
Dim speculationAnalyzer = New SpeculationAnalyzer(name, replacementNode, semanticModel, cancellationToken)
If speculationAnalyzer.ReplacementChangesSemantics() Then
Return False
End If
Return name.CanReplaceWithReducedNameInContext(replacementNode, semanticModel, cancellationToken)
End Function
<Extension>
Private Function CanReplaceWithReducedNameInContext(name As NameSyntax, replacementNode As ExpressionSyntax, semanticModel As SemanticModel, cancellationToken As CancellationToken) As Boolean
' Special case. if this new minimal name parses out to a predefined type, then we
' have to make sure that we're not in a using alias. That's the one place where the
' language doesn't allow predefined types. You have to use the fully qualified name
' instead.
Dim invalidTransformation1 = IsNonNameSyntaxInImportsDirective(name, replacementNode)
Dim invalidTransformation2 = IsReservedNameInAttribute(name, replacementNode)
Dim invalidTransformation3 = IsNullableTypeSyntaxLeftOfDotInMemberAccess(name, replacementNode)
Return Not (invalidTransformation1 OrElse invalidTransformation2 OrElse invalidTransformation3)
End Function
Private Function IsMeOrNamedTypeOrNamespace(expression As ExpressionSyntax, semanticModel As SemanticModel) As Boolean
If expression.Kind = SyntaxKind.MeExpression Then
Return True
End If
Dim expressionInfo = semanticModel.GetSymbolInfo(expression)
If SimplificationHelpers.IsValidSymbolInfo(expressionInfo.Symbol) Then
If TypeOf expressionInfo.Symbol Is INamespaceOrTypeSymbol Then
Return True
End If
If expressionInfo.Symbol.IsThisParameter() Then
Return True
End If
End If
Return False
End Function
''' <summary>
''' Returns the predefined keyword kind for a given special type.
''' </summary>
''' <param name="type">The specialtype of this type.</param>
''' <returns>The keyword kind for a given special type, or SyntaxKind.None if the type name is not a predefined type.</returns>
Private Function GetPredefinedKeywordKind(type As SpecialType) As SyntaxKind
Select Case type
Case SpecialType.System_Boolean
Return SyntaxKind.BooleanKeyword
Case SpecialType.System_Byte
Return SyntaxKind.ByteKeyword
Case SpecialType.System_SByte
Return SyntaxKind.SByteKeyword
Case SpecialType.System_Int32
Return SyntaxKind.IntegerKeyword
Case SpecialType.System_UInt32
Return SyntaxKind.UIntegerKeyword
Case SpecialType.System_Int16
Return SyntaxKind.ShortKeyword
Case SpecialType.System_UInt16
Return SyntaxKind.UShortKeyword
Case SpecialType.System_Int64
Return SyntaxKind.LongKeyword
Case SpecialType.System_UInt64
Return SyntaxKind.ULongKeyword
Case SpecialType.System_Single
Return SyntaxKind.SingleKeyword
Case SpecialType.System_Double
Return SyntaxKind.DoubleKeyword
Case SpecialType.System_Decimal
Return SyntaxKind.DecimalKeyword
Case SpecialType.System_String
Return SyntaxKind.StringKeyword
Case SpecialType.System_Char
Return SyntaxKind.CharKeyword
Case SpecialType.System_Object
Return SyntaxKind.ObjectKeyword
Case SpecialType.System_DateTime
Return SyntaxKind.DateKeyword
Case Else
Return SyntaxKind.None
End Select
End Function
Private Function IsNullableTypeSyntaxLeftOfDotInMemberAccess(expression As ExpressionSyntax, simplifiedNode As ExpressionSyntax) As Boolean
Return expression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) AndAlso
simplifiedNode.Kind = SyntaxKind.NullableType
End Function
Private Function IsNonNameSyntaxInImportsDirective(expression As ExpressionSyntax, simplifiedNode As ExpressionSyntax) As Boolean
Return TypeOf expression.Parent Is ImportsClauseSyntax AndAlso
Not TypeOf simplifiedNode Is NameSyntax
End Function
Public Function IsReservedNameInAttribute(originalName As NameSyntax, simplifiedNode As ExpressionSyntax) As Boolean
Dim attribute = originalName.GetAncestorOrThis(Of AttributeSyntax)()
If attribute Is Nothing Then
Return False
End If
Dim identifier As SimpleNameSyntax
If simplifiedNode.Kind = SyntaxKind.IdentifierName Then
identifier = DirectCast(simplifiedNode, SimpleNameSyntax)
ElseIf simplifiedNode.Kind = SyntaxKind.QualifiedName Then
identifier = DirectCast(DirectCast(simplifiedNode, QualifiedNameSyntax).Left, SimpleNameSyntax)
Else
Return False
End If
If identifier.Identifier.IsBracketed Then
Return False
End If
If attribute.Target Is Nothing Then
Dim identifierValue = SyntaxFacts.MakeHalfWidthIdentifier(identifier.Identifier.ValueText)
If CaseInsensitiveComparison.Equals(identifierValue, "Assembly") OrElse
CaseInsensitiveComparison.Equals(identifierValue, "Module") Then
Return True
End If
End If
Return False
End Function
End Module
End Namespace
| Java |
/*
* Copyright 2015 Textocat
*
* 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.textocat.textokit.morph.commons;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.textocat.textokit.morph.dictionary.resource.GramModel;
import com.textocat.textokit.morph.fs.Word;
import com.textocat.textokit.morph.fs.Wordform;
import com.textocat.textokit.postagger.MorphCasUtils;
import java.util.BitSet;
import java.util.Set;
import static com.textocat.textokit.morph.commons.PunctuationUtils.punctuationTagMap;
import static com.textocat.textokit.morph.model.MorphConstants.*;
/**
* EXPERIMENTAL <br>
* EXPERIMENTAL <br>
* EXPERIMENTAL
*
* @author Rinat Gareev
*/
public class TagUtils {
private static final Set<String> closedPosSet = ImmutableSet.of(NPRO, Apro, PREP, CONJ, PRCL);
/**
* @param dict
* @return function that returns true if the given gram bits represents a
* closed class tag
*/
public static Function<BitSet, Boolean> getClosedClassIndicator(GramModel gm) {
// initialize mask
final BitSet closedClassTagsMask = new BitSet();
for (String cpGram : closedPosSet) {
closedClassTagsMask.set(gm.getGrammemNumId(cpGram));
}
//
return new Function<BitSet, Boolean>() {
@Override
public Boolean apply(BitSet _wfBits) {
BitSet wfBits = (BitSet) _wfBits.clone();
wfBits.and(closedClassTagsMask);
return !wfBits.isEmpty();
}
};
}
// FIXME refactor hard-coded dependency on a tag mapper implementation
public static boolean isClosedClassTag(String tag) {
return closedClassPunctuationTags.contains(tag)
|| !Sets.intersection(
GramModelBasedTagMapper.parseTag(tag), closedPosSet)
.isEmpty();
}
public static String postProcessExternalTag(String tag) {
return !"null".equals(String.valueOf(tag)) ? tag : null;
}
public static final Set<String> closedClassPunctuationTags = ImmutableSet
.copyOf(punctuationTagMap.values());
public static final Function<Word, String> tagFunction() {
return tagFunction;
}
private static final Function<Word, String> tagFunction = new Function<Word, String>() {
@Override
public String apply(Word word) {
if (word == null) {
return null;
}
Wordform wf = MorphCasUtils.requireOnlyWordform(word);
return wf.getPos();
}
};
private TagUtils() {
}
}
| Java |
/**
* Copyright 2016 The AMP HTML 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.
*/
import {Poller} from './poller';
import {Services} from '../../../src/services';
import {addParamToUrl} from '../../../src/url';
import {fetchDocument} from '../../../src/document-fetcher';
import {getMode} from '../../../src/mode';
import {getServicePromiseForDoc} from '../../../src/service';
import {toArray} from '../../../src/types';
import {userAssert} from '../../../src/log';
/** @const {string} */
export const SERVICE_ID = 'liveListManager';
const TRANSFORMED_PREFIX = 'google;v=';
/**
* Property used for storing id of custom slot. This custom slot can be used to
* replace the default "items" and "update" slot.
* @const {string}
*/
export const AMP_LIVE_LIST_CUSTOM_SLOT_ID = 'AMP_LIVE_LIST_CUSTOM_SLOT_ID';
/**
* Manages registered AmpLiveList components.
* Primarily handles network requests and updates the components
* if necessary.
* @implements {../../../src/service.Disposable}
*/
export class LiveListManager {
/**
* @param {!../../../src/service/ampdoc-impl.AmpDoc} ampdoc
*/
constructor(ampdoc) {
/** @const */
this.ampdoc = ampdoc;
/** @private @const {!Object<string, !./amp-live-list.AmpLiveList>} */
this.liveLists_ = Object.create(null);
/** @private @const {!../../../src/service/extensions-impl.Extensions} */
this.extensions_ = Services.extensionsFor(this.ampdoc.win);
/** @private {number} */
this.interval_ = 15000;
/** @private @const {!Array<number>} */
this.intervals_ = [this.interval_];
/** @private {?Poller} */
this.poller_ = null;
/** @private @const {string} */
this.url_ = this.ampdoc.getUrl();
/** @private {time} */
this.latestUpdateTime_ = 0;
/** @private @const {function(): Promise} */
this.work_ = this.fetchDocument_.bind(this);
/** @private @const {boolean} */
this.isTransformed_ = isDocTransformed(ampdoc.getRootNode());
// Only start polling when doc is ready and when the doc is visible.
this.whenDocReady_().then(() => {
// Switch out the poller interval if we can find a lower one and
// then make sure to stop polling if doc is not visible.
this.interval_ = Math.min.apply(Math, this.intervals_);
const initialUpdateTimes = Object.keys(this.liveLists_).map((key) =>
this.liveLists_[key].getUpdateTime()
);
this.latestUpdateTime_ = Math.max.apply(Math, initialUpdateTimes);
// For testing purposes only, we speed up the interval of the update.
// This should NEVER be allowed in production.
if (getMode().localDev) {
const path = this.ampdoc.win.location.pathname;
if (
path.indexOf('/examples/live-list-update.amp.html') != -1 ||
path.indexOf('/examples/live-blog.amp.html') != -1 ||
path.indexOf('/examples/live-blog-non-floating-button.amp.html') != -1
) {
this.interval_ = 5000;
}
}
this.poller_ = new Poller(this.ampdoc.win, this.interval_, this.work_);
// If no live-list is active on dom ready, we don't need to poll at all.
if (this.ampdoc.isVisible() && this.hasActiveLiveLists_()) {
this.poller_.start();
}
this.setupVisibilityHandler_();
});
}
/** @override */
dispose() {
this.poller_.stop();
}
/**
* @param {!Element} element
* @return {!Promise<!LiveListManager>}
*/
static forDoc(element) {
return /** @type {!Promise<!LiveListManager>} */ (getServicePromiseForDoc(
element,
SERVICE_ID
));
}
/**
* Checks if any of the registered amp-live-list components is active/
*
* @return {boolean}
* @private
*/
hasActiveLiveLists_() {
return Object.keys(this.liveLists_).some((key) => {
return this.liveLists_[key].isEnabled();
});
}
/**
* Makes a request to the given url for the latest document.
*
* @private
*/
fetchDocument_() {
let url = this.url_;
if (this.latestUpdateTime_ > 0) {
url = addParamToUrl(
url,
'amp_latest_update_time',
String(this.latestUpdateTime_)
);
}
if (this.isTransformed_) {
const urlService = Services.urlForDoc(this.ampdoc.getBody());
url = urlService.getCdnUrlOnOrigin(url);
}
// TODO(erwinm): add update time here when possible.
return fetchDocument(this.ampdoc.win, url, {}).then(
this.updateLiveLists_.bind(this)
);
}
/**
* Gets all live lists and updates them with their corresponding counterparts.
* Saves latest update time.
*
* @param {!Document} doc
* @private
*/
updateLiveLists_(doc) {
this.installExtensionsForDoc_(doc);
const allLiveLists = this.getLiveLists_(doc).concat(
this.getCustomSlots_(doc)
);
const updateTimes = allLiveLists.map(this.updateLiveList_.bind(this));
const latestUpdateTime = Math.max.apply(Math, [0].concat(updateTimes));
if (latestUpdateTime > 0) {
this.latestUpdateTime_ = latestUpdateTime;
}
// We need to do this after calling `updateLiveList` since that
// would apply the disabled attribute if any exist from the server.
if (!this.hasActiveLiveLists_()) {
this.poller_.stop();
}
}
/**
* Queries the document for all `amp-live-list` tags.
*
* @param {!Document} doc
* @return {!Array<!Element>}
* @private
*/
getLiveLists_(doc) {
return Array.prototype.slice.call(
doc.getElementsByTagName('amp-live-list')
);
}
/**
* Queries for custom slots that will be used to host the live elements. This
* overrides looking for live elements inside the default <amp-live-list>
* element.
*
* @param {!Document} doc
* @return {!Array<!Element>}
* @private
*/
getCustomSlots_(doc) {
const liveListsWithCustomSlots = Object.keys(this.liveLists_).filter((id) =>
this.liveLists_[id].hasCustomSlot()
);
return liveListsWithCustomSlots.map((id) => {
const customSlotId = this.liveLists_[id].element[
AMP_LIVE_LIST_CUSTOM_SLOT_ID
];
return doc.getElementById(customSlotId);
});
}
/**
* Updates the appropriate `amp-live-list` with its updates from the server.
*
* @param {!Element} liveList Live list or custom element that built it.
* @return {number}
*/
updateLiveList_(liveList) {
// amp-live-list elements can be appended dynamically in the client by
// another component using the `i-amphtml-` + `other-component-id` +
// `-dynamic-list` combination as the ID of the amp-live-list.
//
// The fact that we know how this ID is built allows us to find the
// amp-live-list element in the server document. See live-story-manager.js
// for an example.
const dynamicId = 'i-amphtml-' + liveList.id + '-dynamic-list';
const id =
dynamicId in this.liveLists_ ? dynamicId : liveList.getAttribute('id');
userAssert(id, 'amp-live-list must have an id.');
userAssert(
id in this.liveLists_,
'amp-live-list#%s found but did not exist on original page load.',
id
);
const inClientDomLiveList = this.liveLists_[id];
inClientDomLiveList.toggle(
!liveList.hasAttribute('disabled') &&
// When the live list is an amp-story, we use an amp-story specific
// attribute so publishers can disable the live story functionality.
!liveList.hasAttribute('live-story-disabled')
);
if (inClientDomLiveList.isEnabled()) {
return inClientDomLiveList.update(liveList);
}
return 0;
}
/**
* Register an `amp-live-list` instance for updates.
*
* @param {string} id
* @param {!./amp-live-list.AmpLiveList} liveList
*/
register(id, liveList) {
if (id in this.liveLists_) {
return;
}
this.liveLists_[id] = liveList;
this.intervals_.push(liveList.getInterval());
// Polling may not be started yet if no live lists were registered by
// doc ready in LiveListManager's constructor.
if (liveList.isEnabled() && this.poller_ && this.ampdoc.isVisible()) {
this.poller_.start();
}
}
/**
* Returns a promise that is resolved when the document is ready.
* @return {!Promise}
* @private
*/
whenDocReady_() {
return this.ampdoc.whenReady();
}
/**
* Listens to he doc visibility changed event.
* @private
*/
setupVisibilityHandler_() {
// Polling should always be stopped when document is no longer visible.
this.ampdoc.onVisibilityChanged(() => {
if (this.ampdoc.isVisible() && this.hasActiveLiveLists_()) {
// We use immediate so that the user starts getting updates
// right away when they've switched back to the page.
this.poller_.start(/** immediate */ true);
} else {
this.poller_.stop();
}
});
}
/**
* @param {!Document} doc
*/
installExtensionsForDoc_(doc) {
const extensions = toArray(
doc.querySelectorAll('script[custom-element], script[custom-template]')
);
extensions.forEach((script) => {
const extensionName =
script.getAttribute('custom-element') ||
script.getAttribute('custom-template');
// This is a cheap operation if extension is already installed so no need
// to over optimize checks.
this.extensions_.installExtensionForDoc(this.ampdoc, extensionName);
});
}
/**
* Default minimum data poll interval value.
*
* @return {number}
*/
static getMinDataPollInterval() {
// TODO(erwinm): determine if value is too low
return 15000;
}
/**
* Default minimum data max items per page value.
*
* @return {number}
*/
static getMinDataMaxItemsPerPage() {
return 1;
}
}
/**
* Detects if a document has had transforms applied
* e.g. by a domain with signed exchange domain enabled.
* @param {!Document|!ShadowRoot} root
* @return {boolean}
*/
function isDocTransformed(root) {
if (!root.ownerDocument) {
return false;
}
const {documentElement} = root.ownerDocument;
const transformed = documentElement.getAttribute('transformed');
return Boolean(transformed) && transformed.startsWith(TRANSFORMED_PREFIX);
}
| Java |
package org.eclipse.jetty.server.handler;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.net.Socket;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.junit.AfterClass;
/**
* @version $Revision$ $Date$
*/
public abstract class AbstractConnectHandlerTest
{
protected static Server server;
protected static Connector serverConnector;
protected static Server proxy;
protected static Connector proxyConnector;
protected static void startServer(Connector connector, Handler handler) throws Exception
{
server = new Server();
serverConnector = connector;
server.addConnector(serverConnector);
server.setHandler(handler);
server.start();
}
protected static void startProxy() throws Exception
{
proxy = new Server();
proxyConnector = new SelectChannelConnector();
proxy.addConnector(proxyConnector);
proxy.setHandler(new ConnectHandler());
proxy.start();
}
@AfterClass
public static void stop() throws Exception
{
stopProxy();
stopServer();
}
protected static void stopServer() throws Exception
{
server.stop();
server.join();
}
protected static void stopProxy() throws Exception
{
proxy.stop();
proxy.join();
}
protected Response readResponse(BufferedReader reader) throws IOException
{
// Simplified parser for HTTP responses
String line = reader.readLine();
if (line == null)
throw new EOFException();
Matcher responseLine = Pattern.compile("HTTP/1\\.1\\s+(\\d+)").matcher(line);
assertTrue(responseLine.lookingAt());
String code = responseLine.group(1);
Map<String, String> headers = new LinkedHashMap<String, String>();
while ((line = reader.readLine()) != null)
{
if (line.trim().length() == 0)
break;
Matcher header = Pattern.compile("([^:]+):\\s*(.*)").matcher(line);
assertTrue(header.lookingAt());
String headerName = header.group(1);
String headerValue = header.group(2);
headers.put(headerName.toLowerCase(), headerValue.toLowerCase());
}
StringBuilder body = new StringBuilder();
if (headers.containsKey("content-length"))
{
int length = Integer.parseInt(headers.get("content-length"));
for (int i = 0; i < length; ++i)
{
char c = (char)reader.read();
body.append(c);
}
}
else if ("chunked".equals(headers.get("transfer-encoding")))
{
while ((line = reader.readLine()) != null)
{
if ("0".equals(line))
{
line = reader.readLine();
assertEquals("", line);
break;
}
int length = Integer.parseInt(line, 16);
for (int i = 0; i < length; ++i)
{
char c = (char)reader.read();
body.append(c);
}
line = reader.readLine();
assertEquals("", line);
}
}
return new Response(code, headers, body.toString().trim());
}
protected Socket newSocket() throws IOException
{
Socket socket = new Socket("localhost", proxyConnector.getLocalPort());
socket.setSoTimeout(5000);
return socket;
}
protected class Response
{
private final String code;
private final Map<String, String> headers;
private final String body;
private Response(String code, Map<String, String> headers, String body)
{
this.code = code;
this.headers = headers;
this.body = body;
}
public String getCode()
{
return code;
}
public Map<String, String> getHeaders()
{
return headers;
}
public String getBody()
{
return body;
}
@Override
public String toString()
{
StringBuilder builder = new StringBuilder();
builder.append(code).append("\r\n");
for (Map.Entry<String, String> entry : headers.entrySet())
builder.append(entry.getKey()).append(": ").append(entry.getValue()).append("\r\n");
builder.append("\r\n");
builder.append(body);
return builder.toString();
}
}
}
| Java |
package org.apereo.cas.memcached.kryo;
import org.apereo.cas.authentication.AcceptUsersAuthenticationHandler;
import org.apereo.cas.authentication.AuthenticationBuilder;
import org.apereo.cas.authentication.BasicCredentialMetaData;
import org.apereo.cas.authentication.DefaultAuthenticationBuilder;
import org.apereo.cas.authentication.DefaultAuthenticationHandlerExecutionResult;
import org.apereo.cas.authentication.UsernamePasswordCredential;
import org.apereo.cas.authentication.principal.DefaultPrincipalFactory;
import org.apereo.cas.mock.MockServiceTicket;
import org.apereo.cas.mock.MockTicketGrantingTicket;
import org.apereo.cas.services.RegisteredServiceTestUtils;
import org.apereo.cas.ticket.TicketGrantingTicket;
import org.apereo.cas.ticket.TicketGrantingTicketImpl;
import org.apereo.cas.ticket.support.MultiTimeUseOrTimeoutExpirationPolicy;
import org.apereo.cas.ticket.support.NeverExpiresExpirationPolicy;
import com.esotericsoftware.kryo.KryoException;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.junit.Test;
import javax.security.auth.login.AccountNotFoundException;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import static org.junit.Assert.*;
/**
* Unit test for {@link CasKryoTranscoder} class.
*
* @author Marvin S. Addison
* @since 3.0.0
*/
@Slf4j
public class CasKryoTranscoderTests {
private static final String ST_ID = "ST-1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890ABCDEFGHIJK";
private static final String TGT_ID = "TGT-1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890ABCDEFGHIJK-cas1";
private static final String USERNAME = "handymanbob";
private static final String PASSWORD = "foo";
private static final String NICKNAME_KEY = "nickname";
private static final String NICKNAME_VALUE = "bob";
private final CasKryoTranscoder transcoder;
private final Map<String, Object> principalAttributes;
public CasKryoTranscoderTests() {
val classesToRegister = new ArrayList<Class>();
classesToRegister.add(MockServiceTicket.class);
classesToRegister.add(MockTicketGrantingTicket.class);
this.transcoder = new CasKryoTranscoder(new CasKryoPool(classesToRegister));
this.principalAttributes = new HashMap<>();
this.principalAttributes.put(NICKNAME_KEY, NICKNAME_VALUE);
}
@Test
public void verifyEncodeDecodeTGTImpl() {
val userPassCredential = new UsernamePasswordCredential(USERNAME, PASSWORD);
final AuthenticationBuilder bldr = new DefaultAuthenticationBuilder(new DefaultPrincipalFactory()
.createPrincipal("user", new HashMap<>(this.principalAttributes)));
bldr.setAttributes(new HashMap<>(this.principalAttributes));
bldr.setAuthenticationDate(ZonedDateTime.now());
bldr.addCredential(new BasicCredentialMetaData(userPassCredential));
bldr.addFailure("error", new AccountNotFoundException());
bldr.addSuccess("authn", new DefaultAuthenticationHandlerExecutionResult(
new AcceptUsersAuthenticationHandler(""),
new BasicCredentialMetaData(userPassCredential)));
final TicketGrantingTicket expectedTGT = new TicketGrantingTicketImpl(TGT_ID,
RegisteredServiceTestUtils.getService(),
null, bldr.build(),
new NeverExpiresExpirationPolicy());
val ticket = expectedTGT.grantServiceTicket(ST_ID,
RegisteredServiceTestUtils.getService(),
new NeverExpiresExpirationPolicy(), false, true);
val result1 = transcoder.encode(expectedTGT);
val resultTicket = transcoder.decode(result1);
assertEquals(expectedTGT, resultTicket);
val result2 = transcoder.encode(ticket);
val resultStTicket1 = transcoder.decode(result2);
assertEquals(ticket, resultStTicket1);
val resultStTicket2 = transcoder.decode(result2);
assertEquals(ticket, resultStTicket2);
}
@Test
public void verifyEncodeDecode() {
val tgt = new MockTicketGrantingTicket(USERNAME);
val expectedST = new MockServiceTicket(ST_ID, RegisteredServiceTestUtils.getService(), tgt);
assertEquals(expectedST, transcoder.decode(transcoder.encode(expectedST)));
val expectedTGT = new MockTicketGrantingTicket(USERNAME);
expectedTGT.grantServiceTicket(ST_ID, null, null, false, true);
val result = transcoder.encode(expectedTGT);
assertEquals(expectedTGT, transcoder.decode(result));
assertEquals(expectedTGT, transcoder.decode(result));
internalProxyTest();
}
private void internalProxyTest() {
val expectedTGT = new MockTicketGrantingTicket(USERNAME);
expectedTGT.grantServiceTicket(ST_ID, null, null, false, true);
val result = transcoder.encode(expectedTGT);
assertEquals(expectedTGT, transcoder.decode(result));
assertEquals(expectedTGT, transcoder.decode(result));
}
@Test
public void verifyEncodeDecodeTGTWithUnmodifiableMap() {
val userPassCredential = new UsernamePasswordCredential(USERNAME, PASSWORD);
final TicketGrantingTicket expectedTGT =
new MockTicketGrantingTicket(TGT_ID, userPassCredential, new HashMap<>(this.principalAttributes));
expectedTGT.grantServiceTicket(ST_ID, null, null, false, true);
val result = transcoder.encode(expectedTGT);
assertEquals(expectedTGT, transcoder.decode(result));
assertEquals(expectedTGT, transcoder.decode(result));
}
@Test
public void verifyEncodeDecodeTGTWithUnmodifiableList() {
val userPassCredential = new UsernamePasswordCredential(USERNAME, PASSWORD);
val values = new ArrayList<String>();
values.add(NICKNAME_VALUE);
val newAttributes = new HashMap<String, Object>();
newAttributes.put(NICKNAME_KEY, new ArrayList<>(values));
val expectedTGT = new MockTicketGrantingTicket(TGT_ID, userPassCredential, newAttributes);
expectedTGT.grantServiceTicket(ST_ID, null, null, false, true);
val result = transcoder.encode(expectedTGT);
assertEquals(expectedTGT, transcoder.decode(result));
assertEquals(expectedTGT, transcoder.decode(result));
}
@Test
public void verifyEncodeDecodeTGTWithLinkedHashMap() {
val userPassCredential = new UsernamePasswordCredential(USERNAME, PASSWORD);
final TicketGrantingTicket expectedTGT =
new MockTicketGrantingTicket(TGT_ID, userPassCredential, new LinkedHashMap<>(this.principalAttributes));
expectedTGT.grantServiceTicket(ST_ID, null, null, false, true);
val result = transcoder.encode(expectedTGT);
assertEquals(expectedTGT, transcoder.decode(result));
assertEquals(expectedTGT, transcoder.decode(result));
}
@Test
public void verifyEncodeDecodeTGTWithListOrderedMap() {
val userPassCredential = new UsernamePasswordCredential(USERNAME, PASSWORD);
final TicketGrantingTicket expectedTGT =
new MockTicketGrantingTicket(TGT_ID, userPassCredential, this.principalAttributes);
expectedTGT.grantServiceTicket(ST_ID, null, null, false, true);
val result = transcoder.encode(expectedTGT);
assertEquals(expectedTGT, transcoder.decode(result));
assertEquals(expectedTGT, transcoder.decode(result));
}
@Test
public void verifyEncodeDecodeTGTWithUnmodifiableSet() {
val newAttributes = new HashMap<String, Object>();
val values = new HashSet<String>();
values.add(NICKNAME_VALUE);
//CHECKSTYLE:OFF
newAttributes.put(NICKNAME_KEY, Collections.unmodifiableSet(values));
//CHECKSTYLE:ON
val userPassCredential = new UsernamePasswordCredential(USERNAME, PASSWORD);
val expectedTGT = new MockTicketGrantingTicket(TGT_ID, userPassCredential, newAttributes);
expectedTGT.grantServiceTicket(ST_ID, null, null, false, true);
val result = transcoder.encode(expectedTGT);
assertEquals(expectedTGT, transcoder.decode(result));
assertEquals(expectedTGT, transcoder.decode(result));
}
@Test
public void verifyEncodeDecodeTGTWithSingleton() {
val newAttributes = new HashMap<String, Object>();
newAttributes.put(NICKNAME_KEY, Collections.singleton(NICKNAME_VALUE));
val userPassCredential = new UsernamePasswordCredential(USERNAME, PASSWORD);
val expectedTGT = new MockTicketGrantingTicket(TGT_ID, userPassCredential, newAttributes);
expectedTGT.grantServiceTicket(ST_ID, null, null, false, true);
val result = transcoder.encode(expectedTGT);
assertEquals(expectedTGT, transcoder.decode(result));
assertEquals(expectedTGT, transcoder.decode(result));
}
@Test
public void verifyEncodeDecodeTGTWithSingletonMap() {
val newAttributes = Collections.<String, Object>singletonMap(NICKNAME_KEY, NICKNAME_VALUE);
val userPassCredential = new UsernamePasswordCredential(USERNAME, PASSWORD);
val expectedTGT = new MockTicketGrantingTicket(TGT_ID, userPassCredential, newAttributes);
expectedTGT.grantServiceTicket(ST_ID, null, null, false, true);
val result = transcoder.encode(expectedTGT);
assertEquals(expectedTGT, transcoder.decode(result));
assertEquals(expectedTGT, transcoder.decode(result));
}
@Test
public void verifyEncodeDecodeRegisteredService() {
val service = RegisteredServiceTestUtils.getRegisteredService("helloworld");
val result = transcoder.encode(service);
assertEquals(service, transcoder.decode(result));
assertEquals(service, transcoder.decode(result));
}
@Test
public void verifySTWithServiceTicketExpirationPolicy() {
// ServiceTicketExpirationPolicy is not registered with Kryo...
transcoder.getKryo().getClassResolver().reset();
val tgt = new MockTicketGrantingTicket(USERNAME);
val expectedST = new MockServiceTicket(ST_ID, RegisteredServiceTestUtils.getService(), tgt);
val step
= new MultiTimeUseOrTimeoutExpirationPolicy.ServiceTicketExpirationPolicy(1, 600);
expectedST.setExpiration(step);
val result = transcoder.encode(expectedST);
assertEquals(expectedST, transcoder.decode(result));
// Test it a second time - Ensure there's no problem with subsequent de-serializations.
assertEquals(expectedST, transcoder.decode(result));
}
@Test
public void verifyEncodeDecodeNonRegisteredClass() {
val tgt = new MockTicketGrantingTicket(USERNAME);
val expectedST = new MockServiceTicket(ST_ID, RegisteredServiceTestUtils.getService(), tgt);
// This class is not registered with Kryo
val step = new UnregisteredServiceTicketExpirationPolicy(1, 600);
expectedST.setExpiration(step);
try {
transcoder.encode(expectedST);
throw new AssertionError("Unregistered class is not allowed by Kryo");
} catch (final KryoException e) {
LOGGER.trace(e.getMessage(), e);
} catch (final Exception e) {
throw new AssertionError("Unexpected exception due to not resetting Kryo between de-serializations with unregistered class.");
}
}
/**
* Class for testing Kryo unregistered class handling.
*/
private static class UnregisteredServiceTicketExpirationPolicy extends MultiTimeUseOrTimeoutExpirationPolicy {
private static final long serialVersionUID = -1704993954986738308L;
/**
* Instantiates a new Service ticket expiration policy.
*
* @param numberOfUses the number of uses
* @param timeToKillInSeconds the time to kill in seconds
*/
UnregisteredServiceTicketExpirationPolicy(final int numberOfUses, final long timeToKillInSeconds) {
super(numberOfUses, timeToKillInSeconds);
}
}
}
| Java |
package org.apache.velocity.tools.view;
/*
* 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.
*/
/**
* <p>ToolInfo implementation to handle "primitive" data types.
* It currently supports String, Number, and Boolean data.</p>
*
* <p>An example of data elements specified in your toolbox.xml
* might be:
* <pre>
* <data type="string">
* <key>app_name</key>
* <value>FooWeb Deluxe</value>
* </data>
* <data type="number">
* <key>app_version</key>
* <value>4.2</value>
* </data>
* <data type="boolean">
* <key>debug</key>
* <value>true</value>
* </data>
* <data type="number">
* <key>screen_width</key>
* <value>400</value>
* </data>
* </pre></p>
*
* @author Nathan Bubna
* @deprecated Use {@link org.apache.velocity.tools.config.Data}
* @version $Id: DataInfo.java 651469 2008-04-25 00:46:13Z nbubna $
*/
@Deprecated
public class DataInfo implements ToolInfo
{
public static final String TYPE_STRING = "string";
public static final String TYPE_NUMBER = "number";
public static final String TYPE_BOOLEAN = "boolean";
private static final int TYPE_ID_STRING = 0;
private static final int TYPE_ID_NUMBER = 1;
private static final int TYPE_ID_BOOLEAN = 2;
private String key = null;
private int type_id = TYPE_ID_STRING;
private Object data = null;
public DataInfo() {}
/*********************** Mutators *************************/
public void setKey(String key)
{
this.key = key;
}
public void setType(String type)
{
if (TYPE_BOOLEAN.equalsIgnoreCase(type))
{
this.type_id = TYPE_ID_BOOLEAN;
}
else if (TYPE_NUMBER.equalsIgnoreCase(type))
{
this.type_id = TYPE_ID_NUMBER;
}
else /* if no type or type="string" */
{
this.type_id = TYPE_ID_STRING;
}
}
public void setValue(String value)
{
if (type_id == TYPE_ID_BOOLEAN)
{
this.data = Boolean.valueOf(value);
}
else if (type_id == TYPE_ID_NUMBER)
{
if (value.indexOf('.') >= 0)
{
this.data = new Double(value);
}
else
{
this.data = new Integer(value);
}
}
else /* type is "string" */
{
this.data = value;
}
}
/*********************** Accessors *************************/
public String getKey()
{
return key;
}
public String getClassname()
{
return data != null ? data.getClass().getName() : null;
}
/**
* Returns the data. Always returns the same
* object since the data is a constant. Initialization
* data is ignored.
*/
public Object getInstance(Object initData)
{
return data;
}
}
| Java |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft 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 Microsoft.Azure.Commands.Compute.Common;
using Microsoft.Azure.Commands.Compute.Models;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using Microsoft.Azure.Management.Compute;
using System;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Compute
{
[Cmdlet("Get", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "VMAccessExtension"),OutputType(typeof(VirtualMachineAccessExtensionContext))]
public class GetAzureVMAccessExtensionCommand : VirtualMachineExtensionBaseCmdlet
{
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The resource group name.")]
[ResourceGroupCompleter()]
[ValidateNotNullOrEmpty]
public string ResourceGroupName { get; set; }
[Alias("ResourceName")]
[Parameter(
Mandatory = true,
Position = 1,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The virtual machine name.")]
[ResourceNameCompleter("Microsoft.Compute/virtualMachines", "ResourceGroupName")]
[ValidateNotNullOrEmpty]
public string VMName { get; set; }
[Alias("ExtensionName")]
[Parameter(
Mandatory = true,
Position = 2,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The extension name.")]
[ResourceNameCompleter("Microsoft.Compute/virtualMachines/extensions", "ResourceGroupName", "VMName")]
[ValidateNotNullOrEmpty]
public string Name { get; set; }
[Parameter(
Position = 3,
ValueFromPipelineByPropertyName = true,
HelpMessage = "To show the status.")]
[ValidateNotNullOrEmpty]
public SwitchParameter Status { get; set; }
public override void ExecuteCmdlet()
{
base.ExecuteCmdlet();
ExecuteClientAction(() =>
{
if (Status.IsPresent)
{
var result = this.VirtualMachineExtensionClient.GetWithInstanceView(this.ResourceGroupName, this.VMName, this.Name);
var returnedExtension = result.ToPSVirtualMachineExtension(this.ResourceGroupName, this.VMName);
if (returnedExtension.Publisher.Equals(VirtualMachineAccessExtensionContext.ExtensionDefaultPublisher, StringComparison.InvariantCultureIgnoreCase) &&
returnedExtension.ExtensionType.Equals(VirtualMachineAccessExtensionContext.ExtensionDefaultName, StringComparison.InvariantCultureIgnoreCase))
{
WriteObject(new VirtualMachineAccessExtensionContext(returnedExtension));
}
else
{
WriteObject(null);
}
}
else
{
var result = this.VirtualMachineExtensionClient.Get(this.ResourceGroupName, this.VMName, this.Name);
var returnedExtension = result.ToPSVirtualMachineExtension(this.ResourceGroupName, this.VMName);
if (returnedExtension.Publisher.Equals(VirtualMachineAccessExtensionContext.ExtensionDefaultPublisher, StringComparison.InvariantCultureIgnoreCase) &&
returnedExtension.ExtensionType.Equals(VirtualMachineAccessExtensionContext.ExtensionDefaultName, StringComparison.InvariantCultureIgnoreCase))
{
WriteObject(new VirtualMachineAccessExtensionContext(returnedExtension));
}
else
{
WriteObject(null);
}
}
});
}
}
}
| Java |
/*
* Licensed to Diennea S.r.l. under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Diennea S.r.l. 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 docet.engine;
import java.util.Arrays;
/**
*
*
*/
public enum DocetDocFormat {
TYPE_HTML("html", false),
TYPE_PDF("pdf", true);
private String name;
private boolean includeResources;
private DocetDocFormat(final String name, final boolean includeResources) {
this.name = name;
this.includeResources = includeResources;
}
@Override
public String toString() {
return this.name;
}
public boolean isIncludeResources() {
return this.includeResources;
}
public static DocetDocFormat parseDocetRequestByName(final String name) {
return Arrays.asList(DocetDocFormat.values())
.stream()
.filter(req -> req.toString().equals(name)).findFirst().orElse(null);
}
} | Java |
FROM biocontainers/biocontainers:vdebian-buster-backports_cv1
MAINTAINER biocontainers <[email protected]>
LABEL software="pbalign" \
base_image="biocontainers/biocontainers:vdebian-buster-backports_cv1" \
container="pbalign" \
about.summary="map Pacific Biosciences reads to reference DNA sequences (Python2)" \
about.home="https://github.com/PacificBiosciences/pbalign" \
software.version="0.3.2-1-deb-py2" \
upstream.version="0.3.2" \
version="1" \
about.copyright="2011-2014 Pacific Biosciences of California, Inc." \
about.license="PacBio-BSD-3-Clause" \
about.license_file="/usr/share/doc/pbalign/copyright" \
about.tags=""
USER root
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update && (apt-get install -t buster-backports -y python-pbalign || apt-get install -y python-pbalign) && apt-get clean && apt-get purge && rm -rf /var/lib/apt/lists/* /tmp/*
USER biodocker
| 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.coyote.http2;
import java.util.logging.Level;
import java.util.logging.LogManager;
import org.junit.Assert;
import org.junit.Test;
/**
* Unit tests for Section 6.1 of
* <a href="https://tools.ietf.org/html/rfc7540">RFC 7540</a>.
* <br>
* The order of tests in this class is aligned with the order of the
* requirements in the RFC.
*/
public class TestHttp2Section_6_1 extends Http2TestBase {
@Test
public void testDataFrame() throws Exception {
http2Connect();
// Disable overhead protection for window update as it breaks the test
http2Protocol.setOverheadWindowUpdateThreshold(0);
sendSimplePostRequest(3, null);
readSimplePostResponse(false);
Assert.assertEquals("0-WindowSize-[128]\n" +
"3-WindowSize-[128]\n" +
"3-HeadersStart\n" +
"3-Header-[:status]-[200]\n" +
"3-Header-[content-length]-[128]\n" +
"3-Header-[date]-[Wed, 11 Nov 2015 19:18:42 GMT]\n" +
"3-HeadersEnd\n" +
"3-Body-128\n" +
"3-EndOfStream\n", output.getTrace());
}
@Test
public void testDataFrameWithPadding() throws Exception {
LogManager.getLogManager().getLogger("org.apache.coyote").setLevel(Level.ALL);
LogManager.getLogManager().getLogger("org.apache.tomcat.util.net").setLevel(Level.ALL);
try {
http2Connect();
// Disable overhead protection for window update as it breaks the
// test
http2Protocol.setOverheadWindowUpdateThreshold(0);
byte[] padding = new byte[8];
sendSimplePostRequest(3, padding);
readSimplePostResponse(true);
// The window updates for padding could occur anywhere since they
// happen on a different thread to the response.
// The connection window update is always present if there is
// padding.
String trace = output.getTrace();
String paddingWindowUpdate = "0-WindowSize-[9]\n";
Assert.assertTrue(trace, trace.contains(paddingWindowUpdate));
trace = trace.replace(paddingWindowUpdate, "");
// The stream window update may or may not be present depending on
// timing. Remove it if present.
if (trace.contains("3-WindowSize-[9]\n")) {
trace = trace.replace("3-WindowSize-[9]\n", "");
}
Assert.assertEquals("0-WindowSize-[119]\n" +
"3-WindowSize-[119]\n" +
"3-HeadersStart\n" +
"3-Header-[:status]-[200]\n" +
"3-Header-[content-length]-[119]\n" +
"3-Header-[date]-[Wed, 11 Nov 2015 19:18:42 GMT]\n" +
"3-HeadersEnd\n" +
"3-Body-119\n" +
"3-EndOfStream\n", trace);
} finally {
LogManager.getLogManager().getLogger("org.apache.coyote").setLevel(Level.INFO);
LogManager.getLogManager().getLogger("org.apache.tomcat.util.net").setLevel(Level.INFO);
}
}
@Test
public void testDataFrameWithNonZeroPadding() throws Exception {
http2Connect();
byte[] padding = new byte[8];
padding[4] = 0x01;
sendSimplePostRequest(3, padding);
// May see Window updates depending on timing
skipWindowSizeFrames();
String trace = output.getTrace();
Assert.assertTrue(trace, trace.startsWith("0-Goaway-[3]-[1]-["));
}
@Test
public void testDataFrameOnStreamZero() throws Exception {
http2Connect();
byte[] dataFrame = new byte[10];
// Header
// length
ByteUtil.setThreeBytes(dataFrame, 0, 1);
// type (0 for data)
// flags (0)
// stream (0)
// payload (0)
os.write(dataFrame);
os.flush();
handleGoAwayResponse(1);
}
@Test
public void testDataFrameTooMuchPadding() throws Exception {
http2Connect();
byte[] dataFrame = new byte[10];
// Header
// length
ByteUtil.setThreeBytes(dataFrame, 0, 1);
// type 0 (data)
// flags 8 (padded)
dataFrame[4] = 0x08;
// stream 3
ByteUtil.set31Bits(dataFrame, 5, 3);
// payload (pad length of 1)
dataFrame[9] = 1;
os.write(dataFrame);
os.flush();
handleGoAwayResponse(1);
}
@Test
public void testDataFrameWithZeroLengthPadding() throws Exception {
http2Connect();
// Disable overhead protection for window update as it breaks the test
http2Protocol.setOverheadWindowUpdateThreshold(0);
byte[] padding = new byte[0];
sendSimplePostRequest(3, padding);
readSimplePostResponse(true);
// The window updates for padding could occur anywhere since they
// happen on a different thread to the response.
// The connection window update is always present if there is
// padding.
String trace = output.getTrace();
String paddingWindowUpdate = "0-WindowSize-[1]\n";
Assert.assertTrue(trace, trace.contains(paddingWindowUpdate));
trace = trace.replace(paddingWindowUpdate, "");
// The stream window update may or may not be present depending on
// timing. Remove it if present.
paddingWindowUpdate = "3-WindowSize-[1]\n";
if (trace.contains(paddingWindowUpdate)) {
trace = trace.replace(paddingWindowUpdate, "");
}
Assert.assertEquals("0-WindowSize-[127]\n" +
"3-WindowSize-[127]\n" +
"3-HeadersStart\n" +
"3-Header-[:status]-[200]\n" +
"3-Header-[content-length]-[127]\n" +
"3-Header-[date]-[Wed, 11 Nov 2015 19:18:42 GMT]\n" +
"3-HeadersEnd\n" +
"3-Body-127\n" +
"3-EndOfStream\n", trace);
}
}
| Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>TestReversibleScanners xref</title>
<link type="text/css" rel="stylesheet" href="../../../../../stylesheet.css" />
</head>
<body>
<div id="overview"><a href="../../../../../../testapidocs/org/apache/hadoop/hbase/regionserver/TestReversibleScanners.html">View Javadoc</a></div><pre>
<a class="jxr_linenumber" name="1" href="#1">1</a> <em class="jxr_javadoccomment">/**</em>
<a class="jxr_linenumber" name="2" href="#2">2</a> <em class="jxr_javadoccomment"> * Copyright The Apache Software Foundation</em>
<a class="jxr_linenumber" name="3" href="#3">3</a> <em class="jxr_javadoccomment"> *</em>
<a class="jxr_linenumber" name="4" href="#4">4</a> <em class="jxr_javadoccomment"> * Licensed to the Apache Software Foundation (ASF) under one or more</em>
<a class="jxr_linenumber" name="5" href="#5">5</a> <em class="jxr_javadoccomment"> * contributor license agreements. See the NOTICE file distributed with this</em>
<a class="jxr_linenumber" name="6" href="#6">6</a> <em class="jxr_javadoccomment"> * work for additional information regarding copyright ownership. The ASF</em>
<a class="jxr_linenumber" name="7" href="#7">7</a> <em class="jxr_javadoccomment"> * licenses this file to you under the Apache License, Version 2.0 (the</em>
<a class="jxr_linenumber" name="8" href="#8">8</a> <em class="jxr_javadoccomment"> * "License"); you may not use this file except in compliance with the License.</em>
<a class="jxr_linenumber" name="9" href="#9">9</a> <em class="jxr_javadoccomment"> * You may obtain a copy of the License at</em>
<a class="jxr_linenumber" name="10" href="#10">10</a> <em class="jxr_javadoccomment"> *</em>
<a class="jxr_linenumber" name="11" href="#11">11</a> <em class="jxr_javadoccomment"> * <a href="http://www.apache.org/licenses/LICENSE-2.0" target="alexandria_uri">http://www.apache.org/licenses/LICENSE-2.0</a></em>
<a class="jxr_linenumber" name="12" href="#12">12</a> <em class="jxr_javadoccomment"> *</em>
<a class="jxr_linenumber" name="13" href="#13">13</a> <em class="jxr_javadoccomment"> * Unless required by applicable law or agreed to in writing, software</em>
<a class="jxr_linenumber" name="14" href="#14">14</a> <em class="jxr_javadoccomment"> * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT</em>
<a class="jxr_linenumber" name="15" href="#15">15</a> <em class="jxr_javadoccomment"> * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the</em>
<a class="jxr_linenumber" name="16" href="#16">16</a> <em class="jxr_javadoccomment"> * License for the specific language governing permissions and limitations</em>
<a class="jxr_linenumber" name="17" href="#17">17</a> <em class="jxr_javadoccomment"> * under the License.</em>
<a class="jxr_linenumber" name="18" href="#18">18</a> <em class="jxr_javadoccomment"> */</em>
<a class="jxr_linenumber" name="19" href="#19">19</a> <strong class="jxr_keyword">package</strong> org.apache.hadoop.hbase.regionserver;
<a class="jxr_linenumber" name="20" href="#20">20</a>
<a class="jxr_linenumber" name="21" href="#21">21</a> <strong class="jxr_keyword">import</strong> <strong class="jxr_keyword">static</strong> org.junit.Assert.assertEquals;
<a class="jxr_linenumber" name="22" href="#22">22</a> <strong class="jxr_keyword">import</strong> <strong class="jxr_keyword">static</strong> org.junit.Assert.assertFalse;
<a class="jxr_linenumber" name="23" href="#23">23</a> <strong class="jxr_keyword">import</strong> <strong class="jxr_keyword">static</strong> org.junit.Assert.assertTrue;
<a class="jxr_linenumber" name="24" href="#24">24</a>
<a class="jxr_linenumber" name="25" href="#25">25</a> <strong class="jxr_keyword">import</strong> java.io.IOException;
<a class="jxr_linenumber" name="26" href="#26">26</a> <strong class="jxr_keyword">import</strong> java.util.ArrayList;
<a class="jxr_linenumber" name="27" href="#27">27</a> <strong class="jxr_keyword">import</strong> java.util.Collections;
<a class="jxr_linenumber" name="28" href="#28">28</a> <strong class="jxr_keyword">import</strong> java.util.List;
<a class="jxr_linenumber" name="29" href="#29">29</a> <strong class="jxr_keyword">import</strong> java.util.Map;
<a class="jxr_linenumber" name="30" href="#30">30</a> <strong class="jxr_keyword">import</strong> java.util.NavigableSet;
<a class="jxr_linenumber" name="31" href="#31">31</a> <strong class="jxr_keyword">import</strong> java.util.Random;
<a class="jxr_linenumber" name="32" href="#32">32</a>
<a class="jxr_linenumber" name="33" href="#33">33</a> <strong class="jxr_keyword">import</strong> org.apache.commons.logging.Log;
<a class="jxr_linenumber" name="34" href="#34">34</a> <strong class="jxr_keyword">import</strong> org.apache.commons.logging.LogFactory;
<a class="jxr_linenumber" name="35" href="#35">35</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.conf.Configuration;
<a class="jxr_linenumber" name="36" href="#36">36</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.fs.FileSystem;
<a class="jxr_linenumber" name="37" href="#37">37</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.fs.Path;
<a class="jxr_linenumber" name="38" href="#38">38</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.hbase.Cell;
<a class="jxr_linenumber" name="39" href="#39">39</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.hbase.HBaseConfiguration;
<a class="jxr_linenumber" name="40" href="#40">40</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.hbase.HBaseTestingUtility;
<a class="jxr_linenumber" name="41" href="#41">41</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.hbase.HConstants;
<a class="jxr_linenumber" name="42" href="#42">42</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.hbase.KeyValue;
<a class="jxr_linenumber" name="43" href="#43">43</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.hbase.MediumTests;
<a class="jxr_linenumber" name="44" href="#44">44</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.hbase.client.Durability;
<a class="jxr_linenumber" name="45" href="#45">45</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.hbase.client.Put;
<a class="jxr_linenumber" name="46" href="#46">46</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.hbase.client.Result;
<a class="jxr_linenumber" name="47" href="#47">47</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.hbase.client.Scan;
<a class="jxr_linenumber" name="48" href="#48">48</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
<a class="jxr_linenumber" name="49" href="#49">49</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.hbase.filter.Filter;
<a class="jxr_linenumber" name="50" href="#50">50</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.hbase.filter.FilterList;
<a class="jxr_linenumber" name="51" href="#51">51</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.hbase.filter.FilterList.Operator;
<a class="jxr_linenumber" name="52" href="#52">52</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.hbase.filter.PageFilter;
<a class="jxr_linenumber" name="53" href="#53">53</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.hbase.filter.SingleColumnValueFilter;
<a class="jxr_linenumber" name="54" href="#54">54</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.hbase.io.encoding.DataBlockEncoding;
<a class="jxr_linenumber" name="55" href="#55">55</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.hbase.io.hfile.CacheConfig;
<a class="jxr_linenumber" name="56" href="#56">56</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.hbase.io.hfile.HFileContext;
<a class="jxr_linenumber" name="57" href="#57">57</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.hbase.io.hfile.HFileContextBuilder;
<a class="jxr_linenumber" name="58" href="#58">58</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.hbase.util.Bytes;
<a class="jxr_linenumber" name="59" href="#59">59</a> <strong class="jxr_keyword">import</strong> org.apache.hadoop.hbase.util.Pair;
<a class="jxr_linenumber" name="60" href="#60">60</a> <strong class="jxr_keyword">import</strong> org.junit.Test;
<a class="jxr_linenumber" name="61" href="#61">61</a> <strong class="jxr_keyword">import</strong> org.junit.experimental.categories.Category;
<a class="jxr_linenumber" name="62" href="#62">62</a>
<a class="jxr_linenumber" name="63" href="#63">63</a> <strong class="jxr_keyword">import</strong> com.google.common.collect.Lists;
<a class="jxr_linenumber" name="64" href="#64">64</a> <em class="jxr_javadoccomment">/**</em>
<a class="jxr_linenumber" name="65" href="#65">65</a> <em class="jxr_javadoccomment"> * Test cases against ReversibleKeyValueScanner</em>
<a class="jxr_linenumber" name="66" href="#66">66</a> <em class="jxr_javadoccomment"> */</em>
<a class="jxr_linenumber" name="67" href="#67">67</a> @Category(MediumTests.<strong class="jxr_keyword">class</strong>)
<a class="jxr_linenumber" name="68" href="#68">68</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">class</strong> <a href="../../../../../org/apache/hadoop/hbase/regionserver/TestReversibleScanners.html">TestReversibleScanners</a> {
<a class="jxr_linenumber" name="69" href="#69">69</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">static</strong> <strong class="jxr_keyword">final</strong> Log LOG = LogFactory.getLog(TestReversibleScanners.<strong class="jxr_keyword">class</strong>);
<a class="jxr_linenumber" name="70" href="#70">70</a> <a href="../../../../../org/apache/hadoop/hbase/HBaseTestingUtility.html">HBaseTestingUtility</a> TEST_UTIL = <strong class="jxr_keyword">new</strong> <a href="../../../../../org/apache/hadoop/hbase/HBaseTestingUtility.html">HBaseTestingUtility</a>();
<a class="jxr_linenumber" name="71" href="#71">71</a>
<a class="jxr_linenumber" name="72" href="#72">72</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">static</strong> byte[] FAMILYNAME = Bytes.toBytes(<span class="jxr_string">"testCf"</span>);
<a class="jxr_linenumber" name="73" href="#73">73</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">static</strong> <strong class="jxr_keyword">long</strong> TS = System.currentTimeMillis();
<a class="jxr_linenumber" name="74" href="#74">74</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">static</strong> <strong class="jxr_keyword">int</strong> MAXMVCC = 7;
<a class="jxr_linenumber" name="75" href="#75">75</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">static</strong> byte[] ROW = Bytes.toBytes(<span class="jxr_string">"testRow"</span>);
<a class="jxr_linenumber" name="76" href="#76">76</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">static</strong> <strong class="jxr_keyword">final</strong> <strong class="jxr_keyword">int</strong> ROWSIZE = 200;
<a class="jxr_linenumber" name="77" href="#77">77</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">static</strong> byte[][] ROWS = makeN(ROW, ROWSIZE);
<a class="jxr_linenumber" name="78" href="#78">78</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">static</strong> byte[] QUAL = Bytes.toBytes(<span class="jxr_string">"testQual"</span>);
<a class="jxr_linenumber" name="79" href="#79">79</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">static</strong> <strong class="jxr_keyword">final</strong> <strong class="jxr_keyword">int</strong> QUALSIZE = 5;
<a class="jxr_linenumber" name="80" href="#80">80</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">static</strong> byte[][] QUALS = makeN(QUAL, QUALSIZE);
<a class="jxr_linenumber" name="81" href="#81">81</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">static</strong> byte[] VALUE = Bytes.toBytes(<span class="jxr_string">"testValue"</span>);
<a class="jxr_linenumber" name="82" href="#82">82</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">static</strong> <strong class="jxr_keyword">final</strong> <strong class="jxr_keyword">int</strong> VALUESIZE = 3;
<a class="jxr_linenumber" name="83" href="#83">83</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">static</strong> byte[][] VALUES = makeN(VALUE, VALUESIZE);
<a class="jxr_linenumber" name="84" href="#84">84</a>
<a class="jxr_linenumber" name="85" href="#85">85</a> @Test
<a class="jxr_linenumber" name="86" href="#86">86</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> testReversibleStoreFileScanner() <strong class="jxr_keyword">throws</strong> IOException {
<a class="jxr_linenumber" name="87" href="#87">87</a> FileSystem fs = TEST_UTIL.getTestFileSystem();
<a class="jxr_linenumber" name="88" href="#88">88</a> Path hfilePath = <strong class="jxr_keyword">new</strong> Path(<strong class="jxr_keyword">new</strong> Path(
<a class="jxr_linenumber" name="89" href="#89">89</a> TEST_UTIL.getDataTestDir(<span class="jxr_string">"testReversibleStoreFileScanner"</span>),
<a class="jxr_linenumber" name="90" href="#90">90</a> <span class="jxr_string">"regionname"</span>), <span class="jxr_string">"familyname"</span>);
<a class="jxr_linenumber" name="91" href="#91">91</a> CacheConfig cacheConf = <strong class="jxr_keyword">new</strong> CacheConfig(TEST_UTIL.getConfiguration());
<a class="jxr_linenumber" name="92" href="#92">92</a> <strong class="jxr_keyword">for</strong> (DataBlockEncoding encoding : DataBlockEncoding.values()) {
<a class="jxr_linenumber" name="93" href="#93">93</a> HFileContextBuilder hcBuilder = <strong class="jxr_keyword">new</strong> HFileContextBuilder();
<a class="jxr_linenumber" name="94" href="#94">94</a> hcBuilder.withBlockSize(2 * 1024);
<a class="jxr_linenumber" name="95" href="#95">95</a> hcBuilder.withDataBlockEncoding(encoding);
<a class="jxr_linenumber" name="96" href="#96">96</a> HFileContext hFileContext = hcBuilder.build();
<a class="jxr_linenumber" name="97" href="#97">97</a> StoreFile.Writer writer = <strong class="jxr_keyword">new</strong> StoreFile.WriterBuilder(
<a class="jxr_linenumber" name="98" href="#98">98</a> TEST_UTIL.getConfiguration(), cacheConf, fs).withOutputDir(hfilePath)
<a class="jxr_linenumber" name="99" href="#99">99</a> .withFileContext(hFileContext).build();
<a class="jxr_linenumber" name="100" href="#100">100</a> writeStoreFile(writer);
<a class="jxr_linenumber" name="101" href="#101">101</a>
<a class="jxr_linenumber" name="102" href="#102">102</a> StoreFile sf = <strong class="jxr_keyword">new</strong> StoreFile(fs, writer.getPath(),
<a class="jxr_linenumber" name="103" href="#103">103</a> TEST_UTIL.getConfiguration(), cacheConf, BloomType.NONE);
<a class="jxr_linenumber" name="104" href="#104">104</a>
<a class="jxr_linenumber" name="105" href="#105">105</a> List<StoreFileScanner> scanners = StoreFileScanner
<a class="jxr_linenumber" name="106" href="#106">106</a> .getScannersForStoreFiles(Collections.singletonList(sf), false, <strong class="jxr_keyword">true</strong>,
<a class="jxr_linenumber" name="107" href="#107">107</a> false, Long.MAX_VALUE);
<a class="jxr_linenumber" name="108" href="#108">108</a> StoreFileScanner scanner = scanners.get(0);
<a class="jxr_linenumber" name="109" href="#109">109</a> seekTestOfReversibleKeyValueScanner(scanner);
<a class="jxr_linenumber" name="110" href="#110">110</a> <strong class="jxr_keyword">for</strong> (<strong class="jxr_keyword">int</strong> readPoint = 0; readPoint < MAXMVCC; readPoint++) {
<a class="jxr_linenumber" name="111" href="#111">111</a> LOG.info(<span class="jxr_string">"Setting read point to "</span> + readPoint);
<a class="jxr_linenumber" name="112" href="#112">112</a> scanners = StoreFileScanner.getScannersForStoreFiles(
<a class="jxr_linenumber" name="113" href="#113">113</a> Collections.singletonList(sf), false, <strong class="jxr_keyword">true</strong>, false, readPoint);
<a class="jxr_linenumber" name="114" href="#114">114</a> seekTestOfReversibleKeyValueScannerWithMVCC(scanners.get(0), readPoint);
<a class="jxr_linenumber" name="115" href="#115">115</a> }
<a class="jxr_linenumber" name="116" href="#116">116</a> }
<a class="jxr_linenumber" name="117" href="#117">117</a>
<a class="jxr_linenumber" name="118" href="#118">118</a> }
<a class="jxr_linenumber" name="119" href="#119">119</a>
<a class="jxr_linenumber" name="120" href="#120">120</a> @Test
<a class="jxr_linenumber" name="121" href="#121">121</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> testReversibleMemstoreScanner() <strong class="jxr_keyword">throws</strong> IOException {
<a class="jxr_linenumber" name="122" href="#122">122</a> MemStore memstore = <strong class="jxr_keyword">new</strong> MemStore();
<a class="jxr_linenumber" name="123" href="#123">123</a> writeMemstore(memstore);
<a class="jxr_linenumber" name="124" href="#124">124</a> List<KeyValueScanner> scanners = memstore.getScanners(Long.MAX_VALUE);
<a class="jxr_linenumber" name="125" href="#125">125</a> seekTestOfReversibleKeyValueScanner(scanners.get(0));
<a class="jxr_linenumber" name="126" href="#126">126</a> <strong class="jxr_keyword">for</strong> (<strong class="jxr_keyword">int</strong> readPoint = 0; readPoint < MAXMVCC; readPoint++) {
<a class="jxr_linenumber" name="127" href="#127">127</a> LOG.info(<span class="jxr_string">"Setting read point to "</span> + readPoint);
<a class="jxr_linenumber" name="128" href="#128">128</a> scanners = memstore.getScanners(readPoint);
<a class="jxr_linenumber" name="129" href="#129">129</a> seekTestOfReversibleKeyValueScannerWithMVCC(scanners.get(0), readPoint);
<a class="jxr_linenumber" name="130" href="#130">130</a> }
<a class="jxr_linenumber" name="131" href="#131">131</a>
<a class="jxr_linenumber" name="132" href="#132">132</a> }
<a class="jxr_linenumber" name="133" href="#133">133</a>
<a class="jxr_linenumber" name="134" href="#134">134</a> @Test
<a class="jxr_linenumber" name="135" href="#135">135</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> testReversibleKeyValueHeap() <strong class="jxr_keyword">throws</strong> IOException {
<a class="jxr_linenumber" name="136" href="#136">136</a> <em class="jxr_comment">// write data to one memstore and two store files</em>
<a class="jxr_linenumber" name="137" href="#137">137</a> FileSystem fs = TEST_UTIL.getTestFileSystem();
<a class="jxr_linenumber" name="138" href="#138">138</a> Path hfilePath = <strong class="jxr_keyword">new</strong> Path(<strong class="jxr_keyword">new</strong> Path(
<a class="jxr_linenumber" name="139" href="#139">139</a> TEST_UTIL.getDataTestDir(<span class="jxr_string">"testReversibleKeyValueHeap"</span>), <span class="jxr_string">"regionname"</span>),
<a class="jxr_linenumber" name="140" href="#140">140</a> <span class="jxr_string">"familyname"</span>);
<a class="jxr_linenumber" name="141" href="#141">141</a> CacheConfig cacheConf = <strong class="jxr_keyword">new</strong> CacheConfig(TEST_UTIL.getConfiguration());
<a class="jxr_linenumber" name="142" href="#142">142</a> HFileContextBuilder hcBuilder = <strong class="jxr_keyword">new</strong> HFileContextBuilder();
<a class="jxr_linenumber" name="143" href="#143">143</a> hcBuilder.withBlockSize(2 * 1024);
<a class="jxr_linenumber" name="144" href="#144">144</a> HFileContext hFileContext = hcBuilder.build();
<a class="jxr_linenumber" name="145" href="#145">145</a> StoreFile.Writer writer1 = <strong class="jxr_keyword">new</strong> StoreFile.WriterBuilder(
<a class="jxr_linenumber" name="146" href="#146">146</a> TEST_UTIL.getConfiguration(), cacheConf, fs).withOutputDir(
<a class="jxr_linenumber" name="147" href="#147">147</a> hfilePath).withFileContext(hFileContext).build();
<a class="jxr_linenumber" name="148" href="#148">148</a> StoreFile.Writer writer2 = <strong class="jxr_keyword">new</strong> StoreFile.WriterBuilder(
<a class="jxr_linenumber" name="149" href="#149">149</a> TEST_UTIL.getConfiguration(), cacheConf, fs).withOutputDir(
<a class="jxr_linenumber" name="150" href="#150">150</a> hfilePath).withFileContext(hFileContext).build();
<a class="jxr_linenumber" name="151" href="#151">151</a>
<a class="jxr_linenumber" name="152" href="#152">152</a> MemStore memstore = <strong class="jxr_keyword">new</strong> MemStore();
<a class="jxr_linenumber" name="153" href="#153">153</a> writeMemstoreAndStoreFiles(memstore, <strong class="jxr_keyword">new</strong> StoreFile.Writer[] { writer1,
<a class="jxr_linenumber" name="154" href="#154">154</a> writer2 });
<a class="jxr_linenumber" name="155" href="#155">155</a>
<a class="jxr_linenumber" name="156" href="#156">156</a> StoreFile sf1 = <strong class="jxr_keyword">new</strong> StoreFile(fs, writer1.getPath(),
<a class="jxr_linenumber" name="157" href="#157">157</a> TEST_UTIL.getConfiguration(), cacheConf, BloomType.NONE);
<a class="jxr_linenumber" name="158" href="#158">158</a>
<a class="jxr_linenumber" name="159" href="#159">159</a> StoreFile sf2 = <strong class="jxr_keyword">new</strong> StoreFile(fs, writer2.getPath(),
<a class="jxr_linenumber" name="160" href="#160">160</a> TEST_UTIL.getConfiguration(), cacheConf, BloomType.NONE);
<a class="jxr_linenumber" name="161" href="#161">161</a> <em class="jxr_javadoccomment">/**</em>
<a class="jxr_linenumber" name="162" href="#162">162</a> <em class="jxr_javadoccomment"> * Test without MVCC</em>
<a class="jxr_linenumber" name="163" href="#163">163</a> <em class="jxr_javadoccomment"> */</em>
<a class="jxr_linenumber" name="164" href="#164">164</a> <strong class="jxr_keyword">int</strong> startRowNum = ROWSIZE / 2;
<a class="jxr_linenumber" name="165" href="#165">165</a> ReversedKeyValueHeap kvHeap = getReversibleKeyValueHeap(memstore, sf1, sf2,
<a class="jxr_linenumber" name="166" href="#166">166</a> ROWS[startRowNum], MAXMVCC);
<a class="jxr_linenumber" name="167" href="#167">167</a> internalTestSeekAndNextForReversibleKeyValueHeap(kvHeap, startRowNum);
<a class="jxr_linenumber" name="168" href="#168">168</a>
<a class="jxr_linenumber" name="169" href="#169">169</a> startRowNum = ROWSIZE - 1;
<a class="jxr_linenumber" name="170" href="#170">170</a> kvHeap = getReversibleKeyValueHeap(memstore, sf1, sf2,
<a class="jxr_linenumber" name="171" href="#171">171</a> HConstants.EMPTY_START_ROW, MAXMVCC);
<a class="jxr_linenumber" name="172" href="#172">172</a> internalTestSeekAndNextForReversibleKeyValueHeap(kvHeap, startRowNum);
<a class="jxr_linenumber" name="173" href="#173">173</a>
<a class="jxr_linenumber" name="174" href="#174">174</a> <em class="jxr_javadoccomment">/**</em>
<a class="jxr_linenumber" name="175" href="#175">175</a> <em class="jxr_javadoccomment"> * Test with MVCC</em>
<a class="jxr_linenumber" name="176" href="#176">176</a> <em class="jxr_javadoccomment"> */</em>
<a class="jxr_linenumber" name="177" href="#177">177</a> <strong class="jxr_keyword">for</strong> (<strong class="jxr_keyword">int</strong> readPoint = 0; readPoint < MAXMVCC; readPoint++) {
<a class="jxr_linenumber" name="178" href="#178">178</a> LOG.info(<span class="jxr_string">"Setting read point to "</span> + readPoint);
<a class="jxr_linenumber" name="179" href="#179">179</a> startRowNum = ROWSIZE - 1;
<a class="jxr_linenumber" name="180" href="#180">180</a> kvHeap = getReversibleKeyValueHeap(memstore, sf1, sf2,
<a class="jxr_linenumber" name="181" href="#181">181</a> HConstants.EMPTY_START_ROW, readPoint);
<a class="jxr_linenumber" name="182" href="#182">182</a> <strong class="jxr_keyword">for</strong> (<strong class="jxr_keyword">int</strong> i = startRowNum; i >= 0; i--) {
<a class="jxr_linenumber" name="183" href="#183">183</a> <strong class="jxr_keyword">if</strong> (i - 2 < 0) <strong class="jxr_keyword">break</strong>;
<a class="jxr_linenumber" name="184" href="#184">184</a> i = i - 2;
<a class="jxr_linenumber" name="185" href="#185">185</a> kvHeap.seekToPreviousRow(KeyValue.createFirstOnRow(ROWS[i + 1]));
<a class="jxr_linenumber" name="186" href="#186">186</a> Pair<Integer, Integer> nextReadableNum = getNextReadableNumWithBackwardScan(
<a class="jxr_linenumber" name="187" href="#187">187</a> i, 0, readPoint);
<a class="jxr_linenumber" name="188" href="#188">188</a> <strong class="jxr_keyword">if</strong> (nextReadableNum == <strong class="jxr_keyword">null</strong>) <strong class="jxr_keyword">break</strong>;
<a class="jxr_linenumber" name="189" href="#189">189</a> KeyValue expecedKey = makeKV(nextReadableNum.getFirst(),
<a class="jxr_linenumber" name="190" href="#190">190</a> nextReadableNum.getSecond());
<a class="jxr_linenumber" name="191" href="#191">191</a> assertEquals(expecedKey, kvHeap.peek());
<a class="jxr_linenumber" name="192" href="#192">192</a> i = nextReadableNum.getFirst();
<a class="jxr_linenumber" name="193" href="#193">193</a> <strong class="jxr_keyword">int</strong> qualNum = nextReadableNum.getSecond();
<a class="jxr_linenumber" name="194" href="#194">194</a> <strong class="jxr_keyword">if</strong> (qualNum + 1 < QUALSIZE) {
<a class="jxr_linenumber" name="195" href="#195">195</a> kvHeap.backwardSeek(makeKV(i, qualNum + 1));
<a class="jxr_linenumber" name="196" href="#196">196</a> nextReadableNum = getNextReadableNumWithBackwardScan(i, qualNum + 1,
<a class="jxr_linenumber" name="197" href="#197">197</a> readPoint);
<a class="jxr_linenumber" name="198" href="#198">198</a> <strong class="jxr_keyword">if</strong> (nextReadableNum == <strong class="jxr_keyword">null</strong>) <strong class="jxr_keyword">break</strong>;
<a class="jxr_linenumber" name="199" href="#199">199</a> expecedKey = makeKV(nextReadableNum.getFirst(),
<a class="jxr_linenumber" name="200" href="#200">200</a> nextReadableNum.getSecond());
<a class="jxr_linenumber" name="201" href="#201">201</a> assertEquals(expecedKey, kvHeap.peek());
<a class="jxr_linenumber" name="202" href="#202">202</a> i = nextReadableNum.getFirst();
<a class="jxr_linenumber" name="203" href="#203">203</a> qualNum = nextReadableNum.getSecond();
<a class="jxr_linenumber" name="204" href="#204">204</a> }
<a class="jxr_linenumber" name="205" href="#205">205</a>
<a class="jxr_linenumber" name="206" href="#206">206</a> kvHeap.next();
<a class="jxr_linenumber" name="207" href="#207">207</a>
<a class="jxr_linenumber" name="208" href="#208">208</a> <strong class="jxr_keyword">if</strong> (qualNum + 1 >= QUALSIZE) {
<a class="jxr_linenumber" name="209" href="#209">209</a> nextReadableNum = getNextReadableNumWithBackwardScan(i - 1, 0,
<a class="jxr_linenumber" name="210" href="#210">210</a> readPoint);
<a class="jxr_linenumber" name="211" href="#211">211</a> } <strong class="jxr_keyword">else</strong> {
<a class="jxr_linenumber" name="212" href="#212">212</a> nextReadableNum = getNextReadableNumWithBackwardScan(i, qualNum + 1,
<a class="jxr_linenumber" name="213" href="#213">213</a> readPoint);
<a class="jxr_linenumber" name="214" href="#214">214</a> }
<a class="jxr_linenumber" name="215" href="#215">215</a> <strong class="jxr_keyword">if</strong> (nextReadableNum == <strong class="jxr_keyword">null</strong>) <strong class="jxr_keyword">break</strong>;
<a class="jxr_linenumber" name="216" href="#216">216</a> expecedKey = makeKV(nextReadableNum.getFirst(),
<a class="jxr_linenumber" name="217" href="#217">217</a> nextReadableNum.getSecond());
<a class="jxr_linenumber" name="218" href="#218">218</a> assertEquals(expecedKey, kvHeap.peek());
<a class="jxr_linenumber" name="219" href="#219">219</a> i = nextReadableNum.getFirst();
<a class="jxr_linenumber" name="220" href="#220">220</a> }
<a class="jxr_linenumber" name="221" href="#221">221</a> }
<a class="jxr_linenumber" name="222" href="#222">222</a> }
<a class="jxr_linenumber" name="223" href="#223">223</a>
<a class="jxr_linenumber" name="224" href="#224">224</a> @Test
<a class="jxr_linenumber" name="225" href="#225">225</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> testReversibleStoreScanner() <strong class="jxr_keyword">throws</strong> IOException {
<a class="jxr_linenumber" name="226" href="#226">226</a> <em class="jxr_comment">// write data to one memstore and two store files</em>
<a class="jxr_linenumber" name="227" href="#227">227</a> FileSystem fs = TEST_UTIL.getTestFileSystem();
<a class="jxr_linenumber" name="228" href="#228">228</a> Path hfilePath = <strong class="jxr_keyword">new</strong> Path(<strong class="jxr_keyword">new</strong> Path(
<a class="jxr_linenumber" name="229" href="#229">229</a> TEST_UTIL.getDataTestDir(<span class="jxr_string">"testReversibleStoreScanner"</span>), <span class="jxr_string">"regionname"</span>),
<a class="jxr_linenumber" name="230" href="#230">230</a> <span class="jxr_string">"familyname"</span>);
<a class="jxr_linenumber" name="231" href="#231">231</a> CacheConfig cacheConf = <strong class="jxr_keyword">new</strong> CacheConfig(TEST_UTIL.getConfiguration());
<a class="jxr_linenumber" name="232" href="#232">232</a> HFileContextBuilder hcBuilder = <strong class="jxr_keyword">new</strong> HFileContextBuilder();
<a class="jxr_linenumber" name="233" href="#233">233</a> hcBuilder.withBlockSize(2 * 1024);
<a class="jxr_linenumber" name="234" href="#234">234</a> HFileContext hFileContext = hcBuilder.build();
<a class="jxr_linenumber" name="235" href="#235">235</a> StoreFile.Writer writer1 = <strong class="jxr_keyword">new</strong> StoreFile.WriterBuilder(
<a class="jxr_linenumber" name="236" href="#236">236</a> TEST_UTIL.getConfiguration(), cacheConf, fs).withOutputDir(
<a class="jxr_linenumber" name="237" href="#237">237</a> hfilePath).withFileContext(hFileContext).build();
<a class="jxr_linenumber" name="238" href="#238">238</a> StoreFile.Writer writer2 = <strong class="jxr_keyword">new</strong> StoreFile.WriterBuilder(
<a class="jxr_linenumber" name="239" href="#239">239</a> TEST_UTIL.getConfiguration(), cacheConf, fs).withOutputDir(
<a class="jxr_linenumber" name="240" href="#240">240</a> hfilePath).withFileContext(hFileContext).build();
<a class="jxr_linenumber" name="241" href="#241">241</a>
<a class="jxr_linenumber" name="242" href="#242">242</a> MemStore memstore = <strong class="jxr_keyword">new</strong> MemStore();
<a class="jxr_linenumber" name="243" href="#243">243</a> writeMemstoreAndStoreFiles(memstore, <strong class="jxr_keyword">new</strong> StoreFile.Writer[] { writer1,
<a class="jxr_linenumber" name="244" href="#244">244</a> writer2 });
<a class="jxr_linenumber" name="245" href="#245">245</a>
<a class="jxr_linenumber" name="246" href="#246">246</a> StoreFile sf1 = <strong class="jxr_keyword">new</strong> StoreFile(fs, writer1.getPath(),
<a class="jxr_linenumber" name="247" href="#247">247</a> TEST_UTIL.getConfiguration(), cacheConf, BloomType.NONE);
<a class="jxr_linenumber" name="248" href="#248">248</a>
<a class="jxr_linenumber" name="249" href="#249">249</a> StoreFile sf2 = <strong class="jxr_keyword">new</strong> StoreFile(fs, writer2.getPath(),
<a class="jxr_linenumber" name="250" href="#250">250</a> TEST_UTIL.getConfiguration(), cacheConf, BloomType.NONE);
<a class="jxr_linenumber" name="251" href="#251">251</a>
<a class="jxr_linenumber" name="252" href="#252">252</a> ScanType scanType = ScanType.USER_SCAN;
<a class="jxr_linenumber" name="253" href="#253">253</a> ScanInfo scanInfo = <strong class="jxr_keyword">new</strong> ScanInfo(FAMILYNAME, 0, Integer.MAX_VALUE,
<a class="jxr_linenumber" name="254" href="#254">254</a> Long.MAX_VALUE, false, 0, KeyValue.COMPARATOR);
<a class="jxr_linenumber" name="255" href="#255">255</a>
<a class="jxr_linenumber" name="256" href="#256">256</a> <em class="jxr_comment">// Case 1.Test a full reversed scan</em>
<a class="jxr_linenumber" name="257" href="#257">257</a> Scan scan = <strong class="jxr_keyword">new</strong> Scan();
<a class="jxr_linenumber" name="258" href="#258">258</a> scan.setReversed(<strong class="jxr_keyword">true</strong>);
<a class="jxr_linenumber" name="259" href="#259">259</a> StoreScanner storeScanner = getReversibleStoreScanner(memstore, sf1, sf2,
<a class="jxr_linenumber" name="260" href="#260">260</a> scan, scanType, scanInfo, MAXMVCC);
<a class="jxr_linenumber" name="261" href="#261">261</a> verifyCountAndOrder(storeScanner, QUALSIZE * ROWSIZE, ROWSIZE, false);
<a class="jxr_linenumber" name="262" href="#262">262</a>
<a class="jxr_linenumber" name="263" href="#263">263</a> <em class="jxr_comment">// Case 2.Test reversed scan with a specified start row</em>
<a class="jxr_linenumber" name="264" href="#264">264</a> <strong class="jxr_keyword">int</strong> startRowNum = ROWSIZE / 2;
<a class="jxr_linenumber" name="265" href="#265">265</a> byte[] startRow = ROWS[startRowNum];
<a class="jxr_linenumber" name="266" href="#266">266</a> scan.setStartRow(startRow);
<a class="jxr_linenumber" name="267" href="#267">267</a> storeScanner = getReversibleStoreScanner(memstore, sf1, sf2, scan,
<a class="jxr_linenumber" name="268" href="#268">268</a> scanType, scanInfo, MAXMVCC);
<a class="jxr_linenumber" name="269" href="#269">269</a> verifyCountAndOrder(storeScanner, QUALSIZE * (startRowNum + 1),
<a class="jxr_linenumber" name="270" href="#270">270</a> startRowNum + 1, false);
<a class="jxr_linenumber" name="271" href="#271">271</a>
<a class="jxr_linenumber" name="272" href="#272">272</a> <em class="jxr_comment">// Case 3.Test reversed scan with a specified start row and specified</em>
<a class="jxr_linenumber" name="273" href="#273">273</a> <em class="jxr_comment">// qualifiers</em>
<a class="jxr_linenumber" name="274" href="#274">274</a> assertTrue(QUALSIZE > 2);
<a class="jxr_linenumber" name="275" href="#275">275</a> scan.addColumn(FAMILYNAME, QUALS[0]);
<a class="jxr_linenumber" name="276" href="#276">276</a> scan.addColumn(FAMILYNAME, QUALS[2]);
<a class="jxr_linenumber" name="277" href="#277">277</a> storeScanner = getReversibleStoreScanner(memstore, sf1, sf2, scan,
<a class="jxr_linenumber" name="278" href="#278">278</a> scanType, scanInfo, MAXMVCC);
<a class="jxr_linenumber" name="279" href="#279">279</a> verifyCountAndOrder(storeScanner, 2 * (startRowNum + 1), startRowNum + 1,
<a class="jxr_linenumber" name="280" href="#280">280</a> false);
<a class="jxr_linenumber" name="281" href="#281">281</a>
<a class="jxr_linenumber" name="282" href="#282">282</a> <em class="jxr_comment">// Case 4.Test reversed scan with mvcc based on case 3</em>
<a class="jxr_linenumber" name="283" href="#283">283</a> <strong class="jxr_keyword">for</strong> (<strong class="jxr_keyword">int</strong> readPoint = 0; readPoint < MAXMVCC; readPoint++) {
<a class="jxr_linenumber" name="284" href="#284">284</a> LOG.info(<span class="jxr_string">"Setting read point to "</span> + readPoint);
<a class="jxr_linenumber" name="285" href="#285">285</a> storeScanner = getReversibleStoreScanner(memstore, sf1, sf2, scan,
<a class="jxr_linenumber" name="286" href="#286">286</a> scanType, scanInfo, readPoint);
<a class="jxr_linenumber" name="287" href="#287">287</a> <strong class="jxr_keyword">int</strong> expectedRowCount = 0;
<a class="jxr_linenumber" name="288" href="#288">288</a> <strong class="jxr_keyword">int</strong> expectedKVCount = 0;
<a class="jxr_linenumber" name="289" href="#289">289</a> <strong class="jxr_keyword">for</strong> (<strong class="jxr_keyword">int</strong> i = startRowNum; i >= 0; i--) {
<a class="jxr_linenumber" name="290" href="#290">290</a> <strong class="jxr_keyword">int</strong> kvCount = 0;
<a class="jxr_linenumber" name="291" href="#291">291</a> <strong class="jxr_keyword">if</strong> (makeMVCC(i, 0) <= readPoint) {
<a class="jxr_linenumber" name="292" href="#292">292</a> kvCount++;
<a class="jxr_linenumber" name="293" href="#293">293</a> }
<a class="jxr_linenumber" name="294" href="#294">294</a> <strong class="jxr_keyword">if</strong> (makeMVCC(i, 2) <= readPoint) {
<a class="jxr_linenumber" name="295" href="#295">295</a> kvCount++;
<a class="jxr_linenumber" name="296" href="#296">296</a> }
<a class="jxr_linenumber" name="297" href="#297">297</a> <strong class="jxr_keyword">if</strong> (kvCount > 0) {
<a class="jxr_linenumber" name="298" href="#298">298</a> expectedRowCount++;
<a class="jxr_linenumber" name="299" href="#299">299</a> expectedKVCount += kvCount;
<a class="jxr_linenumber" name="300" href="#300">300</a> }
<a class="jxr_linenumber" name="301" href="#301">301</a> }
<a class="jxr_linenumber" name="302" href="#302">302</a> verifyCountAndOrder(storeScanner, expectedKVCount, expectedRowCount,
<a class="jxr_linenumber" name="303" href="#303">303</a> false);
<a class="jxr_linenumber" name="304" href="#304">304</a> }
<a class="jxr_linenumber" name="305" href="#305">305</a> }
<a class="jxr_linenumber" name="306" href="#306">306</a>
<a class="jxr_linenumber" name="307" href="#307">307</a> @Test
<a class="jxr_linenumber" name="308" href="#308">308</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> testReversibleRegionScanner() <strong class="jxr_keyword">throws</strong> IOException {
<a class="jxr_linenumber" name="309" href="#309">309</a> byte[] tableName = Bytes.toBytes(<span class="jxr_string">"testtable"</span>);
<a class="jxr_linenumber" name="310" href="#310">310</a> byte[] FAMILYNAME2 = Bytes.toBytes(<span class="jxr_string">"testCf2"</span>);
<a class="jxr_linenumber" name="311" href="#311">311</a> Configuration conf = HBaseConfiguration.create();
<a class="jxr_linenumber" name="312" href="#312">312</a> HRegion region = TEST_UTIL.createLocalHRegion(tableName, <strong class="jxr_keyword">null</strong>, <strong class="jxr_keyword">null</strong>,
<a class="jxr_linenumber" name="313" href="#313">313</a> <span class="jxr_string">"testReversibleRegionScanner"</span>, conf, false, Durability.SYNC_WAL, <strong class="jxr_keyword">null</strong>,
<a class="jxr_linenumber" name="314" href="#314">314</a> FAMILYNAME, FAMILYNAME2);
<a class="jxr_linenumber" name="315" href="#315">315</a> loadDataToRegion(region, FAMILYNAME2);
<a class="jxr_linenumber" name="316" href="#316">316</a>
<a class="jxr_linenumber" name="317" href="#317">317</a> <em class="jxr_comment">// verify row count with forward scan</em>
<a class="jxr_linenumber" name="318" href="#318">318</a> Scan scan = <strong class="jxr_keyword">new</strong> Scan();
<a class="jxr_linenumber" name="319" href="#319">319</a> InternalScanner scanner = region.getScanner(scan);
<a class="jxr_linenumber" name="320" href="#320">320</a> verifyCountAndOrder(scanner, ROWSIZE * QUALSIZE * 2, ROWSIZE, <strong class="jxr_keyword">true</strong>);
<a class="jxr_linenumber" name="321" href="#321">321</a>
<a class="jxr_linenumber" name="322" href="#322">322</a> <em class="jxr_comment">// Case1:Full reversed scan</em>
<a class="jxr_linenumber" name="323" href="#323">323</a> scan.setReversed(<strong class="jxr_keyword">true</strong>);
<a class="jxr_linenumber" name="324" href="#324">324</a> scanner = region.getScanner(scan);
<a class="jxr_linenumber" name="325" href="#325">325</a> verifyCountAndOrder(scanner, ROWSIZE * QUALSIZE * 2, ROWSIZE, false);
<a class="jxr_linenumber" name="326" href="#326">326</a>
<a class="jxr_linenumber" name="327" href="#327">327</a> <em class="jxr_comment">// Case2:Full reversed scan with one family</em>
<a class="jxr_linenumber" name="328" href="#328">328</a> scan = <strong class="jxr_keyword">new</strong> Scan();
<a class="jxr_linenumber" name="329" href="#329">329</a> scan.setReversed(<strong class="jxr_keyword">true</strong>);
<a class="jxr_linenumber" name="330" href="#330">330</a> scan.addFamily(FAMILYNAME);
<a class="jxr_linenumber" name="331" href="#331">331</a> scanner = region.getScanner(scan);
<a class="jxr_linenumber" name="332" href="#332">332</a> verifyCountAndOrder(scanner, ROWSIZE * QUALSIZE, ROWSIZE, false);
<a class="jxr_linenumber" name="333" href="#333">333</a>
<a class="jxr_linenumber" name="334" href="#334">334</a> <em class="jxr_comment">// Case3:Specify qualifiers + One family</em>
<a class="jxr_linenumber" name="335" href="#335">335</a> byte[][] specifiedQualifiers = { QUALS[1], QUALS[2] };
<a class="jxr_linenumber" name="336" href="#336">336</a> <strong class="jxr_keyword">for</strong> (byte[] specifiedQualifier : specifiedQualifiers)
<a class="jxr_linenumber" name="337" href="#337">337</a> scan.addColumn(FAMILYNAME, specifiedQualifier);
<a class="jxr_linenumber" name="338" href="#338">338</a> scanner = region.getScanner(scan);
<a class="jxr_linenumber" name="339" href="#339">339</a> verifyCountAndOrder(scanner, ROWSIZE * 2, ROWSIZE, false);
<a class="jxr_linenumber" name="340" href="#340">340</a>
<a class="jxr_linenumber" name="341" href="#341">341</a> <em class="jxr_comment">// Case4:Specify qualifiers + Two families</em>
<a class="jxr_linenumber" name="342" href="#342">342</a> <strong class="jxr_keyword">for</strong> (byte[] specifiedQualifier : specifiedQualifiers)
<a class="jxr_linenumber" name="343" href="#343">343</a> scan.addColumn(FAMILYNAME2, specifiedQualifier);
<a class="jxr_linenumber" name="344" href="#344">344</a> scanner = region.getScanner(scan);
<a class="jxr_linenumber" name="345" href="#345">345</a> verifyCountAndOrder(scanner, ROWSIZE * 2 * 2, ROWSIZE, false);
<a class="jxr_linenumber" name="346" href="#346">346</a>
<a class="jxr_linenumber" name="347" href="#347">347</a> <em class="jxr_comment">// Case5: Case4 + specify start row</em>
<a class="jxr_linenumber" name="348" href="#348">348</a> <strong class="jxr_keyword">int</strong> startRowNum = ROWSIZE * 3 / 4;
<a class="jxr_linenumber" name="349" href="#349">349</a> scan.setStartRow(ROWS[startRowNum]);
<a class="jxr_linenumber" name="350" href="#350">350</a> scanner = region.getScanner(scan);
<a class="jxr_linenumber" name="351" href="#351">351</a> verifyCountAndOrder(scanner, (startRowNum + 1) * 2 * 2, (startRowNum + 1),
<a class="jxr_linenumber" name="352" href="#352">352</a> false);
<a class="jxr_linenumber" name="353" href="#353">353</a>
<a class="jxr_linenumber" name="354" href="#354">354</a> <em class="jxr_comment">// Case6: Case4 + specify stop row</em>
<a class="jxr_linenumber" name="355" href="#355">355</a> <strong class="jxr_keyword">int</strong> stopRowNum = ROWSIZE / 4;
<a class="jxr_linenumber" name="356" href="#356">356</a> scan.setStartRow(HConstants.EMPTY_BYTE_ARRAY);
<a class="jxr_linenumber" name="357" href="#357">357</a> scan.setStopRow(ROWS[stopRowNum]);
<a class="jxr_linenumber" name="358" href="#358">358</a> scanner = region.getScanner(scan);
<a class="jxr_linenumber" name="359" href="#359">359</a> verifyCountAndOrder(scanner, (ROWSIZE - stopRowNum - 1) * 2 * 2, (ROWSIZE
<a class="jxr_linenumber" name="360" href="#360">360</a> - stopRowNum - 1), false);
<a class="jxr_linenumber" name="361" href="#361">361</a>
<a class="jxr_linenumber" name="362" href="#362">362</a> <em class="jxr_comment">// Case7: Case4 + specify start row + specify stop row</em>
<a class="jxr_linenumber" name="363" href="#363">363</a> scan.setStartRow(ROWS[startRowNum]);
<a class="jxr_linenumber" name="364" href="#364">364</a> scanner = region.getScanner(scan);
<a class="jxr_linenumber" name="365" href="#365">365</a> verifyCountAndOrder(scanner, (startRowNum - stopRowNum) * 2 * 2,
<a class="jxr_linenumber" name="366" href="#366">366</a> (startRowNum - stopRowNum), false);
<a class="jxr_linenumber" name="367" href="#367">367</a>
<a class="jxr_linenumber" name="368" href="#368">368</a> <em class="jxr_comment">// Case8: Case7 + SingleColumnValueFilter</em>
<a class="jxr_linenumber" name="369" href="#369">369</a> <strong class="jxr_keyword">int</strong> valueNum = startRowNum % VALUESIZE;
<a class="jxr_linenumber" name="370" href="#370">370</a> Filter filter = <strong class="jxr_keyword">new</strong> SingleColumnValueFilter(FAMILYNAME,
<a class="jxr_linenumber" name="371" href="#371">371</a> specifiedQualifiers[0], CompareOp.EQUAL, VALUES[valueNum]);
<a class="jxr_linenumber" name="372" href="#372">372</a> scan.setFilter(filter);
<a class="jxr_linenumber" name="373" href="#373">373</a> scanner = region.getScanner(scan);
<a class="jxr_linenumber" name="374" href="#374">374</a> <strong class="jxr_keyword">int</strong> unfilteredRowNum = (startRowNum - stopRowNum) / VALUESIZE
<a class="jxr_linenumber" name="375" href="#375">375</a> + (stopRowNum / VALUESIZE == valueNum ? 0 : 1);
<a class="jxr_linenumber" name="376" href="#376">376</a> verifyCountAndOrder(scanner, unfilteredRowNum * 2 * 2, unfilteredRowNum,
<a class="jxr_linenumber" name="377" href="#377">377</a> false);
<a class="jxr_linenumber" name="378" href="#378">378</a>
<a class="jxr_linenumber" name="379" href="#379">379</a> <em class="jxr_comment">// Case9: Case7 + PageFilter</em>
<a class="jxr_linenumber" name="380" href="#380">380</a> <strong class="jxr_keyword">int</strong> pageSize = 10;
<a class="jxr_linenumber" name="381" href="#381">381</a> filter = <strong class="jxr_keyword">new</strong> PageFilter(pageSize);
<a class="jxr_linenumber" name="382" href="#382">382</a> scan.setFilter(filter);
<a class="jxr_linenumber" name="383" href="#383">383</a> scanner = region.getScanner(scan);
<a class="jxr_linenumber" name="384" href="#384">384</a> <strong class="jxr_keyword">int</strong> expectedRowNum = pageSize;
<a class="jxr_linenumber" name="385" href="#385">385</a> verifyCountAndOrder(scanner, expectedRowNum * 2 * 2, expectedRowNum, false);
<a class="jxr_linenumber" name="386" href="#386">386</a>
<a class="jxr_linenumber" name="387" href="#387">387</a> <em class="jxr_comment">// Case10: Case7 + FilterList+MUST_PASS_ONE</em>
<a class="jxr_linenumber" name="388" href="#388">388</a> SingleColumnValueFilter scvFilter1 = <strong class="jxr_keyword">new</strong> SingleColumnValueFilter(
<a class="jxr_linenumber" name="389" href="#389">389</a> FAMILYNAME, specifiedQualifiers[0], CompareOp.EQUAL, VALUES[0]);
<a class="jxr_linenumber" name="390" href="#390">390</a> SingleColumnValueFilter scvFilter2 = <strong class="jxr_keyword">new</strong> SingleColumnValueFilter(
<a class="jxr_linenumber" name="391" href="#391">391</a> FAMILYNAME, specifiedQualifiers[0], CompareOp.EQUAL, VALUES[1]);
<a class="jxr_linenumber" name="392" href="#392">392</a> expectedRowNum = 0;
<a class="jxr_linenumber" name="393" href="#393">393</a> <strong class="jxr_keyword">for</strong> (<strong class="jxr_keyword">int</strong> i = startRowNum; i > stopRowNum; i--) {
<a class="jxr_linenumber" name="394" href="#394">394</a> <strong class="jxr_keyword">if</strong> (i % VALUESIZE == 0 || i % VALUESIZE == 1) {
<a class="jxr_linenumber" name="395" href="#395">395</a> expectedRowNum++;
<a class="jxr_linenumber" name="396" href="#396">396</a> }
<a class="jxr_linenumber" name="397" href="#397">397</a> }
<a class="jxr_linenumber" name="398" href="#398">398</a> filter = <strong class="jxr_keyword">new</strong> FilterList(Operator.MUST_PASS_ONE, scvFilter1, scvFilter2);
<a class="jxr_linenumber" name="399" href="#399">399</a> scan.setFilter(filter);
<a class="jxr_linenumber" name="400" href="#400">400</a> scanner = region.getScanner(scan);
<a class="jxr_linenumber" name="401" href="#401">401</a> verifyCountAndOrder(scanner, expectedRowNum * 2 * 2, expectedRowNum, false);
<a class="jxr_linenumber" name="402" href="#402">402</a>
<a class="jxr_linenumber" name="403" href="#403">403</a> <em class="jxr_comment">// Case10: Case7 + FilterList+MUST_PASS_ALL</em>
<a class="jxr_linenumber" name="404" href="#404">404</a> filter = <strong class="jxr_keyword">new</strong> FilterList(Operator.MUST_PASS_ALL, scvFilter1, scvFilter2);
<a class="jxr_linenumber" name="405" href="#405">405</a> expectedRowNum = 0;
<a class="jxr_linenumber" name="406" href="#406">406</a> scan.setFilter(filter);
<a class="jxr_linenumber" name="407" href="#407">407</a> scanner = region.getScanner(scan);
<a class="jxr_linenumber" name="408" href="#408">408</a> verifyCountAndOrder(scanner, expectedRowNum * 2 * 2, expectedRowNum, false);
<a class="jxr_linenumber" name="409" href="#409">409</a> }
<a class="jxr_linenumber" name="410" href="#410">410</a>
<a class="jxr_linenumber" name="411" href="#411">411</a> <strong class="jxr_keyword">private</strong> StoreScanner getReversibleStoreScanner(MemStore memstore,
<a class="jxr_linenumber" name="412" href="#412">412</a> StoreFile sf1, StoreFile sf2, Scan scan, ScanType scanType,
<a class="jxr_linenumber" name="413" href="#413">413</a> ScanInfo scanInfo, <strong class="jxr_keyword">int</strong> readPoint) <strong class="jxr_keyword">throws</strong> IOException {
<a class="jxr_linenumber" name="414" href="#414">414</a> List<KeyValueScanner> scanners = getScanners(memstore, sf1, sf2, <strong class="jxr_keyword">null</strong>,
<a class="jxr_linenumber" name="415" href="#415">415</a> false, readPoint);
<a class="jxr_linenumber" name="416" href="#416">416</a> NavigableSet<byte[]> columns = <strong class="jxr_keyword">null</strong>;
<a class="jxr_linenumber" name="417" href="#417">417</a> <strong class="jxr_keyword">for</strong> (Map.Entry<byte[], NavigableSet<byte[]>> entry : scan.getFamilyMap()
<a class="jxr_linenumber" name="418" href="#418">418</a> .entrySet()) {
<a class="jxr_linenumber" name="419" href="#419">419</a> <em class="jxr_comment">// Should only one family</em>
<a class="jxr_linenumber" name="420" href="#420">420</a> columns = entry.getValue();
<a class="jxr_linenumber" name="421" href="#421">421</a> }
<a class="jxr_linenumber" name="422" href="#422">422</a> StoreScanner storeScanner = <strong class="jxr_keyword">new</strong> ReversedStoreScanner(scan, scanInfo,
<a class="jxr_linenumber" name="423" href="#423">423</a> scanType, columns, scanners);
<a class="jxr_linenumber" name="424" href="#424">424</a> <strong class="jxr_keyword">return</strong> storeScanner;
<a class="jxr_linenumber" name="425" href="#425">425</a> }
<a class="jxr_linenumber" name="426" href="#426">426</a>
<a class="jxr_linenumber" name="427" href="#427">427</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">void</strong> verifyCountAndOrder(InternalScanner scanner,
<a class="jxr_linenumber" name="428" href="#428">428</a> <strong class="jxr_keyword">int</strong> expectedKVCount, <strong class="jxr_keyword">int</strong> expectedRowCount, <strong class="jxr_keyword">boolean</strong> forward)
<a class="jxr_linenumber" name="429" href="#429">429</a> <strong class="jxr_keyword">throws</strong> IOException {
<a class="jxr_linenumber" name="430" href="#430">430</a> List<Cell> kvList = <strong class="jxr_keyword">new</strong> ArrayList<Cell>();
<a class="jxr_linenumber" name="431" href="#431">431</a> Result lastResult = <strong class="jxr_keyword">null</strong>;
<a class="jxr_linenumber" name="432" href="#432">432</a> <strong class="jxr_keyword">int</strong> rowCount = 0;
<a class="jxr_linenumber" name="433" href="#433">433</a> <strong class="jxr_keyword">int</strong> kvCount = 0;
<a class="jxr_linenumber" name="434" href="#434">434</a> <strong class="jxr_keyword">try</strong> {
<a class="jxr_linenumber" name="435" href="#435">435</a> <strong class="jxr_keyword">while</strong> (scanner.next(kvList)) {
<a class="jxr_linenumber" name="436" href="#436">436</a> <strong class="jxr_keyword">if</strong> (kvList.isEmpty()) <strong class="jxr_keyword">continue</strong>;
<a class="jxr_linenumber" name="437" href="#437">437</a> rowCount++;
<a class="jxr_linenumber" name="438" href="#438">438</a> kvCount += kvList.size();
<a class="jxr_linenumber" name="439" href="#439">439</a> <strong class="jxr_keyword">if</strong> (lastResult != <strong class="jxr_keyword">null</strong>) {
<a class="jxr_linenumber" name="440" href="#440">440</a> Result curResult = Result.create(kvList);
<a class="jxr_linenumber" name="441" href="#441">441</a> assertEquals(<span class="jxr_string">"LastResult:"</span> + lastResult + <span class="jxr_string">"CurResult:"</span> + curResult,
<a class="jxr_linenumber" name="442" href="#442">442</a> forward,
<a class="jxr_linenumber" name="443" href="#443">443</a> Bytes.compareTo(curResult.getRow(), lastResult.getRow()) > 0);
<a class="jxr_linenumber" name="444" href="#444">444</a> }
<a class="jxr_linenumber" name="445" href="#445">445</a> lastResult = Result.create(kvList);
<a class="jxr_linenumber" name="446" href="#446">446</a> kvList.clear();
<a class="jxr_linenumber" name="447" href="#447">447</a> }
<a class="jxr_linenumber" name="448" href="#448">448</a> } <strong class="jxr_keyword">finally</strong> {
<a class="jxr_linenumber" name="449" href="#449">449</a> scanner.close();
<a class="jxr_linenumber" name="450" href="#450">450</a> }
<a class="jxr_linenumber" name="451" href="#451">451</a> <strong class="jxr_keyword">if</strong> (!kvList.isEmpty()) {
<a class="jxr_linenumber" name="452" href="#452">452</a> rowCount++;
<a class="jxr_linenumber" name="453" href="#453">453</a> kvCount += kvList.size();
<a class="jxr_linenumber" name="454" href="#454">454</a> kvList.clear();
<a class="jxr_linenumber" name="455" href="#455">455</a> }
<a class="jxr_linenumber" name="456" href="#456">456</a> assertEquals(expectedKVCount, kvCount);
<a class="jxr_linenumber" name="457" href="#457">457</a> assertEquals(expectedRowCount, rowCount);
<a class="jxr_linenumber" name="458" href="#458">458</a> }
<a class="jxr_linenumber" name="459" href="#459">459</a>
<a class="jxr_linenumber" name="460" href="#460">460</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">void</strong> internalTestSeekAndNextForReversibleKeyValueHeap(
<a class="jxr_linenumber" name="461" href="#461">461</a> ReversedKeyValueHeap kvHeap, <strong class="jxr_keyword">int</strong> startRowNum) <strong class="jxr_keyword">throws</strong> IOException {
<a class="jxr_linenumber" name="462" href="#462">462</a> <em class="jxr_comment">// Test next and seek</em>
<a class="jxr_linenumber" name="463" href="#463">463</a> <strong class="jxr_keyword">for</strong> (<strong class="jxr_keyword">int</strong> i = startRowNum; i >= 0; i--) {
<a class="jxr_linenumber" name="464" href="#464">464</a> <strong class="jxr_keyword">if</strong> (i % 2 == 1 && i - 2 >= 0) {
<a class="jxr_linenumber" name="465" href="#465">465</a> i = i - 2;
<a class="jxr_linenumber" name="466" href="#466">466</a> kvHeap.seekToPreviousRow(KeyValue.createFirstOnRow(ROWS[i + 1]));
<a class="jxr_linenumber" name="467" href="#467">467</a> }
<a class="jxr_linenumber" name="468" href="#468">468</a> <strong class="jxr_keyword">for</strong> (<strong class="jxr_keyword">int</strong> j = 0; j < QUALSIZE; j++) {
<a class="jxr_linenumber" name="469" href="#469">469</a> <strong class="jxr_keyword">if</strong> (j % 2 == 1 && (j + 1) < QUALSIZE) {
<a class="jxr_linenumber" name="470" href="#470">470</a> j = j + 1;
<a class="jxr_linenumber" name="471" href="#471">471</a> kvHeap.backwardSeek(makeKV(i, j));
<a class="jxr_linenumber" name="472" href="#472">472</a> }
<a class="jxr_linenumber" name="473" href="#473">473</a> assertEquals(makeKV(i, j), kvHeap.peek());
<a class="jxr_linenumber" name="474" href="#474">474</a> kvHeap.next();
<a class="jxr_linenumber" name="475" href="#475">475</a> }
<a class="jxr_linenumber" name="476" href="#476">476</a> }
<a class="jxr_linenumber" name="477" href="#477">477</a> assertEquals(<strong class="jxr_keyword">null</strong>, kvHeap.peek());
<a class="jxr_linenumber" name="478" href="#478">478</a> }
<a class="jxr_linenumber" name="479" href="#479">479</a>
<a class="jxr_linenumber" name="480" href="#480">480</a> <strong class="jxr_keyword">private</strong> ReversedKeyValueHeap getReversibleKeyValueHeap(MemStore memstore,
<a class="jxr_linenumber" name="481" href="#481">481</a> StoreFile sf1, StoreFile sf2, byte[] startRow, <strong class="jxr_keyword">int</strong> readPoint)
<a class="jxr_linenumber" name="482" href="#482">482</a> <strong class="jxr_keyword">throws</strong> IOException {
<a class="jxr_linenumber" name="483" href="#483">483</a> List<KeyValueScanner> scanners = getScanners(memstore, sf1, sf2, startRow,
<a class="jxr_linenumber" name="484" href="#484">484</a> <strong class="jxr_keyword">true</strong>, readPoint);
<a class="jxr_linenumber" name="485" href="#485">485</a> ReversedKeyValueHeap kvHeap = <strong class="jxr_keyword">new</strong> ReversedKeyValueHeap(scanners,
<a class="jxr_linenumber" name="486" href="#486">486</a> KeyValue.COMPARATOR);
<a class="jxr_linenumber" name="487" href="#487">487</a> <strong class="jxr_keyword">return</strong> kvHeap;
<a class="jxr_linenumber" name="488" href="#488">488</a> }
<a class="jxr_linenumber" name="489" href="#489">489</a>
<a class="jxr_linenumber" name="490" href="#490">490</a> <strong class="jxr_keyword">private</strong> List<KeyValueScanner> getScanners(MemStore memstore, StoreFile sf1,
<a class="jxr_linenumber" name="491" href="#491">491</a> StoreFile sf2, byte[] startRow, <strong class="jxr_keyword">boolean</strong> doSeek, <strong class="jxr_keyword">int</strong> readPoint)
<a class="jxr_linenumber" name="492" href="#492">492</a> <strong class="jxr_keyword">throws</strong> IOException {
<a class="jxr_linenumber" name="493" href="#493">493</a> List<StoreFileScanner> fileScanners = StoreFileScanner
<a class="jxr_linenumber" name="494" href="#494">494</a> .getScannersForStoreFiles(Lists.newArrayList(sf1, sf2), false, <strong class="jxr_keyword">true</strong>,
<a class="jxr_linenumber" name="495" href="#495">495</a> false, readPoint);
<a class="jxr_linenumber" name="496" href="#496">496</a> List<KeyValueScanner> memScanners = memstore.getScanners(readPoint);
<a class="jxr_linenumber" name="497" href="#497">497</a> List<KeyValueScanner> scanners = <strong class="jxr_keyword">new</strong> ArrayList<KeyValueScanner>(
<a class="jxr_linenumber" name="498" href="#498">498</a> fileScanners.size() + 1);
<a class="jxr_linenumber" name="499" href="#499">499</a> scanners.addAll(fileScanners);
<a class="jxr_linenumber" name="500" href="#500">500</a> scanners.addAll(memScanners);
<a class="jxr_linenumber" name="501" href="#501">501</a>
<a class="jxr_linenumber" name="502" href="#502">502</a> <strong class="jxr_keyword">if</strong> (doSeek) {
<a class="jxr_linenumber" name="503" href="#503">503</a> <strong class="jxr_keyword">if</strong> (Bytes.equals(HConstants.EMPTY_START_ROW, startRow)) {
<a class="jxr_linenumber" name="504" href="#504">504</a> <strong class="jxr_keyword">for</strong> (KeyValueScanner scanner : scanners) {
<a class="jxr_linenumber" name="505" href="#505">505</a> scanner.seekToLastRow();
<a class="jxr_linenumber" name="506" href="#506">506</a> }
<a class="jxr_linenumber" name="507" href="#507">507</a> } <strong class="jxr_keyword">else</strong> {
<a class="jxr_linenumber" name="508" href="#508">508</a> KeyValue startKey = KeyValue.createFirstOnRow(startRow);
<a class="jxr_linenumber" name="509" href="#509">509</a> <strong class="jxr_keyword">for</strong> (KeyValueScanner scanner : scanners) {
<a class="jxr_linenumber" name="510" href="#510">510</a> scanner.backwardSeek(startKey);
<a class="jxr_linenumber" name="511" href="#511">511</a> }
<a class="jxr_linenumber" name="512" href="#512">512</a> }
<a class="jxr_linenumber" name="513" href="#513">513</a> }
<a class="jxr_linenumber" name="514" href="#514">514</a> <strong class="jxr_keyword">return</strong> scanners;
<a class="jxr_linenumber" name="515" href="#515">515</a> }
<a class="jxr_linenumber" name="516" href="#516">516</a>
<a class="jxr_linenumber" name="517" href="#517">517</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">void</strong> seekTestOfReversibleKeyValueScanner(KeyValueScanner scanner)
<a class="jxr_linenumber" name="518" href="#518">518</a> <strong class="jxr_keyword">throws</strong> IOException {
<a class="jxr_linenumber" name="519" href="#519">519</a> <em class="jxr_javadoccomment">/**</em>
<a class="jxr_linenumber" name="520" href="#520">520</a> <em class="jxr_javadoccomment"> * Test without MVCC</em>
<a class="jxr_linenumber" name="521" href="#521">521</a> <em class="jxr_javadoccomment"> */</em>
<a class="jxr_linenumber" name="522" href="#522">522</a> <em class="jxr_comment">// Test seek to last row</em>
<a class="jxr_linenumber" name="523" href="#523">523</a> assertTrue(scanner.seekToLastRow());
<a class="jxr_linenumber" name="524" href="#524">524</a> assertEquals(makeKV(ROWSIZE - 1, 0), scanner.peek());
<a class="jxr_linenumber" name="525" href="#525">525</a>
<a class="jxr_linenumber" name="526" href="#526">526</a> <em class="jxr_comment">// Test backward seek in three cases</em>
<a class="jxr_linenumber" name="527" href="#527">527</a> <em class="jxr_comment">// Case1: seek in the same row in backwardSeek</em>
<a class="jxr_linenumber" name="528" href="#528">528</a> KeyValue seekKey = makeKV(ROWSIZE - 2, QUALSIZE - 2);
<a class="jxr_linenumber" name="529" href="#529">529</a> assertTrue(scanner.backwardSeek(seekKey));
<a class="jxr_linenumber" name="530" href="#530">530</a> assertEquals(seekKey, scanner.peek());
<a class="jxr_linenumber" name="531" href="#531">531</a>
<a class="jxr_linenumber" name="532" href="#532">532</a> <em class="jxr_comment">// Case2: seek to the previous row in backwardSeek</em>
<a class="jxr_linenumber" name="533" href="#533">533</a> <strong class="jxr_keyword">int</strong> seekRowNum = ROWSIZE - 2;
<a class="jxr_linenumber" name="534" href="#534">534</a> assertTrue(scanner.backwardSeek(KeyValue.createLastOnRow(ROWS[seekRowNum])));
<a class="jxr_linenumber" name="535" href="#535">535</a> KeyValue expectedKey = makeKV(seekRowNum - 1, 0);
<a class="jxr_linenumber" name="536" href="#536">536</a> assertEquals(expectedKey, scanner.peek());
<a class="jxr_linenumber" name="537" href="#537">537</a>
<a class="jxr_linenumber" name="538" href="#538">538</a> <em class="jxr_comment">// Case3: unable to backward seek</em>
<a class="jxr_linenumber" name="539" href="#539">539</a> assertFalse(scanner.backwardSeek(KeyValue.createLastOnRow(ROWS[0])));
<a class="jxr_linenumber" name="540" href="#540">540</a> assertEquals(<strong class="jxr_keyword">null</strong>, scanner.peek());
<a class="jxr_linenumber" name="541" href="#541">541</a>
<a class="jxr_linenumber" name="542" href="#542">542</a> <em class="jxr_comment">// Test seek to previous row</em>
<a class="jxr_linenumber" name="543" href="#543">543</a> seekRowNum = ROWSIZE - 4;
<a class="jxr_linenumber" name="544" href="#544">544</a> assertTrue(scanner.seekToPreviousRow(KeyValue
<a class="jxr_linenumber" name="545" href="#545">545</a> .createFirstOnRow(ROWS[seekRowNum])));
<a class="jxr_linenumber" name="546" href="#546">546</a> expectedKey = makeKV(seekRowNum - 1, 0);
<a class="jxr_linenumber" name="547" href="#547">547</a> assertEquals(expectedKey, scanner.peek());
<a class="jxr_linenumber" name="548" href="#548">548</a>
<a class="jxr_linenumber" name="549" href="#549">549</a> <em class="jxr_comment">// Test seek to previous row for the first row</em>
<a class="jxr_linenumber" name="550" href="#550">550</a> assertFalse(scanner.seekToPreviousRow(makeKV(0, 0)));
<a class="jxr_linenumber" name="551" href="#551">551</a> assertEquals(<strong class="jxr_keyword">null</strong>, scanner.peek());
<a class="jxr_linenumber" name="552" href="#552">552</a>
<a class="jxr_linenumber" name="553" href="#553">553</a> }
<a class="jxr_linenumber" name="554" href="#554">554</a>
<a class="jxr_linenumber" name="555" href="#555">555</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">void</strong> seekTestOfReversibleKeyValueScannerWithMVCC(
<a class="jxr_linenumber" name="556" href="#556">556</a> KeyValueScanner scanner, <strong class="jxr_keyword">int</strong> readPoint) <strong class="jxr_keyword">throws</strong> IOException {
<a class="jxr_linenumber" name="557" href="#557">557</a> <em class="jxr_javadoccomment">/**</em>
<a class="jxr_linenumber" name="558" href="#558">558</a> <em class="jxr_javadoccomment"> * Test with MVCC</em>
<a class="jxr_linenumber" name="559" href="#559">559</a> <em class="jxr_javadoccomment"> */</em>
<a class="jxr_linenumber" name="560" href="#560">560</a> <em class="jxr_comment">// Test seek to last row</em>
<a class="jxr_linenumber" name="561" href="#561">561</a> KeyValue expectedKey = getNextReadableKeyValueWithBackwardScan(
<a class="jxr_linenumber" name="562" href="#562">562</a> ROWSIZE - 1, 0, readPoint);
<a class="jxr_linenumber" name="563" href="#563">563</a> assertEquals(expectedKey != <strong class="jxr_keyword">null</strong>, scanner.seekToLastRow());
<a class="jxr_linenumber" name="564" href="#564">564</a> assertEquals(expectedKey, scanner.peek());
<a class="jxr_linenumber" name="565" href="#565">565</a>
<a class="jxr_linenumber" name="566" href="#566">566</a> <em class="jxr_comment">// Test backward seek in two cases</em>
<a class="jxr_linenumber" name="567" href="#567">567</a> <em class="jxr_comment">// Case1: seek in the same row in backwardSeek</em>
<a class="jxr_linenumber" name="568" href="#568">568</a> expectedKey = getNextReadableKeyValueWithBackwardScan(ROWSIZE - 2,
<a class="jxr_linenumber" name="569" href="#569">569</a> QUALSIZE - 2, readPoint);
<a class="jxr_linenumber" name="570" href="#570">570</a> assertEquals(expectedKey != <strong class="jxr_keyword">null</strong>, scanner.backwardSeek(expectedKey));
<a class="jxr_linenumber" name="571" href="#571">571</a> assertEquals(expectedKey, scanner.peek());
<a class="jxr_linenumber" name="572" href="#572">572</a>
<a class="jxr_linenumber" name="573" href="#573">573</a> <em class="jxr_comment">// Case2: seek to the previous row in backwardSeek</em>
<a class="jxr_linenumber" name="574" href="#574">574</a> <strong class="jxr_keyword">int</strong> seekRowNum = ROWSIZE - 3;
<a class="jxr_linenumber" name="575" href="#575">575</a> KeyValue seekKey = KeyValue.createLastOnRow(ROWS[seekRowNum]);
<a class="jxr_linenumber" name="576" href="#576">576</a> expectedKey = getNextReadableKeyValueWithBackwardScan(seekRowNum - 1, 0,
<a class="jxr_linenumber" name="577" href="#577">577</a> readPoint);
<a class="jxr_linenumber" name="578" href="#578">578</a> assertEquals(expectedKey != <strong class="jxr_keyword">null</strong>, scanner.backwardSeek(seekKey));
<a class="jxr_linenumber" name="579" href="#579">579</a> assertEquals(expectedKey, scanner.peek());
<a class="jxr_linenumber" name="580" href="#580">580</a>
<a class="jxr_linenumber" name="581" href="#581">581</a> <em class="jxr_comment">// Test seek to previous row</em>
<a class="jxr_linenumber" name="582" href="#582">582</a> seekRowNum = ROWSIZE - 4;
<a class="jxr_linenumber" name="583" href="#583">583</a> expectedKey = getNextReadableKeyValueWithBackwardScan(seekRowNum - 1, 0,
<a class="jxr_linenumber" name="584" href="#584">584</a> readPoint);
<a class="jxr_linenumber" name="585" href="#585">585</a> assertEquals(expectedKey != <strong class="jxr_keyword">null</strong>, scanner.seekToPreviousRow(KeyValue
<a class="jxr_linenumber" name="586" href="#586">586</a> .createFirstOnRow(ROWS[seekRowNum])));
<a class="jxr_linenumber" name="587" href="#587">587</a> assertEquals(expectedKey, scanner.peek());
<a class="jxr_linenumber" name="588" href="#588">588</a> }
<a class="jxr_linenumber" name="589" href="#589">589</a>
<a class="jxr_linenumber" name="590" href="#590">590</a> <strong class="jxr_keyword">private</strong> KeyValue getNextReadableKeyValueWithBackwardScan(<strong class="jxr_keyword">int</strong> startRowNum,
<a class="jxr_linenumber" name="591" href="#591">591</a> <strong class="jxr_keyword">int</strong> startQualNum, <strong class="jxr_keyword">int</strong> readPoint) {
<a class="jxr_linenumber" name="592" href="#592">592</a> Pair<Integer, Integer> nextReadableNum = getNextReadableNumWithBackwardScan(
<a class="jxr_linenumber" name="593" href="#593">593</a> startRowNum, startQualNum, readPoint);
<a class="jxr_linenumber" name="594" href="#594">594</a> <strong class="jxr_keyword">if</strong> (nextReadableNum == <strong class="jxr_keyword">null</strong>)
<a class="jxr_linenumber" name="595" href="#595">595</a> <strong class="jxr_keyword">return</strong> <strong class="jxr_keyword">null</strong>;
<a class="jxr_linenumber" name="596" href="#596">596</a> <strong class="jxr_keyword">return</strong> makeKV(nextReadableNum.getFirst(), nextReadableNum.getSecond());
<a class="jxr_linenumber" name="597" href="#597">597</a> }
<a class="jxr_linenumber" name="598" href="#598">598</a>
<a class="jxr_linenumber" name="599" href="#599">599</a> <strong class="jxr_keyword">private</strong> Pair<Integer, Integer> getNextReadableNumWithBackwardScan(
<a class="jxr_linenumber" name="600" href="#600">600</a> <strong class="jxr_keyword">int</strong> startRowNum, <strong class="jxr_keyword">int</strong> startQualNum, <strong class="jxr_keyword">int</strong> readPoint) {
<a class="jxr_linenumber" name="601" href="#601">601</a> Pair<Integer, Integer> nextReadableNum = <strong class="jxr_keyword">null</strong>;
<a class="jxr_linenumber" name="602" href="#602">602</a> <strong class="jxr_keyword">boolean</strong> findExpected = false;
<a class="jxr_linenumber" name="603" href="#603">603</a> <strong class="jxr_keyword">for</strong> (<strong class="jxr_keyword">int</strong> i = startRowNum; i >= 0; i--) {
<a class="jxr_linenumber" name="604" href="#604">604</a> <strong class="jxr_keyword">for</strong> (<strong class="jxr_keyword">int</strong> j = (i == startRowNum ? startQualNum : 0); j < QUALSIZE; j++) {
<a class="jxr_linenumber" name="605" href="#605">605</a> <strong class="jxr_keyword">if</strong> (makeMVCC(i, j) <= readPoint) {
<a class="jxr_linenumber" name="606" href="#606">606</a> nextReadableNum = <strong class="jxr_keyword">new</strong> Pair<Integer, Integer>(i, j);
<a class="jxr_linenumber" name="607" href="#607">607</a> findExpected = <strong class="jxr_keyword">true</strong>;
<a class="jxr_linenumber" name="608" href="#608">608</a> <strong class="jxr_keyword">break</strong>;
<a class="jxr_linenumber" name="609" href="#609">609</a> }
<a class="jxr_linenumber" name="610" href="#610">610</a> }
<a class="jxr_linenumber" name="611" href="#611">611</a> <strong class="jxr_keyword">if</strong> (findExpected)
<a class="jxr_linenumber" name="612" href="#612">612</a> <strong class="jxr_keyword">break</strong>;
<a class="jxr_linenumber" name="613" href="#613">613</a> }
<a class="jxr_linenumber" name="614" href="#614">614</a> <strong class="jxr_keyword">return</strong> nextReadableNum;
<a class="jxr_linenumber" name="615" href="#615">615</a> }
<a class="jxr_linenumber" name="616" href="#616">616</a>
<a class="jxr_linenumber" name="617" href="#617">617</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">static</strong> <strong class="jxr_keyword">void</strong> loadDataToRegion(HRegion region, byte[] additionalFamily)
<a class="jxr_linenumber" name="618" href="#618">618</a> <strong class="jxr_keyword">throws</strong> IOException {
<a class="jxr_linenumber" name="619" href="#619">619</a> <strong class="jxr_keyword">for</strong> (<strong class="jxr_keyword">int</strong> i = 0; i < ROWSIZE; i++) {
<a class="jxr_linenumber" name="620" href="#620">620</a> Put put = <strong class="jxr_keyword">new</strong> Put(ROWS[i]);
<a class="jxr_linenumber" name="621" href="#621">621</a> <strong class="jxr_keyword">for</strong> (<strong class="jxr_keyword">int</strong> j = 0; j < QUALSIZE; j++) {
<a class="jxr_linenumber" name="622" href="#622">622</a> put.add(makeKV(i, j));
<a class="jxr_linenumber" name="623" href="#623">623</a> <em class="jxr_comment">// put additional family</em>
<a class="jxr_linenumber" name="624" href="#624">624</a> put.add(makeKV(i, j, additionalFamily));
<a class="jxr_linenumber" name="625" href="#625">625</a> }
<a class="jxr_linenumber" name="626" href="#626">626</a> region.put(put);
<a class="jxr_linenumber" name="627" href="#627">627</a> <strong class="jxr_keyword">if</strong> (i == ROWSIZE / 3 || i == ROWSIZE * 2 / 3) {
<a class="jxr_linenumber" name="628" href="#628">628</a> region.flushcache();
<a class="jxr_linenumber" name="629" href="#629">629</a> }
<a class="jxr_linenumber" name="630" href="#630">630</a> }
<a class="jxr_linenumber" name="631" href="#631">631</a> }
<a class="jxr_linenumber" name="632" href="#632">632</a>
<a class="jxr_linenumber" name="633" href="#633">633</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">static</strong> <strong class="jxr_keyword">void</strong> writeMemstoreAndStoreFiles(MemStore memstore,
<a class="jxr_linenumber" name="634" href="#634">634</a> <strong class="jxr_keyword">final</strong> StoreFile.Writer[] writers) <strong class="jxr_keyword">throws</strong> IOException {
<a class="jxr_linenumber" name="635" href="#635">635</a> Random rand = <strong class="jxr_keyword">new</strong> Random();
<a class="jxr_linenumber" name="636" href="#636">636</a> <strong class="jxr_keyword">try</strong> {
<a class="jxr_linenumber" name="637" href="#637">637</a> <strong class="jxr_keyword">for</strong> (<strong class="jxr_keyword">int</strong> i = 0; i < ROWSIZE; i++) {
<a class="jxr_linenumber" name="638" href="#638">638</a> <strong class="jxr_keyword">for</strong> (<strong class="jxr_keyword">int</strong> j = 0; j < QUALSIZE; j++) {
<a class="jxr_linenumber" name="639" href="#639">639</a> <strong class="jxr_keyword">if</strong> (i % 2 == 0) {
<a class="jxr_linenumber" name="640" href="#640">640</a> memstore.add(makeKV(i, j));
<a class="jxr_linenumber" name="641" href="#641">641</a> } <strong class="jxr_keyword">else</strong> {
<a class="jxr_linenumber" name="642" href="#642">642</a> writers[(i + j) % writers.length].append(makeKV(i, j));
<a class="jxr_linenumber" name="643" href="#643">643</a> }
<a class="jxr_linenumber" name="644" href="#644">644</a> }
<a class="jxr_linenumber" name="645" href="#645">645</a> }
<a class="jxr_linenumber" name="646" href="#646">646</a> } <strong class="jxr_keyword">finally</strong> {
<a class="jxr_linenumber" name="647" href="#647">647</a> <strong class="jxr_keyword">for</strong> (<strong class="jxr_keyword">int</strong> i = 0; i < writers.length; i++) {
<a class="jxr_linenumber" name="648" href="#648">648</a> writers[i].close();
<a class="jxr_linenumber" name="649" href="#649">649</a> }
<a class="jxr_linenumber" name="650" href="#650">650</a> }
<a class="jxr_linenumber" name="651" href="#651">651</a> }
<a class="jxr_linenumber" name="652" href="#652">652</a>
<a class="jxr_linenumber" name="653" href="#653">653</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">static</strong> <strong class="jxr_keyword">void</strong> writeStoreFile(<strong class="jxr_keyword">final</strong> StoreFile.Writer writer)
<a class="jxr_linenumber" name="654" href="#654">654</a> <strong class="jxr_keyword">throws</strong> IOException {
<a class="jxr_linenumber" name="655" href="#655">655</a> <strong class="jxr_keyword">try</strong> {
<a class="jxr_linenumber" name="656" href="#656">656</a> <strong class="jxr_keyword">for</strong> (<strong class="jxr_keyword">int</strong> i = 0; i < ROWSIZE; i++) {
<a class="jxr_linenumber" name="657" href="#657">657</a> <strong class="jxr_keyword">for</strong> (<strong class="jxr_keyword">int</strong> j = 0; j < QUALSIZE; j++) {
<a class="jxr_linenumber" name="658" href="#658">658</a> writer.append(makeKV(i, j));
<a class="jxr_linenumber" name="659" href="#659">659</a> }
<a class="jxr_linenumber" name="660" href="#660">660</a> }
<a class="jxr_linenumber" name="661" href="#661">661</a> } <strong class="jxr_keyword">finally</strong> {
<a class="jxr_linenumber" name="662" href="#662">662</a> writer.close();
<a class="jxr_linenumber" name="663" href="#663">663</a> }
<a class="jxr_linenumber" name="664" href="#664">664</a> }
<a class="jxr_linenumber" name="665" href="#665">665</a>
<a class="jxr_linenumber" name="666" href="#666">666</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">static</strong> <strong class="jxr_keyword">void</strong> writeMemstore(MemStore memstore) <strong class="jxr_keyword">throws</strong> IOException {
<a class="jxr_linenumber" name="667" href="#667">667</a> <em class="jxr_comment">// Add half of the keyvalues to memstore</em>
<a class="jxr_linenumber" name="668" href="#668">668</a> <strong class="jxr_keyword">for</strong> (<strong class="jxr_keyword">int</strong> i = 0; i < ROWSIZE; i++) {
<a class="jxr_linenumber" name="669" href="#669">669</a> <strong class="jxr_keyword">for</strong> (<strong class="jxr_keyword">int</strong> j = 0; j < QUALSIZE; j++) {
<a class="jxr_linenumber" name="670" href="#670">670</a> <strong class="jxr_keyword">if</strong> ((i + j) % 2 == 0) {
<a class="jxr_linenumber" name="671" href="#671">671</a> memstore.add(makeKV(i, j));
<a class="jxr_linenumber" name="672" href="#672">672</a> }
<a class="jxr_linenumber" name="673" href="#673">673</a> }
<a class="jxr_linenumber" name="674" href="#674">674</a> }
<a class="jxr_linenumber" name="675" href="#675">675</a> memstore.snapshot();
<a class="jxr_linenumber" name="676" href="#676">676</a> <em class="jxr_comment">// Add another half of the keyvalues to snapshot</em>
<a class="jxr_linenumber" name="677" href="#677">677</a> <strong class="jxr_keyword">for</strong> (<strong class="jxr_keyword">int</strong> i = 0; i < ROWSIZE; i++) {
<a class="jxr_linenumber" name="678" href="#678">678</a> <strong class="jxr_keyword">for</strong> (<strong class="jxr_keyword">int</strong> j = 0; j < QUALSIZE; j++) {
<a class="jxr_linenumber" name="679" href="#679">679</a> <strong class="jxr_keyword">if</strong> ((i + j) % 2 == 1) {
<a class="jxr_linenumber" name="680" href="#680">680</a> memstore.add(makeKV(i, j));
<a class="jxr_linenumber" name="681" href="#681">681</a> }
<a class="jxr_linenumber" name="682" href="#682">682</a> }
<a class="jxr_linenumber" name="683" href="#683">683</a> }
<a class="jxr_linenumber" name="684" href="#684">684</a> }
<a class="jxr_linenumber" name="685" href="#685">685</a>
<a class="jxr_linenumber" name="686" href="#686">686</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">static</strong> KeyValue makeKV(<strong class="jxr_keyword">int</strong> rowNum, <strong class="jxr_keyword">int</strong> cqNum) {
<a class="jxr_linenumber" name="687" href="#687">687</a> <strong class="jxr_keyword">return</strong> makeKV(rowNum, cqNum, FAMILYNAME);
<a class="jxr_linenumber" name="688" href="#688">688</a> }
<a class="jxr_linenumber" name="689" href="#689">689</a>
<a class="jxr_linenumber" name="690" href="#690">690</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">static</strong> KeyValue makeKV(<strong class="jxr_keyword">int</strong> rowNum, <strong class="jxr_keyword">int</strong> cqNum, byte[] familyName) {
<a class="jxr_linenumber" name="691" href="#691">691</a> KeyValue kv = <strong class="jxr_keyword">new</strong> KeyValue(ROWS[rowNum], familyName, QUALS[cqNum], TS,
<a class="jxr_linenumber" name="692" href="#692">692</a> VALUES[rowNum % VALUESIZE]);
<a class="jxr_linenumber" name="693" href="#693">693</a> kv.setMvccVersion(makeMVCC(rowNum, cqNum));
<a class="jxr_linenumber" name="694" href="#694">694</a> <strong class="jxr_keyword">return</strong> kv;
<a class="jxr_linenumber" name="695" href="#695">695</a> }
<a class="jxr_linenumber" name="696" href="#696">696</a>
<a class="jxr_linenumber" name="697" href="#697">697</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">static</strong> <strong class="jxr_keyword">long</strong> makeMVCC(<strong class="jxr_keyword">int</strong> rowNum, <strong class="jxr_keyword">int</strong> cqNum) {
<a class="jxr_linenumber" name="698" href="#698">698</a> <strong class="jxr_keyword">return</strong> (rowNum + cqNum) % (MAXMVCC + 1);
<a class="jxr_linenumber" name="699" href="#699">699</a> }
<a class="jxr_linenumber" name="700" href="#700">700</a>
<a class="jxr_linenumber" name="701" href="#701">701</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">static</strong> byte[][] makeN(byte[] base, <strong class="jxr_keyword">int</strong> n) {
<a class="jxr_linenumber" name="702" href="#702">702</a> byte[][] ret = <strong class="jxr_keyword">new</strong> byte[n][];
<a class="jxr_linenumber" name="703" href="#703">703</a> <strong class="jxr_keyword">for</strong> (<strong class="jxr_keyword">int</strong> i = 0; i < n; i++) {
<a class="jxr_linenumber" name="704" href="#704">704</a> ret[i] = Bytes.add(base, Bytes.toBytes(String.format(<span class="jxr_string">"%04d"</span>, i)));
<a class="jxr_linenumber" name="705" href="#705">705</a> }
<a class="jxr_linenumber" name="706" href="#706">706</a> <strong class="jxr_keyword">return</strong> ret;
<a class="jxr_linenumber" name="707" href="#707">707</a> }
<a class="jxr_linenumber" name="708" href="#708">708</a> }
</pre>
<hr/><div id="footer">This page was automatically generated by <a href="http://maven.apache.org/">Maven</a></div></body>
</html>
| Java |
// Copyright 2021 The Oppia 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.
/**
* @fileoverview Component for delete account modal.
*/
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
import { UserService } from 'services/user.service';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'oppia-delete-account-modal',
templateUrl: './delete-account-modal.component.html'
})
export class DeleteAccountModalComponent implements OnInit {
expectedUsername: string;
username: string;
constructor(
private userService: UserService,
private ngbActiveModal: NgbActiveModal,
) {}
ngOnInit(): void {
this.expectedUsername = null;
this.userService.getUserInfoAsync().then((userInfo) => {
this.expectedUsername = userInfo.getUsername();
});
}
isValid(): boolean {
return this.username === this.expectedUsername;
}
confirm(): void {
this.ngbActiveModal.close();
}
cancel(): void {
this.ngbActiveModal.dismiss();
}
}
| Java |
/*
* Javolution - Java(TM) Solution for Real-Time and Embedded Systems
* Copyright (C) 2007 - Javolution (http://javolution.org/)
* All rights reserved.
*
* Permission to use, copy, modify, and distribute this software is
* freely granted, provided that this notice is preserved.
*/
package javolution.xml;
import java.io.Serializable;
/**
* <p> This interface identifies classes supporting XML serialization
* (XML serialization is still possible for classes not implementing this
* interface through dynamic {@link XMLBinding} though).</p>
*
* <p> Typically, classes implementing this interface have a protected static
* {@link XMLFormat} holding their default XML representation.
* For example:[code]
* public final class Complex implements XMLSerializable {
*
* // Use the cartesien form for the default XML representation.
* protected static final XMLFormat<Complex> XML = new XMLFormat<Complex>(Complex.class) {
* public Complex newInstance(Class<Complex> cls, InputElement xml) throws XMLStreamException {
* return Complex.valueOf(xml.getAttribute("real", 0.0),
* xml.getAttribute("imaginary", 0.0));
* }
* public void write(Complex complex, OutputElement xml) throws XMLStreamException {
* xml.setAttribute("real", complex.getReal());
* xml.setAttribute("imaginary", complex.getImaginary());
* }
* public void read(InputElement xml, Complex complex) {
* // Immutable, deserialization occurs at creation, ref. newIntance(...)
* }
* };
* ...
* }[/code]</p>
*
* @author <a href="mailto:[email protected]">Jean-Marie Dautelle</a>
* @version 4.2, April 15, 2007
*/
public interface XMLSerializable extends Serializable {
// No method. Tagging interface.
}
| Java |
# Internship
| Java |
# Copyright 2008-2013 Software freedom conservancy
#
# 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.
"""WebElement implementation."""
import hashlib
import os
import zipfile
try:
from StringIO import StringIO as IOStream
except ImportError: # 3+
from io import BytesIO as IOStream
import base64
from .command import Command
from selenium.common.exceptions import WebDriverException
from selenium.common.exceptions import InvalidSelectorException
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
try:
str = basestring
except NameError:
pass
class WebElement(object):
"""Represents an HTML element.
Generally, all interesting operations to do with interacting with a page
will be performed through this interface."""
def __init__(self, parent, id_):
self._parent = parent
self._id = id_
@property
def tag_name(self):
"""Gets this element's tagName property."""
return self._execute(Command.GET_ELEMENT_TAG_NAME)['value']
@property
def text(self):
"""Gets the text of the element."""
return self._execute(Command.GET_ELEMENT_TEXT)['value']
def click(self):
"""Clicks the element."""
self._execute(Command.CLICK_ELEMENT)
def submit(self):
"""Submits a form."""
self._execute(Command.SUBMIT_ELEMENT)
def clear(self):
"""Clears the text if it's a text entry element."""
self._execute(Command.CLEAR_ELEMENT)
def get_attribute(self, name):
"""Gets the attribute value.
:Args:
- name - name of the attribute property to retieve.
Example::
# Check if the 'active' css class is applied to an element.
is_active = "active" in target_element.get_attribute("class")
"""
resp = self._execute(Command.GET_ELEMENT_ATTRIBUTE, {'name': name})
attributeValue = ''
if resp['value'] is None:
attributeValue = None
else:
attributeValue = resp['value']
if name != 'value' and attributeValue.lower() in ('true', 'false'):
attributeValue = attributeValue.lower()
return attributeValue
def is_selected(self):
"""Whether the element is selected.
Can be used to check if a checkbox or radio button is selected.
"""
return self._execute(Command.IS_ELEMENT_SELECTED)['value']
def is_enabled(self):
"""Whether the element is enabled."""
return self._execute(Command.IS_ELEMENT_ENABLED)['value']
def find_element_by_id(self, id_):
"""Finds element within the child elements of this element.
:Args:
- id_ - ID of child element to locate.
"""
return self.find_element(by=By.ID, value=id_)
def find_elements_by_id(self, id_):
"""Finds a list of elements within the children of this element
with the matching ID.
:Args:
- id_ - Id of child element to find.
"""
return self.find_elements(by=By.ID, value=id_)
def find_element_by_name(self, name):
"""Find element with in this element's children by name.
:Args:
- name - name property of the element to find.
"""
return self.find_element(by=By.NAME, value=name)
def find_elements_by_name(self, name):
"""Finds a list of elements with in this element's children by name.
:Args:
- name - name property to search for.
"""
return self.find_elements(by=By.NAME, value=name)
def find_element_by_link_text(self, link_text):
"""Finds element with in this element's children by visible link text.
:Args:
- link_text - Link text string to search for.
"""
return self.find_element(by=By.LINK_TEXT, value=link_text)
def find_elements_by_link_text(self, link_text):
"""Finds a list of elements with in this element's children by visible link text.
:Args:
- link_text - Link text string to search for.
"""
return self.find_elements(by=By.LINK_TEXT, value=link_text)
def find_element_by_partial_link_text(self, link_text):
"""Finds element with in this element's children by parial visible link text.
:Args:
- link_text - Link text string to search for.
"""
return self.find_element(by=By.PARTIAL_LINK_TEXT, value=link_text)
def find_elements_by_partial_link_text(self, link_text):
"""Finds a list of elements with in this element's children by link text.
:Args:
- link_text - Link text string to search for.
"""
return self.find_elements(by=By.PARTIAL_LINK_TEXT, value=link_text)
def find_element_by_tag_name(self, name):
"""Finds element with in this element's children by tag name.
:Args:
- name - name of html tag (eg: h1, a, span)
"""
return self.find_element(by=By.TAG_NAME, value=name)
def find_elements_by_tag_name(self, name):
"""Finds a list of elements with in this element's children by tag name.
:Args:
- name - name of html tag (eg: h1, a, span)
"""
return self.find_elements(by=By.TAG_NAME, value=name)
def find_element_by_xpath(self, xpath):
"""Finds element by xpath.
:Args:
xpath - xpath of element to locate. "//input[@class='myelement']"
Note: The base path will be relative to this element's location.
This will select the first link under this element.::
myelement.find_elements_by_xpath(".//a")
However, this will select the first link on the page.
myelement.find_elements_by_xpath("//a")
"""
return self.find_element(by=By.XPATH, value=xpath)
def find_elements_by_xpath(self, xpath):
"""Finds elements within the elements by xpath.
:Args:
- xpath - xpath locator string.
Note: The base path will be relative to this element's location.
This will select all links under this element.::
myelement.find_elements_by_xpath(".//a")
However, this will select all links in the page itself.
myelement.find_elements_by_xpath("//a")
"""
return self.find_elements(by=By.XPATH, value=xpath)
def find_element_by_class_name(self, name):
"""Finds an element within this element's children by their class name.
:Args:
- name - class name to search on.
"""
return self.find_element(by=By.CLASS_NAME, value=name)
def find_elements_by_class_name(self, name):
"""Finds a list of elements within children of this element by their class name.
:Args:
- name - class name to search on.
"""
return self.find_elements(by=By.CLASS_NAME, value=name)
def find_element_by_css_selector(self, css_selector):
"""Find and return an element that's a child of this element by CSS selector.
:Args:
- css_selector - CSS selctor string, ex: 'a.nav#home'
"""
return self.find_element(by=By.CSS_SELECTOR, value=css_selector)
def find_elements_by_css_selector(self, css_selector):
"""Find and return list of multiple elements within the children of this
element by CSS selector.
:Args:
- css_selector - CSS selctor string, ex: 'a.nav#home'
"""
return self.find_elements(by=By.CSS_SELECTOR, value=css_selector)
def send_keys(self, *value):
"""Simulates typing into the element.
:Args:
- value - A string for typing, or setting form fields. For setting
file inputs, this could be a local file path.
Use this to send simple key events or to fill out form fields::
form_textfield = driver.find_element_by_name('username')
form_textfield.send_keys("admin")
This can also be used to set file inputs.::
file_input = driver.find_element_by_name('profilePic')
file_input.send_keys("path/to/profilepic.gif")
# Generally it's better to wrap the file path in one of the methods
# in os.path to return the actual path to support cross OS testing.
# file_input.send_keys(os.path.abspath("path/to/profilepic.gif"))
"""
# transfer file to another machine only if remote driver is used
# the same behaviour as for java binding
if self.parent._is_remote:
local_file = LocalFileDetector.is_local_file(*value)
if local_file is not None:
value = self._upload(local_file)
typing = []
for val in value:
if isinstance(val, Keys):
typing.append(val)
elif isinstance(val, int):
val = val.__str__()
for i in range(len(val)):
typing.append(val[i])
else:
for i in range(len(val)):
typing.append(val[i])
self._execute(Command.SEND_KEYS_TO_ELEMENT, {'value': typing})
# RenderedWebElement Items
def is_displayed(self):
"""Whether the element would be visible to a user
"""
return self._execute(Command.IS_ELEMENT_DISPLAYED)['value']
@property
def location_once_scrolled_into_view(self):
"""CONSIDERED LIABLE TO CHANGE WITHOUT WARNING. Use this to discover where on the screen an
element is so that we can click it. This method should cause the element to be scrolled
into view.
Returns the top lefthand corner location on the screen, or None if the element is not visible"""
return self._execute(Command.GET_ELEMENT_LOCATION_ONCE_SCROLLED_INTO_VIEW)['value']
@property
def size(self):
""" Returns the size of the element """
size = self._execute(Command.GET_ELEMENT_SIZE)['value']
new_size = {}
new_size["height"] = size["height"]
new_size["width"] = size["width"]
return new_size
def value_of_css_property(self, property_name):
""" Returns the value of a CSS property """
return self._execute(Command.GET_ELEMENT_VALUE_OF_CSS_PROPERTY,
{'propertyName': property_name})['value']
@property
def location(self):
""" Returns the location of the element in the renderable canvas"""
old_loc = self._execute(Command.GET_ELEMENT_LOCATION)['value']
new_loc = {"x": old_loc['x'],
"y": old_loc['y']}
return new_loc
@property
def rect(self):
""" Returns a dictionary with the size and location of the element"""
return self._execute(Command.GET_ELEMENT_RECT)['value']
@property
def parent(self):
""" Returns parent element is available. """
return self._parent
@property
def id(self):
""" Returns internal id used by selenium.
This is mainly for internal use. Simple use cases such as checking if 2 webelements
refer to the same element, can be done using '=='::
if element1 == element2:
print("These 2 are equal")
"""
return self._id
def __eq__(self, element):
if self._id == element.id:
return True
else:
return self._execute(Command.ELEMENT_EQUALS, {'other': element.id})['value']
# Private Methods
def _execute(self, command, params=None):
"""Executes a command against the underlying HTML element.
Args:
command: The name of the command to _execute as a string.
params: A dictionary of named parameters to send with the command.
Returns:
The command's JSON response loaded into a dictionary object.
"""
if not params:
params = {}
params['id'] = self._id
return self._parent.execute(command, params)
def find_element(self, by=By.ID, value=None):
if not By.is_valid(by) or not isinstance(value, str):
raise InvalidSelectorException("Invalid locator values passed in")
return self._execute(Command.FIND_CHILD_ELEMENT,
{"using": by, "value": value})['value']
def find_elements(self, by=By.ID, value=None):
if not By.is_valid(by) or not isinstance(value, str):
raise InvalidSelectorException("Invalid locator values passed in")
return self._execute(Command.FIND_CHILD_ELEMENTS,
{"using": by, "value": value})['value']
def __hash__(self):
return int(hashlib.md5(self._id.encode('utf-8')).hexdigest(), 16)
def _upload(self, filename):
fp = IOStream()
zipped = zipfile.ZipFile(fp, 'w', zipfile.ZIP_DEFLATED)
zipped.write(filename, os.path.split(filename)[1])
zipped.close()
content = base64.encodestring(fp.getvalue())
if not isinstance(content, str):
content = content.decode('utf-8')
try:
return self._execute(Command.UPLOAD_FILE,
{'file': content})['value']
except WebDriverException as e:
if "Unrecognized command: POST" in e.__str__():
return filename
elif "Command not found: POST " in e.__str__():
return filename
elif '{"status":405,"value":["GET","HEAD","DELETE"]}' in e.__str__():
return filename
else:
raise e
class LocalFileDetector(object):
@classmethod
def is_local_file(cls, *keys):
file_path = ''
typing = []
for val in keys:
if isinstance(val, Keys):
typing.append(val)
elif isinstance(val, int):
val = val.__str__()
for i in range(len(val)):
typing.append(val[i])
else:
for i in range(len(val)):
typing.append(val[i])
file_path = ''.join(typing)
if file_path is '':
return None
try:
if os.path.isfile(file_path):
return file_path
except:
pass
return None
| Java |
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/location/model/SearchForTextResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace LocationService
{
namespace Model
{
SearchForTextResult::SearchForTextResult() :
m_placeHasBeenSet(false)
{
}
SearchForTextResult::SearchForTextResult(JsonView jsonValue) :
m_placeHasBeenSet(false)
{
*this = jsonValue;
}
SearchForTextResult& SearchForTextResult::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("Place"))
{
m_place = jsonValue.GetObject("Place");
m_placeHasBeenSet = true;
}
return *this;
}
JsonValue SearchForTextResult::Jsonize() const
{
JsonValue payload;
if(m_placeHasBeenSet)
{
payload.WithObject("Place", m_place.Jsonize());
}
return payload;
}
} // namespace Model
} // namespace LocationService
} // namespace Aws
| Java |
/*
* $Id$
* Copyright (C) 2008 AIST, National Institute of Advanced Industrial Science and Technology
*/
/*
* took from Ruby. Thank you, Ruby!
*/
int endian()
{
static int init = 0;
static int endian = 0;
char *p;
if (init) return endian;
init = 1;
p = &init;
return endian = p[0]?1:0;
}
| Java |
package com.siyeh.ig.assignment;
import com.IGInspectionTestCase;
public class AssignmentToMethodParameterInspectionTest extends IGInspectionTestCase {
public void test() throws Exception {
final AssignmentToMethodParameterInspection inspection =
new AssignmentToMethodParameterInspection();
inspection.ignoreTransformationOfOriginalParameter = true;
doTest("com/siyeh/igtest/assignment/method_parameter",
inspection);
}
} | Java |
"""This component provides support to the Ring Door Bell camera."""
import asyncio
from datetime import timedelta
import logging
import voluptuous as vol
from homeassistant.components.camera import PLATFORM_SCHEMA, Camera
from homeassistant.components.ffmpeg import DATA_FFMPEG
from homeassistant.const import ATTR_ATTRIBUTION, CONF_SCAN_INTERVAL
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.aiohttp_client import async_aiohttp_proxy_stream
from homeassistant.util import dt as dt_util
from . import ATTRIBUTION, DATA_RING, NOTIFICATION_ID
CONF_FFMPEG_ARGUMENTS = 'ffmpeg_arguments'
FORCE_REFRESH_INTERVAL = timedelta(minutes=45)
_LOGGER = logging.getLogger(__name__)
NOTIFICATION_TITLE = 'Ring Camera Setup'
SCAN_INTERVAL = timedelta(seconds=90)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_FFMPEG_ARGUMENTS): cv.string,
vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period,
})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up a Ring Door Bell and StickUp Camera."""
ring = hass.data[DATA_RING]
cams = []
cams_no_plan = []
for camera in ring.doorbells:
if camera.has_subscription:
cams.append(RingCam(hass, camera, config))
else:
cams_no_plan.append(camera)
for camera in ring.stickup_cams:
if camera.has_subscription:
cams.append(RingCam(hass, camera, config))
else:
cams_no_plan.append(camera)
# show notification for all cameras without an active subscription
if cams_no_plan:
cameras = str(', '.join([camera.name for camera in cams_no_plan]))
err_msg = '''A Ring Protect Plan is required for the''' \
''' following cameras: {}.'''.format(cameras)
_LOGGER.error(err_msg)
hass.components.persistent_notification.create(
'Error: {}<br />'
'You will need to restart hass after fixing.'
''.format(err_msg),
title=NOTIFICATION_TITLE,
notification_id=NOTIFICATION_ID)
add_entities(cams, True)
return True
class RingCam(Camera):
"""An implementation of a Ring Door Bell camera."""
def __init__(self, hass, camera, device_info):
"""Initialize a Ring Door Bell camera."""
super(RingCam, self).__init__()
self._camera = camera
self._hass = hass
self._name = self._camera.name
self._ffmpeg = hass.data[DATA_FFMPEG]
self._ffmpeg_arguments = device_info.get(CONF_FFMPEG_ARGUMENTS)
self._last_video_id = self._camera.last_recording_id
self._video_url = self._camera.recording_url(self._last_video_id)
self._utcnow = dt_util.utcnow()
self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow
@property
def name(self):
"""Return the name of this camera."""
return self._name
@property
def unique_id(self):
"""Return a unique ID."""
return self._camera.id
@property
def device_state_attributes(self):
"""Return the state attributes."""
return {
ATTR_ATTRIBUTION: ATTRIBUTION,
'device_id': self._camera.id,
'firmware': self._camera.firmware,
'kind': self._camera.kind,
'timezone': self._camera.timezone,
'type': self._camera.family,
'video_url': self._video_url,
}
async def async_camera_image(self):
"""Return a still image response from the camera."""
from haffmpeg.tools import ImageFrame, IMAGE_JPEG
ffmpeg = ImageFrame(self._ffmpeg.binary, loop=self.hass.loop)
if self._video_url is None:
return
image = await asyncio.shield(ffmpeg.get_image(
self._video_url, output_format=IMAGE_JPEG,
extra_cmd=self._ffmpeg_arguments))
return image
async def handle_async_mjpeg_stream(self, request):
"""Generate an HTTP MJPEG stream from the camera."""
from haffmpeg.camera import CameraMjpeg
if self._video_url is None:
return
stream = CameraMjpeg(self._ffmpeg.binary, loop=self.hass.loop)
await stream.open_camera(
self._video_url, extra_cmd=self._ffmpeg_arguments)
try:
stream_reader = await stream.get_reader()
return await async_aiohttp_proxy_stream(
self.hass, request, stream_reader,
self._ffmpeg.ffmpeg_stream_content_type)
finally:
await stream.close()
@property
def should_poll(self):
"""Update the image periodically."""
return True
def update(self):
"""Update camera entity and refresh attributes."""
_LOGGER.debug("Checking if Ring DoorBell needs to refresh video_url")
self._camera.update()
self._utcnow = dt_util.utcnow()
try:
last_event = self._camera.history(limit=1)[0]
except (IndexError, TypeError):
return
last_recording_id = last_event['id']
video_status = last_event['recording']['status']
if video_status == 'ready' and \
(self._last_video_id != last_recording_id or
self._utcnow >= self._expires_at):
video_url = self._camera.recording_url(last_recording_id)
if video_url:
_LOGGER.info("Ring DoorBell properties refreshed")
# update attributes if new video or if URL has expired
self._last_video_id = last_recording_id
self._video_url = video_url
self._expires_at = FORCE_REFRESH_INTERVAL + self._utcnow
| Java |
/**
* Copyright 2014
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
* @project loon
* @author cping
* @email:[email protected]
* @version 0.4.2
*/
package loon.core.graphics.component.table;
import loon.core.graphics.LComponent;
import loon.core.graphics.LContainer;
import loon.core.graphics.device.LColor;
import loon.core.graphics.opengl.GLEx;
import loon.core.graphics.opengl.LTexture;
import loon.utils.collection.ArrayList;
public class TableLayout extends LContainer {
private TableLayoutRow[] tableRows;
private boolean grid = true;
public TableLayout(int x, int y, int w, int h) {
this(x, y, w, h, 4, 4);
}
public TableLayout(int x, int y, int w, int h, int cols, int rows) {
super(x, y, w, h);
prepareTable(cols, rows);
}
protected void renderComponents(GLEx g) {
for (int i = 0; i < getComponentCount(); i++) {
getComponents()[i].createUI(g);
}
if (grid) {
for (int i = 0; i < tableRows.length; i++) {
tableRows[i].paint(g);
}
g.drawRect(getX(), getY(), getWidth(), getHeight(), LColor.gray);
}
}
@Override
public void createUI(GLEx g, int x, int y, LComponent component,
LTexture[] buttonImage) {
}
private void prepareTable(int cols, int rows) {
tableRows = new TableLayoutRow[rows];
if (rows > 0 && cols > 0) {
int rowHeight = getHeight() / rows;
for (int i = 0; i < rows; i++) {
tableRows[i] = new TableLayoutRow(x(), y() + (i * rowHeight),
getWidth(), rowHeight, cols);
}
}
}
public void setComponent(LComponent component, int col, int row) {
add(component);
remove(tableRows[row].getComponent(col));
tableRows[row].setComponent(component, col);
}
public void removeComponent(int col, int row) {
remove(tableRows[row].getComponent(col));
tableRows[row].setComponent(null, col);
}
public void addRow(int column, int position) {
ArrayList newRows = new ArrayList();
int newRowHeight = getHeight() / (tableRows.length + 1);
if (canAddRow(newRowHeight)) {
if (position == 0) {
newRows.add(new TableLayoutRow(x(), y(), getWidth(),
newRowHeight, column));
}
for (int i = 0; i < tableRows.length; i++) {
if (i == position && position != 0) {
newRows.add(new TableLayoutRow(x(), y(), getWidth(),
newRowHeight, column));
}
newRows.add(tableRows[i]);
}
if (position == tableRows.length && position != 0) {
newRows.add(new TableLayoutRow(x(), y(), getWidth(),
newRowHeight, column));
}
for (int i = 0; i < newRows.size(); i++) {
((TableLayoutRow) newRows.get(i))
.setY(y() + (i * newRowHeight));
((TableLayoutRow) newRows.get(i)).setHeight(newRowHeight);
}
tableRows = (TableLayoutRow[]) newRows.toArray();
}
}
public void addRow(int column) {
addRow(column, tableRows.length);
}
private boolean canAddRow(int newRowHeight) {
if (tableRows != null && tableRows.length > 0) {
return tableRows[0].canSetHeight(newRowHeight);
}
return true;
}
public boolean setColumnWidth(int width, int col, int row) {
return tableRows[row].setColumnWidth(width, col);
}
public boolean setColumnHeight(int height, int row) {
if (!tableRows[row].canSetHeight(height)) {
return false;
}
tableRows[row].setHeight(height);
return true;
}
public void setMargin(int leftMargin, int rightMargin, int topMargin,
int bottomMargin, int col, int row) {
tableRows[row].getColumn(col).setMargin(leftMargin, rightMargin,
topMargin, bottomMargin);
}
public void setAlignment(int horizontalAlignment, int verticalAlignment,
int col, int row) {
tableRows[row].getColumn(col).setHorizontalAlignment(
horizontalAlignment);
tableRows[row].getColumn(col).setVerticalAlignment(verticalAlignment);
}
public int getRows() {
return tableRows.length;
}
public int getColumns(int row) {
return tableRows[row].getCoulumnSize();
}
@Override
public void setWidth(int width) {
boolean couldShrink = true;
for (int i = 0; i < tableRows.length; i++) {
if (!tableRows[i].setWidth(width)) {
couldShrink = false;
}
}
if (couldShrink) {
super.setWidth(width);
}
}
@Override
public void setHeight(int height) {
super.setHeight(height);
for (int i = 0; i < tableRows.length; i++) {
tableRows[i].setHeight(height);
}
}
public boolean isGrid() {
return grid;
}
public void setGrid(boolean grid) {
this.grid = grid;
}
@Override
public String getUIName() {
return "TableLayout";
}
}
| Java |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.debugger.engine.evaluation.expression;
import com.intellij.debugger.DebuggerBundle;
import com.intellij.debugger.engine.evaluation.EvaluateException;
import com.intellij.debugger.engine.evaluation.EvaluateExceptionUtil;
import com.intellij.debugger.engine.evaluation.EvaluateRuntimeException;
import com.intellij.debugger.jdi.VirtualMachineProxyImpl;
import com.intellij.openapi.diagnostic.Logger;
import java.util.HashMap;
import com.sun.jdi.Value;
import java.util.Map;
/**
* @author lex
*/
public class CodeFragmentEvaluator extends BlockStatementEvaluator{
private static final Logger LOG = Logger.getInstance("#com.intellij.debugger.engine.evaluation.expression.CodeFragmentEvaluator");
private final CodeFragmentEvaluator myParentFragmentEvaluator;
private final Map<String, Object> mySyntheticLocals = new HashMap<>();
public CodeFragmentEvaluator(CodeFragmentEvaluator parentFragmentEvaluator) {
super(null);
myParentFragmentEvaluator = parentFragmentEvaluator;
}
public void setStatements(Evaluator[] evaluators) {
myStatements = evaluators;
}
public Value getValue(String localName, VirtualMachineProxyImpl vm) throws EvaluateException {
if(!mySyntheticLocals.containsKey(localName)) {
if(myParentFragmentEvaluator != null){
return myParentFragmentEvaluator.getValue(localName, vm);
} else {
throw EvaluateExceptionUtil.createEvaluateException(DebuggerBundle.message("evaluation.error.variable.not.declared", localName));
}
}
Object value = mySyntheticLocals.get(localName);
if(value instanceof Value) {
return (Value)value;
}
else if(value == null) {
return null;
}
else if(value instanceof Boolean) {
return vm.mirrorOf(((Boolean)value).booleanValue());
}
else if(value instanceof Byte) {
return vm.mirrorOf(((Byte)value).byteValue());
}
else if(value instanceof Character) {
return vm.mirrorOf(((Character)value).charValue());
}
else if(value instanceof Short) {
return vm.mirrorOf(((Short)value).shortValue());
}
else if(value instanceof Integer) {
return vm.mirrorOf(((Integer)value).intValue());
}
else if(value instanceof Long) {
return vm.mirrorOf(((Long)value).longValue());
}
else if(value instanceof Float) {
return vm.mirrorOf(((Float)value).floatValue());
}
else if(value instanceof Double) {
return vm.mirrorOf(((Double)value).doubleValue());
}
else if(value instanceof String) {
return vm.mirrorOf((String)value);
}
else {
LOG.error("unknown default initializer type " + value.getClass().getName());
return null;
}
}
private boolean hasValue(String localName) {
if(!mySyntheticLocals.containsKey(localName)) {
if(myParentFragmentEvaluator != null){
return myParentFragmentEvaluator.hasValue(localName);
} else {
return false;
}
} else {
return true;
}
}
public void setInitialValue(String localName, Object value) {
LOG.assertTrue(!(value instanceof Value), "use setValue for jdi values");
if(hasValue(localName)) {
throw new EvaluateRuntimeException(
EvaluateExceptionUtil.createEvaluateException(DebuggerBundle.message("evaluation.error.variable.already.declared", localName)));
}
mySyntheticLocals.put(localName, value);
}
public void setValue(String localName, Value value) throws EvaluateException {
if(!mySyntheticLocals.containsKey(localName)) {
if(myParentFragmentEvaluator != null){
myParentFragmentEvaluator.setValue(localName, value);
} else {
throw EvaluateExceptionUtil.createEvaluateException(DebuggerBundle.message("evaluation.error.variable.not.declared", localName));
}
}
else {
mySyntheticLocals.put(localName, value);
}
}
}
| Java |
/*Stats*/
.bar-chart-grids { margin:150px auto; max-width:640px;}
.fabo-chart {
border-right: 1px;
margin: 2em 0 0 0;
}
.fabo-chart::after {
content: " ";
display: table;
clear: both; }
.fabo-chart .fabo-point {
height: 400px;
display: inline-block;
float: left;
box-sizing: border-box;
padding-left: 0px;
ovefabolow: hidden; }
.fabo-chart .fabo-point .fabo-point-inner {
height: 100%;
position: relative;
ovefabolow: hidden;
background: #f4f6f7; }
.fabo-chart .fabo-point
.fabo-value-text {
width: 100%;
text-align: center;
z-index: 100;
color: #ffffff;
font-size: 18px;
font-weight: 600;
position: absolute;
left: 0;
right: 0;
bottom: 18px; }
.fabo-chart .fabo-point
.fabo-value-label {
width: 100%;
text-align: center;
z-index: 100;
color: #95a5b3;
font-size: 12px;
font-weight: 700;
position: absolute;
left: 0;
right: 0;
top: 18px; }
.fabo-chart .fabo-point .fabo-value {
box-sizing: content-box;
width: 0;
height: 100px;
border-top: 0 solid transparent;
border-right: 0 solid #7b82ff;
border-bottom: 0 solid transparent;
border-left: 0px solid #7b82ff;
transition: height 200ms;
position: absolute;
bottom: 0;
-webkit-animation: chart-height 200ms;
animation: chart-height 200ms; }
.fabo-chart .fabo-point .fabo-value.hide {
display: none;
height: 0 !important; }
.fabo-chart .fabo-point .fabo-value.hide-border {
border-top-width: 0 !important; }
@-webkit-keyframes chart-height {
0% {
height: 0; } }
@keyframes chart-height {
0% {
height: 0; } }
/*# sourceMappingURL=chart.css.map */ | Java |
#include "extensions/common/tap/tap_config_base.h"
#include "envoy/config/tap/v3/common.pb.h"
#include "envoy/data/tap/v3/common.pb.h"
#include "envoy/data/tap/v3/wrapper.pb.h"
#include "common/common/assert.h"
#include "common/common/fmt.h"
#include "common/config/version_converter.h"
#include "common/protobuf/utility.h"
#include "extensions/common/matcher/matcher.h"
#include "absl/container/fixed_array.h"
namespace Envoy {
namespace Extensions {
namespace Common {
namespace Tap {
using namespace Matcher;
bool Utility::addBufferToProtoBytes(envoy::data::tap::v3::Body& output_body,
uint32_t max_buffered_bytes, const Buffer::Instance& data,
uint32_t buffer_start_offset, uint32_t buffer_length_to_copy) {
// TODO(mattklein123): Figure out if we can use the buffer API here directly in some way. This is
// is not trivial if we want to avoid extra copies since we end up appending to the existing
// protobuf string.
// Note that max_buffered_bytes is assumed to include any data already contained in output_bytes.
// This is to account for callers that may be tracking this over multiple body objects.
ASSERT(buffer_start_offset + buffer_length_to_copy <= data.length());
const uint32_t final_bytes_to_copy = std::min(max_buffered_bytes, buffer_length_to_copy);
Buffer::RawSliceVector slices = data.getRawSlices();
trimSlices(slices, buffer_start_offset, final_bytes_to_copy);
for (const Buffer::RawSlice& slice : slices) {
output_body.mutable_as_bytes()->append(static_cast<const char*>(slice.mem_), slice.len_);
}
if (final_bytes_to_copy < buffer_length_to_copy) {
output_body.set_truncated(true);
return true;
} else {
return false;
}
}
TapConfigBaseImpl::TapConfigBaseImpl(envoy::config::tap::v3::TapConfig&& proto_config,
Common::Tap::Sink* admin_streamer)
: max_buffered_rx_bytes_(PROTOBUF_GET_WRAPPED_OR_DEFAULT(
proto_config.output_config(), max_buffered_rx_bytes, DefaultMaxBufferedBytes)),
max_buffered_tx_bytes_(PROTOBUF_GET_WRAPPED_OR_DEFAULT(
proto_config.output_config(), max_buffered_tx_bytes, DefaultMaxBufferedBytes)),
streaming_(proto_config.output_config().streaming()) {
ASSERT(proto_config.output_config().sinks().size() == 1);
// TODO(mattklein123): Add per-sink checks to make sure format makes sense. I.e., when using
// streaming, we should require the length delimited version of binary proto, etc.
sink_format_ = proto_config.output_config().sinks()[0].format();
switch (proto_config.output_config().sinks()[0].output_sink_type_case()) {
case envoy::config::tap::v3::OutputSink::OutputSinkTypeCase::kStreamingAdmin:
ASSERT(admin_streamer != nullptr, "admin output must be configured via admin");
// TODO(mattklein123): Graceful failure, error message, and test if someone specifies an
// admin stream output with the wrong format.
RELEASE_ASSERT(sink_format_ == envoy::config::tap::v3::OutputSink::JSON_BODY_AS_BYTES ||
sink_format_ == envoy::config::tap::v3::OutputSink::JSON_BODY_AS_STRING,
"admin output only supports JSON formats");
sink_to_use_ = admin_streamer;
break;
case envoy::config::tap::v3::OutputSink::OutputSinkTypeCase::kFilePerTap:
sink_ =
std::make_unique<FilePerTapSink>(proto_config.output_config().sinks()[0].file_per_tap());
sink_to_use_ = sink_.get();
break;
default:
NOT_REACHED_GCOVR_EXCL_LINE;
}
envoy::config::common::matcher::v3::MatchPredicate match;
if (proto_config.has_match()) {
// Use the match field whenever it is set.
match = proto_config.match();
} else if (proto_config.has_match_config()) {
// Fallback to use the deprecated match_config field and upgrade (wire cast) it to the new
// MatchPredicate which is backward compatible with the old MatchPredicate originally
// introduced in the Tap filter.
Config::VersionConverter::upgrade(proto_config.match_config(), match);
} else {
throw EnvoyException(fmt::format("Neither match nor match_config is set in TapConfig: {}",
proto_config.DebugString()));
}
buildMatcher(match, matchers_);
}
const Matcher& TapConfigBaseImpl::rootMatcher() const {
ASSERT(!matchers_.empty());
return *matchers_[0];
}
namespace {
void swapBytesToString(envoy::data::tap::v3::Body& body) {
body.set_allocated_as_string(body.release_as_bytes());
}
} // namespace
void Utility::bodyBytesToString(envoy::data::tap::v3::TraceWrapper& trace,
envoy::config::tap::v3::OutputSink::Format sink_format) {
// Swap the "bytes" string into the "string" string. This is done purely so that JSON
// serialization will serialize as a string vs. doing base64 encoding.
if (sink_format != envoy::config::tap::v3::OutputSink::JSON_BODY_AS_STRING) {
return;
}
switch (trace.trace_case()) {
case envoy::data::tap::v3::TraceWrapper::TraceCase::kHttpBufferedTrace: {
auto* http_trace = trace.mutable_http_buffered_trace();
if (http_trace->has_request() && http_trace->request().has_body()) {
swapBytesToString(*http_trace->mutable_request()->mutable_body());
}
if (http_trace->has_response() && http_trace->response().has_body()) {
swapBytesToString(*http_trace->mutable_response()->mutable_body());
}
break;
}
case envoy::data::tap::v3::TraceWrapper::TraceCase::kHttpStreamedTraceSegment: {
auto* http_trace = trace.mutable_http_streamed_trace_segment();
if (http_trace->has_request_body_chunk()) {
swapBytesToString(*http_trace->mutable_request_body_chunk());
}
if (http_trace->has_response_body_chunk()) {
swapBytesToString(*http_trace->mutable_response_body_chunk());
}
break;
}
case envoy::data::tap::v3::TraceWrapper::TraceCase::kSocketBufferedTrace: {
auto* socket_trace = trace.mutable_socket_buffered_trace();
for (auto& event : *socket_trace->mutable_events()) {
if (event.has_read()) {
swapBytesToString(*event.mutable_read()->mutable_data());
} else {
ASSERT(event.has_write());
swapBytesToString(*event.mutable_write()->mutable_data());
}
}
break;
}
case envoy::data::tap::v3::TraceWrapper::TraceCase::kSocketStreamedTraceSegment: {
auto& event = *trace.mutable_socket_streamed_trace_segment()->mutable_event();
if (event.has_read()) {
swapBytesToString(*event.mutable_read()->mutable_data());
} else if (event.has_write()) {
swapBytesToString(*event.mutable_write()->mutable_data());
}
break;
}
case envoy::data::tap::v3::TraceWrapper::TraceCase::TRACE_NOT_SET:
NOT_REACHED_GCOVR_EXCL_LINE;
}
}
void TapConfigBaseImpl::PerTapSinkHandleManagerImpl::submitTrace(TraceWrapperPtr&& trace) {
Utility::bodyBytesToString(*trace, parent_.sink_format_);
handle_->submitTrace(std::move(trace), parent_.sink_format_);
}
void FilePerTapSink::FilePerTapSinkHandle::submitTrace(
TraceWrapperPtr&& trace, envoy::config::tap::v3::OutputSink::Format format) {
if (!output_file_.is_open()) {
std::string path = fmt::format("{}_{}", parent_.config_.path_prefix(), trace_id_);
switch (format) {
case envoy::config::tap::v3::OutputSink::PROTO_BINARY:
path += MessageUtil::FileExtensions::get().ProtoBinary;
break;
case envoy::config::tap::v3::OutputSink::PROTO_BINARY_LENGTH_DELIMITED:
path += MessageUtil::FileExtensions::get().ProtoBinaryLengthDelimited;
break;
case envoy::config::tap::v3::OutputSink::PROTO_TEXT:
path += MessageUtil::FileExtensions::get().ProtoText;
break;
case envoy::config::tap::v3::OutputSink::JSON_BODY_AS_BYTES:
case envoy::config::tap::v3::OutputSink::JSON_BODY_AS_STRING:
path += MessageUtil::FileExtensions::get().Json;
break;
default:
NOT_REACHED_GCOVR_EXCL_LINE;
}
ENVOY_LOG_MISC(debug, "Opening tap file for [id={}] to {}", trace_id_, path);
// When reading and writing binary files, we need to be sure std::ios_base::binary
// is set, otherwise we will not get the expected results on Windows
output_file_.open(path, std::ios_base::binary);
}
ENVOY_LOG_MISC(trace, "Tap for [id={}]: {}", trace_id_, trace->DebugString());
switch (format) {
case envoy::config::tap::v3::OutputSink::PROTO_BINARY:
trace->SerializeToOstream(&output_file_);
break;
case envoy::config::tap::v3::OutputSink::PROTO_BINARY_LENGTH_DELIMITED: {
Protobuf::io::OstreamOutputStream stream(&output_file_);
Protobuf::io::CodedOutputStream coded_stream(&stream);
coded_stream.WriteVarint32(trace->ByteSize());
trace->SerializeWithCachedSizes(&coded_stream);
break;
}
case envoy::config::tap::v3::OutputSink::PROTO_TEXT:
output_file_ << trace->DebugString();
break;
case envoy::config::tap::v3::OutputSink::JSON_BODY_AS_BYTES:
case envoy::config::tap::v3::OutputSink::JSON_BODY_AS_STRING:
output_file_ << MessageUtil::getJsonStringFromMessage(*trace, true, true);
break;
default:
NOT_REACHED_GCOVR_EXCL_LINE;
}
}
} // namespace Tap
} // namespace Common
} // namespace Extensions
} // namespace Envoy
| Java |
#pragma once
#include <string>
#include "envoy/server/filter_config.h"
#include "common/protobuf/protobuf.h"
namespace Envoy {
namespace Extensions {
namespace HttpFilters {
namespace Common {
/**
* Config registration for http filters that have empty configuration blocks.
* The boiler plate instantiation functions (createFilterFactory, createFilterFactoryFromProto,
* and createEmptyConfigProto) are implemented here. Users of this class have to implement
* the createFilter function that instantiates the actual filter.
*/
class EmptyHttpFilterConfig : public Server::Configuration::NamedHttpFilterConfigFactory {
public:
virtual Http::FilterFactoryCb createFilter(const std::string& stat_prefix,
Server::Configuration::FactoryContext& context) PURE;
Http::FilterFactoryCb
createFilterFactoryFromProto(const Protobuf::Message&, const std::string& stat_prefix,
Server::Configuration::FactoryContext& context) override {
return createFilter(stat_prefix, context);
}
ProtobufTypes::MessagePtr createEmptyConfigProto() override {
// Using Struct instead of a custom filter config proto. This is only allowed in tests.
return ProtobufTypes::MessagePtr{new Envoy::ProtobufWkt::Struct()};
}
std::string configType() override {
// Prevent registration of filters by type. This is only allowed in tests.
return "";
}
std::string name() const override { return name_; }
protected:
EmptyHttpFilterConfig(const std::string& name) : name_(name) {}
private:
const std::string name_;
};
} // namespace Common
} // namespace HttpFilters
} // namespace Extensions
} // namespace Envoy
| 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.5.0_09) on Wed Aug 01 14:02:17 EEST 2007 -->
<TITLE>
datechooser.beans.editor.border.types (DateChooser javadoc)
</TITLE>
<META NAME="keywords" CONTENT="datechooser.beans.editor.border.types package">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
</HEAD>
<BODY BGCOLOR="white">
<FONT size="+1" CLASS="FrameTitleFont">
<A HREF="../../../../../datechooser/beans/editor/border/types/package-summary.html" target="classFrame">datechooser.beans.editor.border.types</A></FONT>
<TABLE BORDER="0" WIDTH="100%" SUMMARY="">
<TR>
<TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont">
Classes</FONT>
<FONT CLASS="FrameItemFont">
<BR>
<A HREF="AbstractBevelBorderEditor.html" title="class in datechooser.beans.editor.border.types" target="classFrame">AbstractBevelBorderEditor</A>
<BR>
<A HREF="AbstractBorderEditor.html" title="class in datechooser.beans.editor.border.types" target="classFrame">AbstractBorderEditor</A>
<BR>
<A HREF="BevelBorderEditor.html" title="class in datechooser.beans.editor.border.types" target="classFrame">BevelBorderEditor</A>
<BR>
<A HREF="CompoundBorderEditor.html" title="class in datechooser.beans.editor.border.types" target="classFrame">CompoundBorderEditor</A>
<BR>
<A HREF="DefaultBorderEditor.html" title="class in datechooser.beans.editor.border.types" target="classFrame">DefaultBorderEditor</A>
<BR>
<A HREF="EmptyBorderEditor.html" title="class in datechooser.beans.editor.border.types" target="classFrame">EmptyBorderEditor</A>
<BR>
<A HREF="EtchedBorderEditor.html" title="class in datechooser.beans.editor.border.types" target="classFrame">EtchedBorderEditor</A>
<BR>
<A HREF="LineBorderEditor.html" title="class in datechooser.beans.editor.border.types" target="classFrame">LineBorderEditor</A>
<BR>
<A HREF="MatteBorderEditor.html" title="class in datechooser.beans.editor.border.types" target="classFrame">MatteBorderEditor</A>
<BR>
<A HREF="NoBorderEditor.html" title="class in datechooser.beans.editor.border.types" target="classFrame">NoBorderEditor</A>
<BR>
<A HREF="SoftBevelBorderEditor.html" title="class in datechooser.beans.editor.border.types" target="classFrame">SoftBevelBorderEditor</A>
<BR>
<A HREF="TitledBorderEditor.html" title="class in datechooser.beans.editor.border.types" target="classFrame">TitledBorderEditor</A></FONT></TD>
</TR>
</TABLE>
</BODY>
</HTML>
| Java |
package com.kit.imagelib.imagelooker;
public interface OnPageSelectedListener {
public void onPageSelected();
}
| Java |
package matchers
import (
"fmt"
"github.com/onsi/gomega/format"
"math"
)
type BeNumericallyMatcher struct {
Comparator string
CompareTo []interface{}
}
func (matcher *BeNumericallyMatcher) Match(actual interface{}) (success bool, message string, err error) {
if len(matcher.CompareTo) == 0 || len(matcher.CompareTo) > 2 {
return false, "", fmt.Errorf("BeNumerically requires 1 or 2 CompareTo arguments. Got:\n%s", format.Object(matcher.CompareTo, 1))
}
if !isNumber(actual) {
return false, "", fmt.Errorf("Expected a number. Got:\n%s", format.Object(actual, 1))
}
if !isNumber(matcher.CompareTo[0]) {
return false, "", fmt.Errorf("Expected a number. Got:\n%s", format.Object(matcher.CompareTo[0], 1))
}
if len(matcher.CompareTo) == 2 && !isNumber(matcher.CompareTo[1]) {
return false, "", fmt.Errorf("Expected a number. Got:\n%s", format.Object(matcher.CompareTo[0], 1))
}
switch matcher.Comparator {
case "==", "~", ">", ">=", "<", "<=":
default:
return false, "", fmt.Errorf("Unknown comparator: %s", matcher.Comparator)
}
if isFloat(actual) || isFloat(matcher.CompareTo[0]) {
var secondOperand float64 = 1e-8
if len(matcher.CompareTo) == 2 {
secondOperand = toFloat(matcher.CompareTo[1])
}
success = matcher.matchFloats(toFloat(actual), toFloat(matcher.CompareTo[0]), secondOperand)
} else if isInteger(actual) {
var secondOperand int64 = 0
if len(matcher.CompareTo) == 2 {
secondOperand = toInteger(matcher.CompareTo[1])
}
success = matcher.matchIntegers(toInteger(actual), toInteger(matcher.CompareTo[0]), secondOperand)
} else if isUnsignedInteger(actual) {
var secondOperand uint64 = 0
if len(matcher.CompareTo) == 2 {
secondOperand = toUnsignedInteger(matcher.CompareTo[1])
}
success = matcher.matchUnsignedIntegers(toUnsignedInteger(actual), toUnsignedInteger(matcher.CompareTo[0]), secondOperand)
} else {
return false, "", fmt.Errorf("Failed to compare:\n%s\n%s:\n%s", format.Object(actual, 1), matcher.Comparator, format.Object(matcher.CompareTo[0], 1))
}
if success {
return true, format.Message(actual, fmt.Sprintf("not to be %s", matcher.Comparator), matcher.CompareTo[0]), nil
} else {
return false, format.Message(actual, fmt.Sprintf("to be %s", matcher.Comparator), matcher.CompareTo[0]), nil
}
}
func (matcher *BeNumericallyMatcher) matchIntegers(actual, compareTo, threshold int64) (success bool) {
switch matcher.Comparator {
case "==", "~":
diff := actual - compareTo
return -threshold <= diff && diff <= threshold
case ">":
return (actual > compareTo)
case ">=":
return (actual >= compareTo)
case "<":
return (actual < compareTo)
case "<=":
return (actual <= compareTo)
}
return false
}
func (matcher *BeNumericallyMatcher) matchUnsignedIntegers(actual, compareTo, threshold uint64) (success bool) {
switch matcher.Comparator {
case "==", "~":
if actual < compareTo {
actual, compareTo = compareTo, actual
}
return actual-compareTo <= threshold
case ">":
return (actual > compareTo)
case ">=":
return (actual >= compareTo)
case "<":
return (actual < compareTo)
case "<=":
return (actual <= compareTo)
}
return false
}
func (matcher *BeNumericallyMatcher) matchFloats(actual, compareTo, threshold float64) (success bool) {
switch matcher.Comparator {
case "~":
return math.Abs(actual-compareTo) <= threshold
case "==":
return (actual == compareTo)
case ">":
return (actual > compareTo)
case ">=":
return (actual >= compareTo)
case "<":
return (actual < compareTo)
case "<=":
return (actual <= compareTo)
}
return false
}
| Java |
/*******************************************************************************
* Copyright 2015 Unicon (R) Licensed under the
* Educational Community 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.osedu.org/licenses/ECL-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.apereo.lai;
import java.io.Serializable;
/**
* @author ggilbert
*
*/
public interface Institution extends Serializable {
String getName();
String getKey();
String getSecret();
}
| Java |
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/hwpf/fapi2/include/plat/subroutine_executor.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2017 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file subroutine_executor.H
///
/// @brief Defines the PLAT Subroutine Executor Macro.
///
/// The PLAT Subroutine Executor macro is called by
/// FAPI_CALL_SUBROUTINE when a hardware procedure when
/// a subroutine is needed, typicaly a chipop function.
///
/// Example implementation of plat code
#ifndef SUBROUTINEEXECUTOR_H_
#define SUBROUTINEEXECUTOR_H_
#include <fapi2_subroutine_executor.H>
#include <plat_trace.H>
/**
* @brief Subroutine Executor macro example code - Platforms will need to
* implement as needed for their enviroment.
*
* This macro calls a PLAT macro which will do any platform specific work to
* execute the Subroutine (e.g. dlopening a shared library)
*/
#define FAPI_PLAT_CALL_SUBROUTINE(RC, FUNC, _args...) \
{ \
FAPI_DBG("executing FAPI_PLAT_CALL_SUBROUTINE macro"); \
RC = FUNC(_args); \
}
#endif
| Java |
/*
* Copyright (c) 2017 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#define DT_DRV_COMPAT plantower_pms7003
/* sensor pms7003.c - Driver for plantower PMS7003 sensor
* PMS7003 product: http://www.plantower.com/en/content/?110.html
* PMS7003 spec: http://aqicn.org/air/view/sensor/spec/pms7003.pdf
*/
#include <errno.h>
#include <arch/cpu.h>
#include <init.h>
#include <kernel.h>
#include <drivers/sensor.h>
#include <stdlib.h>
#include <string.h>
#include <drivers/uart.h>
#include <logging/log.h>
LOG_MODULE_REGISTER(PMS7003, CONFIG_SENSOR_LOG_LEVEL);
/* wait serial output with 1000ms timeout */
#define CFG_PMS7003_SERIAL_TIMEOUT 1000
struct pms7003_data {
const struct device *uart_dev;
uint16_t pm_1_0;
uint16_t pm_2_5;
uint16_t pm_10;
};
/**
* @brief wait for an array data from uart device with a timeout
*
* @param dev the uart device
* @param data the data array to be matched
* @param len the data array len
* @param timeout the timeout in milliseconds
* @return 0 if success; -ETIME if timeout
*/
static int uart_wait_for(const struct device *dev, uint8_t *data, int len,
int timeout)
{
int matched_size = 0;
int64_t timeout_time = k_uptime_get() + K_MSEC(timeout);
while (1) {
uint8_t c;
if (k_uptime_get() > timeout_time) {
return -ETIME;
}
if (uart_poll_in(dev, &c) == 0) {
if (c == data[matched_size]) {
matched_size++;
if (matched_size == len) {
break;
}
} else if (c == data[0]) {
matched_size = 1;
} else {
matched_size = 0;
}
}
}
return 0;
}
/**
* @brief read bytes from uart
*
* @param data the data buffer
* @param len the data len
* @param timeout the timeout in milliseconds
* @return 0 if success; -ETIME if timeout
*/
static int uart_read_bytes(const struct device *dev, uint8_t *data, int len,
int timeout)
{
int read_size = 0;
int64_t timeout_time = k_uptime_get() + K_MSEC(timeout);
while (1) {
uint8_t c;
if (k_uptime_get() > timeout_time) {
return -ETIME;
}
if (uart_poll_in(dev, &c) == 0) {
data[read_size++] = c;
if (read_size == len) {
break;
}
}
}
return 0;
}
static int pms7003_sample_fetch(const struct device *dev,
enum sensor_channel chan)
{
struct pms7003_data *drv_data = dev->data;
/* sample output */
/* 42 4D 00 1C 00 01 00 01 00 01 00 01 00 01 00 01 01 92
* 00 4E 00 03 00 00 00 00 00 00 71 00 02 06
*/
uint8_t pms7003_start_bytes[] = {0x42, 0x4d};
uint8_t pms7003_receive_buffer[30];
if (uart_wait_for(drv_data->uart_dev, pms7003_start_bytes,
sizeof(pms7003_start_bytes),
CFG_PMS7003_SERIAL_TIMEOUT) < 0) {
LOG_WRN("waiting for start bytes is timeout");
return -ETIME;
}
if (uart_read_bytes(drv_data->uart_dev, pms7003_receive_buffer, 30,
CFG_PMS7003_SERIAL_TIMEOUT) < 0) {
return -ETIME;
}
drv_data->pm_1_0 =
(pms7003_receive_buffer[8] << 8) + pms7003_receive_buffer[9];
drv_data->pm_2_5 =
(pms7003_receive_buffer[10] << 8) + pms7003_receive_buffer[11];
drv_data->pm_10 =
(pms7003_receive_buffer[12] << 8) + pms7003_receive_buffer[13];
LOG_DBG("pm1.0 = %d", drv_data->pm_1_0);
LOG_DBG("pm2.5 = %d", drv_data->pm_2_5);
LOG_DBG("pm10 = %d", drv_data->pm_10);
return 0;
}
static int pms7003_channel_get(const struct device *dev,
enum sensor_channel chan,
struct sensor_value *val)
{
struct pms7003_data *drv_data = dev->data;
if (chan == SENSOR_CHAN_PM_1_0) {
val->val1 = drv_data->pm_1_0;
val->val2 = 0;
} else if (chan == SENSOR_CHAN_PM_2_5) {
val->val1 = drv_data->pm_2_5;
val->val2 = 0;
} else if (chan == SENSOR_CHAN_PM_10) {
val->val1 = drv_data->pm_10;
val->val2 = 0;
} else {
return -EINVAL;
}
return 0;
}
static const struct sensor_driver_api pms7003_api = {
.sample_fetch = &pms7003_sample_fetch,
.channel_get = &pms7003_channel_get,
};
static int pms7003_init(const struct device *dev)
{
struct pms7003_data *drv_data = dev->data;
drv_data->uart_dev = device_get_binding(DT_INST_BUS_LABEL(0));
if (!drv_data->uart_dev) {
LOG_DBG("uart device is not found: %s",
DT_INST_BUS_LABEL(0));
return -EINVAL;
}
return 0;
}
static struct pms7003_data pms7003_data;
DEVICE_DT_INST_DEFINE(0, &pms7003_init, device_pm_control_nop,
&pms7003_data, NULL, POST_KERNEL,
CONFIG_SENSOR_INIT_PRIORITY, &pms7003_api);
| Java |
var spawn = require('child_process').spawn
var port = exports.port = 1337
exports.registry = "http://localhost:" + port
exports.run = run
function run (cmd, t, opts, cb) {
if (!opts)
opts = {}
if (!Array.isArray(cmd))
throw new Error("cmd must be an Array")
if (!t || !t.end)
throw new Error("node-tap instance is missing")
var stdout = ""
, stderr = ""
, node = process.execPath
, child = spawn(node, cmd, opts)
child.stderr.on("data", function (chunk) {
stderr += chunk
})
child.stdout.on("data", function (chunk) {
stdout += chunk
})
child.on("close", function (code) {
if (cb)
cb(t, stdout, stderr, code, { cmd: cmd, opts: opts })
else
t.end()
})
}
| Java |
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/securityhub/model/AwsS3BucketLoggingConfiguration.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace SecurityHub
{
namespace Model
{
AwsS3BucketLoggingConfiguration::AwsS3BucketLoggingConfiguration() :
m_destinationBucketNameHasBeenSet(false),
m_logFilePrefixHasBeenSet(false)
{
}
AwsS3BucketLoggingConfiguration::AwsS3BucketLoggingConfiguration(JsonView jsonValue) :
m_destinationBucketNameHasBeenSet(false),
m_logFilePrefixHasBeenSet(false)
{
*this = jsonValue;
}
AwsS3BucketLoggingConfiguration& AwsS3BucketLoggingConfiguration::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("DestinationBucketName"))
{
m_destinationBucketName = jsonValue.GetString("DestinationBucketName");
m_destinationBucketNameHasBeenSet = true;
}
if(jsonValue.ValueExists("LogFilePrefix"))
{
m_logFilePrefix = jsonValue.GetString("LogFilePrefix");
m_logFilePrefixHasBeenSet = true;
}
return *this;
}
JsonValue AwsS3BucketLoggingConfiguration::Jsonize() const
{
JsonValue payload;
if(m_destinationBucketNameHasBeenSet)
{
payload.WithString("DestinationBucketName", m_destinationBucketName);
}
if(m_logFilePrefixHasBeenSet)
{
payload.WithString("LogFilePrefix", m_logFilePrefix);
}
return payload;
}
} // namespace Model
} // namespace SecurityHub
} // namespace Aws
| Java |
#
# Author:: Adam Jacob (<[email protected]>)
# Copyright:: Copyright 2008-2017, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# 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.
#
require "spec_helper"
require "ostruct"
describe Chef::Provider::Package::Apt do
# XXX: sorry this is ugly and was done quickly to get 12.0.2 out, this file needs a rewrite to use
# let blocks and shared examples
[ Chef::Resource::Package, Chef::Resource::AptPackage ].each do |resource_klass|
describe "when the new_resource is a #{resource_klass}" do
before(:each) do
@node = Chef::Node.new
@events = Chef::EventDispatch::Dispatcher.new
@run_context = Chef::RunContext.new(@node, {}, @events)
@new_resource = resource_klass.new("irssi", @run_context)
@status = double("Status", :exitstatus => 0)
@provider = Chef::Provider::Package::Apt.new(@new_resource, @run_context)
@stdin = StringIO.new
@stdout = <<-PKG_STATUS
irssi:
Installed: (none)
Candidate: 0.8.14-1ubuntu4
Version table:
0.8.14-1ubuntu4 0
500 http://us.archive.ubuntu.com/ubuntu/ lucid/main Packages
PKG_STATUS
@stderr = ""
@shell_out = OpenStruct.new(:stdout => @stdout, :stdin => @stdin, :stderr => @stderr, :status => @status, :exitstatus => 0)
@timeout = 900
end
describe "when loading current resource" do
it "should create a current resource with the name of the new_resource" do
expect(@provider).to receive(:shell_out!).with(
"apt-cache", "policy", @new_resource.package_name,
:env => { "DEBIAN_FRONTEND" => "noninteractive" },
:timeout => @timeout
).and_return(@shell_out)
@provider.load_current_resource
current_resource = @provider.current_resource
expect(current_resource).to be_a(Chef::Resource::Package)
expect(current_resource.name).to eq("irssi")
expect(current_resource.package_name).to eq("irssi")
expect(current_resource.version).to eql([nil])
end
it "should set the installed version if package has one" do
@stdout.replace(<<-INSTALLED)
sudo:
Installed: 1.7.2p1-1ubuntu5.3
Candidate: 1.7.2p1-1ubuntu5.3
Version table:
*** 1.7.2p1-1ubuntu5.3 0
500 http://us.archive.ubuntu.com/ubuntu/ lucid-updates/main Packages
500 http://security.ubuntu.com/ubuntu/ lucid-security/main Packages
100 /var/lib/dpkg/status
1.7.2p1-1ubuntu5 0
500 http://us.archive.ubuntu.com/ubuntu/ lucid/main Packages
INSTALLED
expect(@provider).to receive(:shell_out!).and_return(@shell_out)
@provider.load_current_resource
expect(@provider.current_resource.version).to eq(["1.7.2p1-1ubuntu5.3"])
expect(@provider.candidate_version).to eql(["1.7.2p1-1ubuntu5.3"])
end
# it is the superclasses responsibility to throw most exceptions
it "if the package does not exist in the cache sets installed + candidate version to nil" do
@new_resource.package_name("conic-smarms")
policy_out = <<-POLICY_STDOUT
N: Unable to locate package conic-smarms
POLICY_STDOUT
policy = double(:stdout => policy_out, :exitstatus => 0)
expect(@provider).to receive(:shell_out!).with(
"apt-cache", "policy", "conic-smarms",
:env => { "DEBIAN_FRONTEND" => "noninteractive" },
:timeout => @timeout
).and_return(policy)
showpkg_out = <<-SHOWPKG_STDOUT
N: Unable to locate package conic-smarms
SHOWPKG_STDOUT
showpkg = double(:stdout => showpkg_out, :exitstatus => 0)
expect(@provider).to receive(:shell_out!).with(
"apt-cache", "showpkg", "conic-smarms",
:env => { "DEBIAN_FRONTEND" => "noninteractive" },
:timeout => @timeout
).and_return(showpkg)
@provider.load_current_resource
end
# libmysqlclient-dev is a real package in newer versions of debian + ubuntu
# list of virtual packages: http://www.debian.org/doc/packaging-manuals/virtual-package-names-list.txt
it "should not install the virtual package there is a single provider package and it is installed" do
@new_resource.package_name("libmysqlclient15-dev")
virtual_package_out = <<-VPKG_STDOUT
libmysqlclient15-dev:
Installed: (none)
Candidate: (none)
Version table:
VPKG_STDOUT
virtual_package = double(:stdout => virtual_package_out, :exitstatus => 0)
expect(@provider).to receive(:shell_out!).with(
"apt-cache", "policy", "libmysqlclient15-dev",
:env => { "DEBIAN_FRONTEND" => "noninteractive" },
:timeout => @timeout
).and_return(virtual_package)
showpkg_out = <<-SHOWPKG_STDOUT
Package: libmysqlclient15-dev
Versions:
Reverse Depends:
libmysqlclient-dev,libmysqlclient15-dev
libmysqlclient-dev,libmysqlclient15-dev
libmysqlclient-dev,libmysqlclient15-dev
libmysqlclient-dev,libmysqlclient15-dev
libmysqlclient-dev,libmysqlclient15-dev
libmysqlclient-dev,libmysqlclient15-dev
Dependencies:
Provides:
Reverse Provides:
libmysqlclient-dev 5.1.41-3ubuntu12.7
libmysqlclient-dev 5.1.41-3ubuntu12.10
libmysqlclient-dev 5.1.41-3ubuntu12
SHOWPKG_STDOUT
showpkg = double(:stdout => showpkg_out, :exitstatus => 0)
expect(@provider).to receive(:shell_out!).with(
"apt-cache", "showpkg", "libmysqlclient15-dev",
:env => { "DEBIAN_FRONTEND" => "noninteractive" },
:timeout => @timeout
).and_return(showpkg)
real_package_out = <<-RPKG_STDOUT
libmysqlclient-dev:
Installed: 5.1.41-3ubuntu12.10
Candidate: 5.1.41-3ubuntu12.10
Version table:
*** 5.1.41-3ubuntu12.10 0
500 http://us.archive.ubuntu.com/ubuntu/ lucid-updates/main Packages
100 /var/lib/dpkg/status
5.1.41-3ubuntu12.7 0
500 http://security.ubuntu.com/ubuntu/ lucid-security/main Packages
5.1.41-3ubuntu12 0
500 http://us.archive.ubuntu.com/ubuntu/ lucid/main Packages
RPKG_STDOUT
real_package = double(:stdout => real_package_out, :exitstatus => 0)
expect(@provider).to receive(:shell_out!).with(
"apt-cache", "policy", "libmysqlclient-dev",
:env => { "DEBIAN_FRONTEND" => "noninteractive" },
:timeout => @timeout
).and_return(real_package)
@provider.load_current_resource
end
it "should raise an exception if you specify a virtual package with multiple provider packages" do
@new_resource.package_name("mp3-decoder")
virtual_package_out = <<-VPKG_STDOUT
mp3-decoder:
Installed: (none)
Candidate: (none)
Version table:
VPKG_STDOUT
virtual_package = double(:stdout => virtual_package_out, :exitstatus => 0)
expect(@provider).to receive(:shell_out!).with(
"apt-cache", "policy", "mp3-decoder",
:env => { "DEBIAN_FRONTEND" => "noninteractive" },
:timeout => @timeout
).and_return(virtual_package)
showpkg_out = <<-SHOWPKG_STDOUT
Package: mp3-decoder
Versions:
Reverse Depends:
nautilus,mp3-decoder
vux,mp3-decoder
plait,mp3-decoder
ecasound,mp3-decoder
nautilus,mp3-decoder
Dependencies:
Provides:
Reverse Provides:
vlc-nox 1.0.6-1ubuntu1.8
vlc 1.0.6-1ubuntu1.8
vlc-nox 1.0.6-1ubuntu1
vlc 1.0.6-1ubuntu1
opencubicplayer 1:0.1.17-2
mpg321 0.2.10.6
mpg123 1.12.1-0ubuntu1
SHOWPKG_STDOUT
showpkg = double(:stdout => showpkg_out, :exitstatus => 0)
expect(@provider).to receive(:shell_out!).with(
"apt-cache", "showpkg", "mp3-decoder",
:env => { "DEBIAN_FRONTEND" => "noninteractive" },
:timeout => @timeout
).and_return(showpkg)
expect { @provider.load_current_resource }.to raise_error(Chef::Exceptions::Package)
end
it "should run apt-cache policy with the default_release option, if there is one on the resource" do
@new_resource = Chef::Resource::AptPackage.new("irssi", @run_context)
@provider = Chef::Provider::Package::Apt.new(@new_resource, @run_context)
@new_resource.default_release("lenny-backports")
@new_resource.provider(nil)
expect(@provider).to receive(:shell_out!).with(
"apt-cache", "-o", "APT::Default-Release=lenny-backports", "policy", "irssi",
:env => { "DEBIAN_FRONTEND" => "noninteractive" },
:timeout => @timeout
).and_return(@shell_out)
@provider.load_current_resource
end
it "raises an exception if a source is specified (CHEF-5113)" do
@new_resource.source "pluto"
expect(@provider).to receive(:shell_out!).with(
"apt-cache", "policy", @new_resource.package_name,
:env => { "DEBIAN_FRONTEND" => "noninteractive" } ,
:timeout => @timeout
).and_return(@shell_out)
expect { @provider.run_action(:install) }.to raise_error(Chef::Exceptions::Package)
end
end
context "after loading the current resource" do
before do
@current_resource = resource_klass.new("irssi", @run_context)
@provider.current_resource = @current_resource
allow(@provider).to receive(:package_data).and_return({
"irssi" => {
virtual: false,
candidate_version: "0.8.12-7",
installed_version: nil,
},
"libmysqlclient15-dev" => {
virtual: true,
candidate_version: nil,
installed_version: nil,
},
})
end
describe "install_package" do
it "should run apt-get install with the package name and version" do
expect(@provider).to receive(:shell_out!). with(
"apt-get", "-q", "-y", "install", "irssi=0.8.12-7",
:env => { "DEBIAN_FRONTEND" => "noninteractive" },
:timeout => @timeout
)
@provider.install_package(["irssi"], ["0.8.12-7"])
end
it "should run apt-get install with the package name and version and options if specified" do
expect(@provider).to receive(:shell_out!).with(
"apt-get", "-q", "-y", "--force-yes", "install", "irssi=0.8.12-7",
:env => { "DEBIAN_FRONTEND" => "noninteractive" },
:timeout => @timeout
)
@new_resource.options("--force-yes")
@provider.install_package(["irssi"], ["0.8.12-7"])
end
it "should run apt-get install with the package name and version and default_release if there is one and provider is explicitly defined" do
@new_resource = nil
@new_resource = Chef::Resource::AptPackage.new("irssi", @run_context)
@new_resource.default_release("lenny-backports")
@new_resource.provider = nil
@provider.new_resource = @new_resource
expect(@provider).to receive(:shell_out!).with(
"apt-get", "-q", "-y", "-o", "APT::Default-Release=lenny-backports", "install", "irssi=0.8.12-7",
:env => { "DEBIAN_FRONTEND" => "noninteractive" },
:timeout => @timeout
)
@provider.install_package(["irssi"], ["0.8.12-7"])
end
it "should run apt-get install with the package name and quotes options if specified" do
expect(@provider).to receive(:shell_out!).with(
"apt-get", "-q", "-y", "--force-yes", "-o", "Dpkg::Options::=--force-confdef", "-o", "Dpkg::Options::=--force-confnew", "install", "irssi=0.8.12-7",
:env => { "DEBIAN_FRONTEND" => "noninteractive" },
:timeout => @timeout
)
@new_resource.options('--force-yes -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confnew"')
@provider.install_package(["irssi"], ["0.8.12-7"])
end
end
describe resource_klass, "upgrade_package" do
it "should run install_package with the name and version" do
expect(@provider).to receive(:install_package).with(["irssi"], ["0.8.12-7"])
@provider.upgrade_package(["irssi"], ["0.8.12-7"])
end
end
describe resource_klass, "remove_package" do
it "should run apt-get remove with the package name" do
expect(@provider).to receive(:shell_out!).with(
"apt-get", "-q", "-y", "remove", "irssi",
:env => { "DEBIAN_FRONTEND" => "noninteractive" },
:timeout => @timeout
)
@provider.remove_package(["irssi"], ["0.8.12-7"])
end
it "should run apt-get remove with the package name and options if specified" do
expect(@provider).to receive(:shell_out!).with(
"apt-get", "-q", "-y", "--force-yes", "remove", "irssi",
:env => { "DEBIAN_FRONTEND" => "noninteractive" },
:timeout => @timeout
)
@new_resource.options("--force-yes")
@provider.remove_package(["irssi"], ["0.8.12-7"])
end
end
describe "when purging a package" do
it "should run apt-get purge with the package name" do
expect(@provider).to receive(:shell_out!).with(
"apt-get", "-q", "-y", "purge", "irssi",
:env => { "DEBIAN_FRONTEND" => "noninteractive" },
:timeout => @timeout
)
@provider.purge_package(["irssi"], ["0.8.12-7"])
end
it "should run apt-get purge with the package name and options if specified" do
expect(@provider).to receive(:shell_out!).with(
"apt-get", "-q", "-y", "--force-yes", "purge", "irssi",
:env => { "DEBIAN_FRONTEND" => "noninteractive" },
:timeout => @timeout
)
@new_resource.options("--force-yes")
@provider.purge_package(["irssi"], ["0.8.12-7"])
end
end
describe "when preseeding a package" do
before(:each) do
allow(@provider).to receive(:get_preseed_file).and_return("/tmp/irssi-0.8.12-7.seed")
end
it "should get the full path to the preseed response file" do
file = "/tmp/irssi-0.8.12-7.seed"
expect(@provider).to receive(:shell_out!).with(
"debconf-set-selections", "/tmp/irssi-0.8.12-7.seed",
:env => { "DEBIAN_FRONTEND" => "noninteractive" },
:timeout => @timeout
)
@provider.preseed_package(file)
end
it "should run debconf-set-selections on the preseed file if it has changed" do
expect(@provider).to receive(:shell_out!).with(
"debconf-set-selections", "/tmp/irssi-0.8.12-7.seed",
:env => { "DEBIAN_FRONTEND" => "noninteractive" },
:timeout => @timeout
)
file = @provider.get_preseed_file("irssi", "0.8.12-7")
@provider.preseed_package(file)
end
it "should not run debconf-set-selections if the preseed file has not changed" do
allow(@provider).to receive(:check_all_packages_state)
@current_resource.version "0.8.11"
@new_resource.response_file "/tmp/file"
allow(@provider).to receive(:get_preseed_file).and_return(false)
expect(@provider).not_to receive(:shell_out!)
@provider.run_action(:reconfig)
end
end
describe "when reconfiguring a package" do
it "should run dpkg-reconfigure package" do
expect(@provider).to receive(:shell_out!).with(
"dpkg-reconfigure", "irssi",
:env => { "DEBIAN_FRONTEND" => "noninteractive" },
:timeout => @timeout
)
@provider.reconfig_package("irssi", "0.8.12-7")
end
end
describe "when locking a package" do
it "should run apt-mark hold package" do
expect(@provider).to receive(:shell_out!).with(
"apt-mark", "hold", "irssi",
:env => { "DEBIAN_FRONTEND" => "noninteractive" },
:timeout => @timeout
)
@provider.lock_package("irssi", "0.8.12-7")
end
end
describe "when unlocking a package" do
it "should run apt-mark unhold package" do
expect(@provider).to receive(:shell_out!).with(
"apt-mark", "unhold", "irssi",
:env => { "DEBIAN_FRONTEND" => "noninteractive" },
:timeout => @timeout
)
@provider.unlock_package("irssi", "0.8.12-7")
end
end
describe "when installing a virtual package" do
it "should install the package without specifying a version" do
@provider.package_data["libmysqlclient15-dev"][:virtual] = true
expect(@provider).to receive(:shell_out!).with(
"apt-get", "-q", "-y", "install", "libmysqlclient15-dev",
:env => { "DEBIAN_FRONTEND" => "noninteractive" },
:timeout => @timeout
)
@provider.install_package(["libmysqlclient15-dev"], ["not_a_real_version"])
end
end
describe "when removing a virtual package" do
it "should remove the resolved name instead of the virtual package name" do
expect(@provider).to receive(:resolve_virtual_package_name).with("libmysqlclient15-dev").and_return("libmysqlclient-dev")
expect(@provider).to receive(:shell_out!).with(
"apt-get", "-q", "-y", "remove", "libmysqlclient-dev",
:env => { "DEBIAN_FRONTEND" => "noninteractive" },
:timeout => @timeout
)
@provider.remove_package(["libmysqlclient15-dev"], ["not_a_real_version"])
end
end
describe "when purging a virtual package" do
it "should purge the resolved name instead of the virtual package name" do
expect(@provider).to receive(:resolve_virtual_package_name).with("libmysqlclient15-dev").and_return("libmysqlclient-dev")
expect(@provider).to receive(:shell_out!).with(
"apt-get", "-q", "-y", "purge", "libmysqlclient-dev",
:env => { "DEBIAN_FRONTEND" => "noninteractive" },
:timeout => @timeout
)
@provider.purge_package(["libmysqlclient15-dev"], ["not_a_real_version"])
end
end
describe "when installing multiple packages" do
it "can install a virtual package followed by a non-virtual package" do
# https://github.com/chef/chef/issues/2914
expect(@provider).to receive(:shell_out!).with(
"apt-get", "-q", "-y", "install", "libmysqlclient15-dev", "irssi=0.8.12-7",
:env => { "DEBIAN_FRONTEND" => "noninteractive" },
:timeout => @timeout
)
@provider.install_package(["libmysqlclient15-dev", "irssi"], ["not_a_real_version", "0.8.12-7"])
end
end
describe "#action_install" do
it "should run dpkg to compare versions if an existing version is installed" do
allow(@provider).to receive(:get_current_versions).and_return("1.4.0")
allow(@new_resource).to receive(:allow_downgrade).and_return(false)
expect(@provider).to receive(:shell_out_compact_timeout).with(
"dpkg", "--compare-versions", "1.4.0", "gt", "0.8.12-7"
).and_return(double(error?: false))
@provider.run_action(:upgrade)
end
it "should install the package if the installed version is older" do
allow(@provider).to receive(:get_current_versions).and_return("0.4.0")
allow(@new_resource).to receive(:allow_downgrade).and_return(false)
expect(@provider).to receive(:version_compare).and_return(-1)
expect(@provider).to receive(:shell_out!).with(
"apt-get", "-q", "-y", "install", "irssi=0.8.12-7",
:env => { "DEBIAN_FRONTEND" => "noninteractive" },
:timeout => @timeout
)
@provider.run_action(:upgrade)
end
it "should not compare versions if an existing version is not installed" do
allow(@provider).to receive(:get_current_versions).and_return(nil)
allow(@new_resource).to receive(:allow_downgrade).and_return(false)
expect(@provider).not_to receive(:version_compare)
expect(@provider).to receive(:shell_out!).with(
"apt-get", "-q", "-y", "install", "irssi=0.8.12-7",
:env => { "DEBIAN_FRONTEND" => "noninteractive" },
:timeout => @timeout
)
@provider.run_action(:upgrade)
end
end
end
end
end
end
| Java |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.Remoting;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.VisualStudio.LanguageServices.Remote;
using Nerdbank;
using Roslyn.Utilities;
using StreamJsonRpc;
namespace Roslyn.Test.Utilities.Remote
{
internal sealed class InProcRemoteHostClient : RemoteHostClient
{
private readonly InProcRemoteServices _inprocServices;
private readonly ReferenceCountedDisposable<RemotableDataJsonRpc> _remotableDataRpc;
private readonly JsonRpc _rpc;
public static async Task<RemoteHostClient> CreateAsync(Workspace workspace, bool runCacheCleanup)
{
var inprocServices = new InProcRemoteServices(runCacheCleanup);
// Create the RemotableDataJsonRpc before we create the remote host: this call implicitly sets up the remote IExperimentationService so that will be available for later calls
var remotableDataRpc = new RemotableDataJsonRpc(workspace, inprocServices.Logger, await inprocServices.RequestServiceAsync(WellKnownServiceHubServices.SnapshotService).ConfigureAwait(false));
var remoteHostStream = await inprocServices.RequestServiceAsync(WellKnownRemoteHostServices.RemoteHostService).ConfigureAwait(false);
var current = CreateClientId(Process.GetCurrentProcess().Id.ToString());
var instance = new InProcRemoteHostClient(current, workspace, inprocServices, new ReferenceCountedDisposable<RemotableDataJsonRpc>(remotableDataRpc), remoteHostStream);
// make sure connection is done right
var telemetrySession = default(string);
var uiCultureLCIDE = 0;
var cultureLCID = 0;
var host = await instance._rpc.InvokeAsync<string>(nameof(IRemoteHostService.Connect), current, uiCultureLCIDE, cultureLCID, telemetrySession).ConfigureAwait(false);
// TODO: change this to non fatal watson and make VS to use inproc implementation
Contract.ThrowIfFalse(host == current.ToString());
instance.Started();
// return instance
return instance;
}
private InProcRemoteHostClient(
string clientId,
Workspace workspace,
InProcRemoteServices inprocServices,
ReferenceCountedDisposable<RemotableDataJsonRpc> remotableDataRpc,
Stream stream)
: base(workspace)
{
Contract.ThrowIfNull(remotableDataRpc);
ClientId = clientId;
_inprocServices = inprocServices;
_remotableDataRpc = remotableDataRpc;
_rpc = stream.CreateStreamJsonRpc(target: this, inprocServices.Logger);
// handle disconnected situation
_rpc.Disconnected += OnRpcDisconnected;
_rpc.StartListening();
}
public AssetStorage AssetStorage => _inprocServices.AssetStorage;
public void RegisterService(string name, Func<Stream, IServiceProvider, ServiceHubServiceBase> serviceCreator)
{
_inprocServices.RegisterService(name, serviceCreator);
}
public override string ClientId { get; }
public override async Task<Connection> TryCreateConnectionAsync(
string serviceName, object callbackTarget, CancellationToken cancellationToken)
{
// get stream from service hub to communicate service specific information
// this is what consumer actually use to communicate information
var serviceStream = await _inprocServices.RequestServiceAsync(serviceName).ConfigureAwait(false);
return new JsonRpcConnection(_inprocServices.Logger, callbackTarget, serviceStream, _remotableDataRpc.TryAddReference());
}
protected override void OnStarted()
{
}
protected override void OnStopped()
{
// we are asked to disconnect. unsubscribe and dispose to disconnect
_rpc.Disconnected -= OnRpcDisconnected;
_rpc.Dispose();
_remotableDataRpc.Dispose();
}
private void OnRpcDisconnected(object sender, JsonRpcDisconnectedEventArgs e)
{
Stopped();
}
public class ServiceProvider : IServiceProvider
{
private static readonly TraceSource s_traceSource = new TraceSource("inprocRemoteClient");
private readonly AssetStorage _storage;
public ServiceProvider(bool runCacheCleanup)
{
_storage = runCacheCleanup ?
new AssetStorage(cleanupInterval: TimeSpan.FromSeconds(30), purgeAfter: TimeSpan.FromMinutes(1), gcAfter: TimeSpan.FromMinutes(5)) :
new AssetStorage();
}
public AssetStorage AssetStorage => _storage;
public object GetService(Type serviceType)
{
if (typeof(TraceSource) == serviceType)
{
return s_traceSource;
}
if (typeof(AssetStorage) == serviceType)
{
return _storage;
}
throw ExceptionUtilities.UnexpectedValue(serviceType);
}
}
private class InProcRemoteServices
{
private readonly ServiceProvider _serviceProvider;
private readonly Dictionary<string, Func<Stream, IServiceProvider, ServiceHubServiceBase>> _creatorMap;
public InProcRemoteServices(bool runCacheCleanup)
{
_serviceProvider = new ServiceProvider(runCacheCleanup);
_creatorMap = new Dictionary<string, Func<Stream, IServiceProvider, ServiceHubServiceBase>>();
RegisterService(WellKnownRemoteHostServices.RemoteHostService, (s, p) => new RemoteHostService(s, p));
RegisterService(WellKnownServiceHubServices.CodeAnalysisService, (s, p) => new CodeAnalysisService(s, p));
RegisterService(WellKnownServiceHubServices.SnapshotService, (s, p) => new SnapshotService(s, p));
RegisterService(WellKnownServiceHubServices.RemoteSymbolSearchUpdateEngine, (s, p) => new RemoteSymbolSearchUpdateEngine(s, p));
}
public AssetStorage AssetStorage => _serviceProvider.AssetStorage;
public TraceSource Logger { get; } = new TraceSource("Default");
public void RegisterService(string name, Func<Stream, IServiceProvider, ServiceHubServiceBase> serviceCreator)
{
_creatorMap.Add(name, serviceCreator);
}
public Task<Stream> RequestServiceAsync(string serviceName)
{
if (_creatorMap.TryGetValue(serviceName, out var creator))
{
var tuple = FullDuplexStream.CreateStreams();
return Task.FromResult<Stream>(new WrappedStream(creator(tuple.Item1, _serviceProvider), tuple.Item2));
}
throw ExceptionUtilities.UnexpectedValue(serviceName);
}
private class WrappedStream : Stream
{
private readonly IDisposable _service;
private readonly Stream _stream;
public WrappedStream(IDisposable service, Stream stream)
{
// tie service's lifetime with that of stream
_service = service;
_stream = stream;
}
public override long Position
{
get { return _stream.Position; }
set { _stream.Position = value; }
}
public override int ReadTimeout
{
get { return _stream.ReadTimeout; }
set { _stream.ReadTimeout = value; }
}
public override int WriteTimeout
{
get { return _stream.WriteTimeout; }
set { _stream.WriteTimeout = value; }
}
public override bool CanRead => _stream.CanRead;
public override bool CanSeek => _stream.CanSeek;
public override bool CanWrite => _stream.CanWrite;
public override long Length => _stream.Length;
public override bool CanTimeout => _stream.CanTimeout;
public override void Flush() => _stream.Flush();
public override Task FlushAsync(CancellationToken cancellationToken) => _stream.FlushAsync(cancellationToken);
public override long Seek(long offset, SeekOrigin origin) => _stream.Seek(offset, origin);
public override void SetLength(long value) => _stream.SetLength(value);
public override int ReadByte() => _stream.ReadByte();
public override void WriteByte(byte value) => _stream.WriteByte(value);
public override int Read(byte[] buffer, int offset, int count) => _stream.Read(buffer, offset, count);
public override void Write(byte[] buffer, int offset, int count) => _stream.Write(buffer, offset, count);
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => _stream.ReadAsync(buffer, offset, count, cancellationToken);
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => _stream.WriteAsync(buffer, offset, count, cancellationToken);
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) => _stream.BeginRead(buffer, offset, count, callback, state);
public override int EndRead(IAsyncResult asyncResult) => _stream.EndRead(asyncResult);
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) => _stream.BeginWrite(buffer, offset, count, callback, state);
public override void EndWrite(IAsyncResult asyncResult) => _stream.EndWrite(asyncResult);
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) => _stream.CopyToAsync(destination, bufferSize, cancellationToken);
public override object InitializeLifetimeService()
{
throw new NotSupportedException();
}
public override ObjRef CreateObjRef(Type requestedType)
{
throw new NotSupportedException();
}
public override void Close()
{
_service.Dispose();
_stream.Close();
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
_service.Dispose();
_stream.Dispose();
}
}
}
}
}
| Java |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Monitoring.V3.Snippets
{
// [START monitoring_v3_generated_UptimeCheckService_CreateUptimeCheckConfig_sync_flattened]
using Google.Cloud.Monitoring.V3;
public sealed partial class GeneratedUptimeCheckServiceClientSnippets
{
/// <summary>Snippet for CreateUptimeCheckConfig</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void CreateUptimeCheckConfig()
{
// Create client
UptimeCheckServiceClient uptimeCheckServiceClient = UptimeCheckServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]";
UptimeCheckConfig uptimeCheckConfig = new UptimeCheckConfig();
// Make the request
UptimeCheckConfig response = uptimeCheckServiceClient.CreateUptimeCheckConfig(parent, uptimeCheckConfig);
}
}
// [END monitoring_v3_generated_UptimeCheckService_CreateUptimeCheckConfig_sync_flattened]
}
| Java |
package org.goodsManagement.service.impl.PoiUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.goodsManagement.po.GetGoodsDto;
import org.goodsManagement.vo.GetGoodsVO;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
/**
* Created by lifei on 2015/9/23.
*/
@Component
public class GetGoodsToExcel {
/*public static void main(String[] args){
List<GetGoodsVO> list = new ArrayList<GetGoodsVO>();
GetGoodsVO a1 = new GetGoodsVO();
a1.setStaffname("大黄");
a1.setGoodname("屎");
a1.setGetnumber(2);
a1.setGoodtype("一大坨");
list.add(a1);
GetGoodsVO a2 = new GetGoodsVO();
a2.setStaffname("小黄");
a2.setGoodname("屎");
a2.setGetnumber(2);
a2.setGoodtype("一桶");
list.add(a2);
String path = "C:\\Users\\lifei\\Desktop\\getgood.xls";
GetGoodsToExcel.toExcel(list,path);
System.out.println("导出完成");
}*/
/**
*
* @param list
* 数据库表中人员领用记录的集合
* @param path
* 要写入的文件的路径
*/
public void addtoExcel(List<GetGoodsVO> list,String path){
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("Outgoods");
String[] n = { "姓名", "物品名称号", "物品型号", "物品数量" };
Object[][] value = new Object[list.size() + 1][4];
for (int m = 0; m < n.length; m++) {
value[0][m] = n[m];
}
for (int i = 0; i < list.size(); i++) {
GetGoodsVO getGoodsVOg= (GetGoodsVO) list.get(i);
value[i + 1][0] = getGoodsVOg.getStaffname();
value[i + 1][1] = getGoodsVOg.getGoodname();
value[i + 1][2] = getGoodsVOg.getGoodtype();
value[i + 1][3] = getGoodsVOg.getGetnumber();
}
ExcelUtils.writeArrayToExcel(wb, sheet, list.size() + 1, 4, value);
ExcelUtils.writeWorkbook(wb, path);
}
}
| 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.camel.component.bean.validator.springboot;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Generated;
import org.apache.camel.CamelContext;
import org.apache.camel.component.bean.validator.BeanValidatorComponent;
import org.apache.camel.spi.ComponentCustomizer;
import org.apache.camel.spi.HasId;
import org.apache.camel.spring.boot.CamelAutoConfiguration;
import org.apache.camel.spring.boot.ComponentConfigurationProperties;
import org.apache.camel.spring.boot.util.CamelPropertiesHelper;
import org.apache.camel.spring.boot.util.ConditionalOnCamelContextAndAutoConfigurationBeans;
import org.apache.camel.spring.boot.util.GroupCondition;
import org.apache.camel.spring.boot.util.HierarchicalPropertiesEvaluator;
import org.apache.camel.support.IntrospectionSupport;
import org.apache.camel.util.ObjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
/**
* Generated by camel-package-maven-plugin - do not edit this file!
*/
@Generated("org.apache.camel.maven.packaging.SpringBootAutoConfigurationMojo")
@Configuration
@Conditional({ConditionalOnCamelContextAndAutoConfigurationBeans.class,
BeanValidatorComponentAutoConfiguration.GroupConditions.class})
@AutoConfigureAfter(CamelAutoConfiguration.class)
@EnableConfigurationProperties({ComponentConfigurationProperties.class,
BeanValidatorComponentConfiguration.class})
public class BeanValidatorComponentAutoConfiguration {
private static final Logger LOGGER = LoggerFactory
.getLogger(BeanValidatorComponentAutoConfiguration.class);
@Autowired
private ApplicationContext applicationContext;
@Autowired
private CamelContext camelContext;
@Autowired
private BeanValidatorComponentConfiguration configuration;
@Autowired(required = false)
private List<ComponentCustomizer<BeanValidatorComponent>> customizers;
static class GroupConditions extends GroupCondition {
public GroupConditions() {
super("camel.component", "camel.component.bean-validator");
}
}
@Lazy
@Bean(name = "bean-validator-component")
@ConditionalOnMissingBean(BeanValidatorComponent.class)
public BeanValidatorComponent configureBeanValidatorComponent()
throws Exception {
BeanValidatorComponent component = new BeanValidatorComponent();
component.setCamelContext(camelContext);
Map<String, Object> parameters = new HashMap<>();
IntrospectionSupport.getProperties(configuration, parameters, null,
false);
for (Map.Entry<String, Object> entry : parameters.entrySet()) {
Object value = entry.getValue();
Class<?> paramClass = value.getClass();
if (paramClass.getName().endsWith("NestedConfiguration")) {
Class nestedClass = null;
try {
nestedClass = (Class) paramClass.getDeclaredField(
"CAMEL_NESTED_CLASS").get(null);
HashMap<String, Object> nestedParameters = new HashMap<>();
IntrospectionSupport.getProperties(value, nestedParameters,
null, false);
Object nestedProperty = nestedClass.newInstance();
CamelPropertiesHelper.setCamelProperties(camelContext,
nestedProperty, nestedParameters, false);
entry.setValue(nestedProperty);
} catch (NoSuchFieldException e) {
}
}
}
CamelPropertiesHelper.setCamelProperties(camelContext, component,
parameters, false);
if (ObjectHelper.isNotEmpty(customizers)) {
for (ComponentCustomizer<BeanValidatorComponent> customizer : customizers) {
boolean useCustomizer = (customizer instanceof HasId)
? HierarchicalPropertiesEvaluator.evaluate(
applicationContext.getEnvironment(),
"camel.component.customizer",
"camel.component.bean-validator.customizer",
((HasId) customizer).getId())
: HierarchicalPropertiesEvaluator.evaluate(
applicationContext.getEnvironment(),
"camel.component.customizer",
"camel.component.bean-validator.customizer");
if (useCustomizer) {
LOGGER.debug("Configure component {}, with customizer {}",
component, customizer);
customizer.customize(component);
}
}
}
return component;
}
} | Java |
#ifndef _DICTIONARY_H_
#define _DICTIONARY_H_
#include <string>
#include <unordered_map>
#include <cinttypes>
// This class represents a dictionary that maps integer values to strings.
class Dictionary {
public:
typedef int32_t DiffType; // return value of compare function
typedef uint32_t IntType; // int is enough, no need for int64
typedef std::string StringType;
typedef std::unordered_map<IntType, IntType> TranslationTable;
private:
typedef std::unordered_map<IntType, StringType> IndexMap;
typedef std::unordered_map<StringType, IntType> ReverseMap;
public:
typedef IndexMap::const_iterator const_iterator;
private:
// Mapping from ID to String
IndexMap indexMap;
// Mapping from String to ID
ReverseMap reverseMap;
// Mapping from ID to index in sorted order
TranslationTable orderMap;
// Next ID to be given
IntType nextID;
// Whether or not the dictionary has been modified since loading.
bool modified;
// Whether or not orderMap is valid
bool orderValid;
public:
// Constructor
Dictionary( void );
// Construct from dictionary name
Dictionary( const std::string name );
// Destructor
~Dictionary( void );
// Look up an ID and get the String
const char * Dereference( const IntType id ) const;
// Look up a String and get the ID
// Return invalid if not found
IntType Lookup( const char * str, const IntType invalid ) const;
// Insert a value into the Dictionary and return the ID.
// Throw an error if the new ID is larger than maxID
IntType Insert( const char * str, const IntType maxID );
// Integrate another dictionary into this one, and produce a translation
// table for any values whose ID has changed.
void Integrate( Dictionary& other, TranslationTable& trans );
// load/save dictionary from SQL
// name specifies which dictionary to load/save
void Load(const char* name);
void Save(const char* name);
// Compare two factors lexicographically.
// The return value will be as follows:
// first > second : retVal > 0
// first = second : retVal = 0
// first < second : retVal < 0
DiffType Compare( IntType firstID, IntType secondID ) const;
const_iterator begin( void) const;
const_iterator cbegin( void ) const;
const_iterator end( void ) const;
const_iterator cend( void ) const;
private:
// Helper method for reverse lookups
IntType Lookup( const StringType& str, const IntType invalid ) const;
// Helper method for inserting strings
IntType Insert( StringType& str );
// Helper method to compute the sorted order.
void ComputeOrder( void );
/* ***** Static Members ***** */
private:
typedef std::unordered_map<std::string, Dictionary> DictionaryMap;
// Storage for global dictionaries
static DictionaryMap dicts;
/* ***** Static Methods ***** */
public:
static Dictionary & GetDictionary( const std::string name );
};
#endif //_DICTIONARY_H_
| Java |
//===- WriterUtils.cpp ----------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "WriterUtils.h"
#include "lld/Common/ErrorHandler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/EndianStream.h"
#include "llvm/Support/LEB128.h"
#define DEBUG_TYPE "lld"
using namespace llvm;
using namespace llvm::wasm;
namespace lld {
std::string toString(ValType type) {
switch (type) {
case ValType::I32:
return "i32";
case ValType::I64:
return "i64";
case ValType::F32:
return "f32";
case ValType::F64:
return "f64";
case ValType::V128:
return "v128";
case ValType::EXNREF:
return "exnref";
case ValType::EXTERNREF:
return "externref";
}
llvm_unreachable("Invalid wasm::ValType");
}
std::string toString(const WasmSignature &sig) {
SmallString<128> s("(");
for (ValType type : sig.Params) {
if (s.size() != 1)
s += ", ";
s += toString(type);
}
s += ") -> ";
if (sig.Returns.empty())
s += "void";
else
s += toString(sig.Returns[0]);
return std::string(s.str());
}
std::string toString(const WasmGlobalType &type) {
return (type.Mutable ? "var " : "const ") +
toString(static_cast<ValType>(type.Type));
}
std::string toString(const WasmEventType &type) {
if (type.Attribute == WASM_EVENT_ATTRIBUTE_EXCEPTION)
return "exception";
return "unknown";
}
namespace wasm {
void debugWrite(uint64_t offset, const Twine &msg) {
LLVM_DEBUG(dbgs() << format(" | %08lld: ", offset) << msg << "\n");
}
void writeUleb128(raw_ostream &os, uint64_t number, const Twine &msg) {
debugWrite(os.tell(), msg + "[" + utohexstr(number) + "]");
encodeULEB128(number, os);
}
void writeSleb128(raw_ostream &os, int64_t number, const Twine &msg) {
debugWrite(os.tell(), msg + "[" + utohexstr(number) + "]");
encodeSLEB128(number, os);
}
void writeBytes(raw_ostream &os, const char *bytes, size_t count,
const Twine &msg) {
debugWrite(os.tell(), msg + " [data[" + Twine(count) + "]]");
os.write(bytes, count);
}
void writeStr(raw_ostream &os, StringRef string, const Twine &msg) {
debugWrite(os.tell(),
msg + " [str[" + Twine(string.size()) + "]: " + string + "]");
encodeULEB128(string.size(), os);
os.write(string.data(), string.size());
}
void writeU8(raw_ostream &os, uint8_t byte, const Twine &msg) {
debugWrite(os.tell(), msg + " [0x" + utohexstr(byte) + "]");
os << byte;
}
void writeU32(raw_ostream &os, uint32_t number, const Twine &msg) {
debugWrite(os.tell(), msg + "[0x" + utohexstr(number) + "]");
support::endian::write(os, number, support::little);
}
void writeU64(raw_ostream &os, uint64_t number, const Twine &msg) {
debugWrite(os.tell(), msg + "[0x" + utohexstr(number) + "]");
support::endian::write(os, number, support::little);
}
void writeValueType(raw_ostream &os, ValType type, const Twine &msg) {
writeU8(os, static_cast<uint8_t>(type),
msg + "[type: " + toString(type) + "]");
}
void writeSig(raw_ostream &os, const WasmSignature &sig) {
writeU8(os, WASM_TYPE_FUNC, "signature type");
writeUleb128(os, sig.Params.size(), "param Count");
for (ValType paramType : sig.Params) {
writeValueType(os, paramType, "param type");
}
writeUleb128(os, sig.Returns.size(), "result Count");
for (ValType returnType : sig.Returns) {
writeValueType(os, returnType, "result type");
}
}
void writeI32Const(raw_ostream &os, int32_t number, const Twine &msg) {
writeU8(os, WASM_OPCODE_I32_CONST, "i32.const");
writeSleb128(os, number, msg);
}
void writeI64Const(raw_ostream &os, int64_t number, const Twine &msg) {
writeU8(os, WASM_OPCODE_I64_CONST, "i64.const");
writeSleb128(os, number, msg);
}
void writeMemArg(raw_ostream &os, uint32_t alignment, uint64_t offset) {
writeUleb128(os, alignment, "alignment");
writeUleb128(os, offset, "offset");
}
void writeInitExpr(raw_ostream &os, const WasmInitExpr &initExpr) {
writeU8(os, initExpr.Opcode, "opcode");
switch (initExpr.Opcode) {
case WASM_OPCODE_I32_CONST:
writeSleb128(os, initExpr.Value.Int32, "literal (i32)");
break;
case WASM_OPCODE_I64_CONST:
writeSleb128(os, initExpr.Value.Int64, "literal (i64)");
break;
case WASM_OPCODE_F32_CONST:
writeU32(os, initExpr.Value.Float32, "literal (f32)");
break;
case WASM_OPCODE_F64_CONST:
writeU64(os, initExpr.Value.Float64, "literal (f64)");
break;
case WASM_OPCODE_GLOBAL_GET:
writeUleb128(os, initExpr.Value.Global, "literal (global index)");
break;
case WASM_OPCODE_REF_NULL:
writeValueType(os, ValType::EXTERNREF, "literal (externref type)");
break;
default:
fatal("unknown opcode in init expr: " + Twine(initExpr.Opcode));
}
writeU8(os, WASM_OPCODE_END, "opcode:end");
}
void writeLimits(raw_ostream &os, const WasmLimits &limits) {
writeU8(os, limits.Flags, "limits flags");
writeUleb128(os, limits.Initial, "limits initial");
if (limits.Flags & WASM_LIMITS_FLAG_HAS_MAX)
writeUleb128(os, limits.Maximum, "limits max");
}
void writeGlobalType(raw_ostream &os, const WasmGlobalType &type) {
// TODO: Update WasmGlobalType to use ValType and remove this cast.
writeValueType(os, ValType(type.Type), "global type");
writeU8(os, type.Mutable, "global mutable");
}
void writeGlobal(raw_ostream &os, const WasmGlobal &global) {
writeGlobalType(os, global.Type);
writeInitExpr(os, global.InitExpr);
}
void writeEventType(raw_ostream &os, const WasmEventType &type) {
writeUleb128(os, type.Attribute, "event attribute");
writeUleb128(os, type.SigIndex, "sig index");
}
void writeEvent(raw_ostream &os, const WasmEvent &event) {
writeEventType(os, event.Type);
}
void writeTableType(raw_ostream &os, const llvm::wasm::WasmTable &type) {
writeU8(os, WASM_TYPE_FUNCREF, "table type");
writeLimits(os, type.Limits);
}
void writeImport(raw_ostream &os, const WasmImport &import) {
writeStr(os, import.Module, "import module name");
writeStr(os, import.Field, "import field name");
writeU8(os, import.Kind, "import kind");
switch (import.Kind) {
case WASM_EXTERNAL_FUNCTION:
writeUleb128(os, import.SigIndex, "import sig index");
break;
case WASM_EXTERNAL_GLOBAL:
writeGlobalType(os, import.Global);
break;
case WASM_EXTERNAL_EVENT:
writeEventType(os, import.Event);
break;
case WASM_EXTERNAL_MEMORY:
writeLimits(os, import.Memory);
break;
case WASM_EXTERNAL_TABLE:
writeTableType(os, import.Table);
break;
default:
fatal("unsupported import type: " + Twine(import.Kind));
}
}
void writeExport(raw_ostream &os, const WasmExport &export_) {
writeStr(os, export_.Name, "export name");
writeU8(os, export_.Kind, "export kind");
switch (export_.Kind) {
case WASM_EXTERNAL_FUNCTION:
writeUleb128(os, export_.Index, "function index");
break;
case WASM_EXTERNAL_GLOBAL:
writeUleb128(os, export_.Index, "global index");
break;
case WASM_EXTERNAL_EVENT:
writeUleb128(os, export_.Index, "event index");
break;
case WASM_EXTERNAL_MEMORY:
writeUleb128(os, export_.Index, "memory index");
break;
case WASM_EXTERNAL_TABLE:
writeUleb128(os, export_.Index, "table index");
break;
default:
fatal("unsupported export type: " + Twine(export_.Kind));
}
}
} // namespace wasm
} // namespace lld
| Java |
# Copyright 2015 Rafe Kaplan
#
# 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 . import parser
class Rule(parser.Parser):
def __init__(self, expected_attr_type=None):
self.__expected_attr_type = expected_attr_type
@property
def attr_type(self):
if self.__expected_attr_type:
return self.__expected_attr_type
else:
try:
inner_parser = self.__parser
except AttributeError:
raise NotImplementedError
else:
return inner_parser.attr_type
@property
def parser(self):
return self.__parser
@parser.setter
def parser(self, value):
if self.__expected_attr_type and self.__expected_attr_type != value.attr_type:
raise ValueError('Unexpected attribute type')
self.__parser = parser.as_parser(value)
def _parse(self, state, *args, **kwargs):
with state.open_scope(*args, **kwargs):
self.__parser._parse(state)
def __imod__(self, other):
self.parser = other
return self
def __call__(self, *args, **kwargs):
return RuleCall(self, *args, **kwargs)
class RuleCall(parser.Unary):
def __init__(self, rule, *args, **kwargs):
if not isinstance(rule, Rule):
raise TypeError('Expected rule to be type Rule, was {}'.format(type(rule).__name__))
super(RuleCall, self).__init__(rule)
self.__args = args
self.__kwargs = kwargs
@property
def args(self):
return self.__args
@property
def kwargs(self):
return dict(self.__kwargs)
def _parse(self, state):
args = [state.invoke(a) for a in self.__args]
kwargs = {k: state.invoke(v) for k, v in self.__kwargs.items()}
self.parser._parse(state, *args, **kwargs)
| Java |
package build
import sbt._
import Keys._
import Def.SettingsDefinition
final class MultiScalaProject private (private val projects: Map[String, Project])
extends CompositeProject {
import MultiScalaProject._
val v2_11: Project = projects("2.11")
val v2_12: Project = projects("2.12")
val v2_13: Project = projects("2.13")
def settings(ss: SettingsDefinition*): MultiScalaProject =
transform(_.settings(ss: _*))
def enablePlugins(ns: Plugins*): MultiScalaProject =
transform(_.enablePlugins(ns: _*))
def dependsOn(deps: ScopedMultiScalaProject*): MultiScalaProject = {
def classpathDependency(d: ScopedMultiScalaProject) =
strictMapValues(d.project.projects)(ClasspathDependency(_, d.configuration))
val depsByVersion: Map[String, Seq[ClasspathDependency]] =
strictMapValues(deps.flatMap(classpathDependency).groupBy(_._1))(_.map(_._2))
zipped(depsByVersion)(_.dependsOn(_: _*))
}
def configs(cs: Configuration*): MultiScalaProject =
transform(_.configs(cs: _*))
def zippedSettings(that: MultiScalaProject)(ss: Project => SettingsDefinition): MultiScalaProject =
zipped(that.projects)((p, sp) => p.settings(ss(sp)))
def zippedSettings(project: String)(ss: LocalProject => SettingsDefinition): MultiScalaProject =
zippedSettings(Seq(project))(ps => ss(ps(0)))
/** Set settings on this MultiScalaProject depending on other MultiScalaProjects by name.
*
* For every Scala version of this MultiScalaProject, `ss` is invoked onced
* with a LocalProjects corresponding to the names in projectNames with a
* suffix for that version.
*/
def zippedSettings(projectNames: Seq[String])(
ss: Seq[LocalProject] => SettingsDefinition): MultiScalaProject = {
val ps = for {
(v, p) <- projects
} yield {
val lps = projectNames.map(pn => LocalProject(projectID(pn, v)))
v -> p.settings(ss(lps))
}
new MultiScalaProject(ps)
}
def %(configuration: String) = new ScopedMultiScalaProject(this, Some(configuration))
override def componentProjects: Seq[Project] = projects.valuesIterator.toSeq
private def zipped[T](that: Map[String, T])(f: (Project, T) => Project): MultiScalaProject = {
val ps = for ((v, p) <- projects) yield v -> f(p, that(v))
new MultiScalaProject(ps)
}
private def transform(f: Project => Project): MultiScalaProject =
new MultiScalaProject(strictMapValues(projects)(f))
}
final class ScopedMultiScalaProject(val project: MultiScalaProject, val configuration: Option[String])
object ScopedMultiScalaProject {
implicit def fromMultiScalaProject(mp: MultiScalaProject): ScopedMultiScalaProject =
new ScopedMultiScalaProject(mp, None)
}
object MultiScalaProject {
private def strictMapValues[K, U, V](v: Map[K, U])(f: U => V): Map[K, V] =
v.map(v => (v._1, f(v._2)))
private final val versions = Map[String, Seq[String]](
"2.11" -> Seq("2.11.12"),
"2.12" -> Seq("2.12.1", "2.12.2", "2.12.3", "2.12.4", "2.12.5", "2.12.6", "2.12.7", "2.12.8", "2.12.9", "2.12.10", "2.12.11", "2.12.12", "2.12.13", "2.12.14", "2.12.15"),
"2.13" -> Seq("2.13.0", "2.13.1", "2.13.2", "2.13.3", "2.13.4", "2.13.5", "2.13.6", "2.13.7", "2.13.8"),
)
val Default2_11ScalaVersion = versions("2.11").last
val Default2_12ScalaVersion = versions("2.12").last
val Default2_13ScalaVersion = versions("2.13").last
/** The default Scala version is the default 2.12 Scala version, because it
* must work for sbt plugins.
*/
val DefaultScalaVersion = Default2_12ScalaVersion
private final val ideVersion = "2.12"
private def projectID(id: String, major: String) = id + major.replace('.', '_')
def apply(id: String, base: File): MultiScalaProject = {
val projects = for {
(major, minors) <- versions
} yield {
val noIDEExportSettings =
if (major == ideVersion) Nil
else NoIDEExport.noIDEExportSettings
major -> Project(id = projectID(id, major), base = new File(base, "." + major)).settings(
scalaVersion := minors.last,
crossScalaVersions := minors,
noIDEExportSettings,
)
}
new MultiScalaProject(projects).settings(
sourceDirectory := baseDirectory.value.getParentFile / "src",
)
}
}
| Java |
/*
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2019
*/
package com.ibm.streamsx.topology.internal.logging;
import java.util.logging.Level;
import java.util.logging.Logger;
public interface Logging {
/**
* Set the root logging levels from Python logging integer level.
* @param levelS
*/
public static void setRootLevels(String levelS) {
int loggingLevel = Integer.valueOf(levelS);
Level level;
if (loggingLevel >= 40) {
level = Level.SEVERE;
} else if (loggingLevel >= 30) {
level = Level.WARNING;
} else if (loggingLevel >= 20) {
level = Level.CONFIG;
} else {
level = Level.FINE;
}
Logger.getLogger("").setLevel(level);
}
}
| Java |
package wikokit.base.wikt.db;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/** Decompress ziped file.
*
* @see http://www.jondev.net/articles/Unzipping_Files_with_Android_%28Programmatically%29
*/
public class Decompressor {
private String _zipFile;
private String _location;
public Decompressor(String zipFile, String location) {
_zipFile = zipFile;
_location = location;
_dirChecker("");
}
public void unzip() {
try {
FileInputStream fin = new FileInputStream(_zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
Log.v("Decompress", "Unzipping " + ze.getName());
if(ze.isDirectory()) {
_dirChecker(ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(_location + ze.getName());
for (int c = zin.read(); c != -1; c = zin.read()) {
fout.write(c);
}
zin.closeEntry();
fout.close();
}
}
zin.close();
} catch(Exception e) {
Log.e("Decompress", "unzip", e);
}
}
private void _dirChecker(String dir) {
File f = new File(_location + dir);
if(!f.isDirectory()) {
f.mkdirs();
}
}
} | Java |
// --------------------------------------------------------------------------------------------------------------------
// <summary>
// The chat room controller.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace WebStreams.Sample
{
using System;
using System.Collections.Concurrent;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using Dapr.WebStreams.Server;
/// <summary>
/// The chat room controller.
/// </summary>
[RoutePrefix("/chat")]
public class ChatRoomController
{
/// <summary>
/// The chat rooms.
/// </summary>
private readonly ConcurrentDictionary<string, ISubject<ChatEvent>> rooms = new ConcurrentDictionary<string, ISubject<ChatEvent>>();
/// <summary>
/// The stream of room updates.
/// </summary>
private readonly ISubject<string> roomUpdates = new Subject<string>();
/// <summary>
/// Joins the calling user to a chat room.
/// </summary>
/// <param name="room">
/// The room name.
/// </param>
/// <param name="user">
/// The joining user's name.
/// </param>
/// <param name="messages">
/// The stream of chat messages from the user.
/// </param>
/// <returns>
/// The stream of chat events.
/// </returns>
[Route("join")]
public IObservable<ChatEvent> JoinRoom(string room, string user, IObservable<string> messages)
{
// Get or create the room being requested.
var roomStream = this.GetOrAddRoom(room);
// Send a happy little join message.
roomStream.OnNext(new ChatEvent
{
User = user,
Message = "Joined!",
Time = DateTime.UtcNow,
Type = "presence"
});
// Turn incoming messages into chat events and pipe them into the room.
messages.Select(message => new ChatEvent
{
User = user,
Message = message,
Time = DateTime.UtcNow
})
.Subscribe(
roomStream.OnNext,
() => roomStream.OnNext(new ChatEvent
{
User = user,
Message = "Left.",
Time = DateTime.UtcNow,
Type = "presence"
}));
return roomStream;
}
/// <summary>
/// Returns the stream of chat rooms.
/// </summary>
/// <returns>The stream of chat rooms.</returns>
[Route("rooms")]
public IObservable<string> GetRooms()
{
var result = new ReplaySubject<string>();
this.roomUpdates.Subscribe(result);
foreach (var channel in this.rooms.Keys)
{
result.OnNext(channel);
}
return result;
}
/// <summary>
/// Returns the chat room with the provided <paramref name="name"/>.
/// </summary>
/// <param name="name">
/// The room name.
/// </param>
/// <returns>
/// The chat room with the provided <paramref name="name"/>.
/// </returns>
private ISubject<ChatEvent> GetOrAddRoom(string name)
{
var added = default(ISubject<ChatEvent>);
var result = this.rooms.GetOrAdd(
name,
_ => added = new ReplaySubject<ChatEvent>(100));
// If a new room was actually added, fire an update.
if (result.Equals(added))
{
this.roomUpdates.OnNext(name);
}
return result;
}
}
} | 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.camel.component.jms.tx;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.spring.CamelSpringTestSupport;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Simple unit test for transaction client EIP pattern and JMS.
*/
public class JMSTransactionalClientWithRollbackTest extends CamelSpringTestSupport {
protected ClassPathXmlApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext(
"/org/apache/camel/component/jms/tx/JMSTransactionalClientWithRollbackTest.xml");
}
@Test
public void testTransactionSuccess() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(1);
mock.expectedBodiesReceived("Bye World");
// success at 3rd attempt
mock.message(0).header("count").isEqualTo(3);
template.sendBody("activemq:queue:okay", "Hello World");
mock.assertIsSatisfied();
}
public static class MyProcessor implements Processor {
private int count;
public void process(Exchange exchange) throws Exception {
exchange.getIn().setBody("Bye World");
exchange.getIn().setHeader("count", ++count);
}
}
} | Java |
(function() {
var head = document.head || document.getElementsByTagName('head')[0];
var style = null;
var mobileScreenWidth = 768;
// Make sure this value is equal to the width of .wy-nav-content in overrides.css.
var initialContentWidth = 960;
// Make sure this value is equal to the width of .wy-nav-side in theme.css.
var sideWidth = 300;
// Keeps the current width of .wy-nav-content.
var contentWidth = initialContentWidth;
// Centers the page content dynamically.
function centerPage() {
if (style) {
head.removeChild(style);
style = null;
}
var windowWidth = window.innerWidth;
if (windowWidth <= mobileScreenWidth) {
return;
}
var leftMargin = Math.max(0, (windowWidth - sideWidth - contentWidth) / 2);
var scrollbarWidth = document.body ? windowWidth - document.body.clientWidth : 0;
var css = '';
css += '.wy-nav-side { left: ' + leftMargin + 'px; }';
css += "\n";
css += '.wy-nav-content-wrap { margin-left: ' + (sideWidth + leftMargin) + 'px; }';
css += "\n";
css += '.github-fork-ribbon { margin-right: ' + (leftMargin - scrollbarWidth) + 'px; }';
css += "\n";
var newStyle = document.createElement('style');
newStyle.type = 'text/css';
if (newStyle.styleSheet) {
newStyle.styleSheet.cssText = css;
} else {
newStyle.appendChild(document.createTextNode(css));
}
head.appendChild(newStyle);
style = newStyle;
}
centerPage();
window.addEventListener('resize', centerPage);
// Adjust the position of the 'fork me at GitHub' ribbon after document.body is available,
// so that we can calculate the width of the scroll bar correctly.
window.addEventListener('DOMContentLoaded', centerPage);
// Allow a user to drag the left or right edge of the content to resize the content.
if (interact) {
interact('.wy-nav-content').resizable({
edges: {left: true, right: true, bottom: false, top: false},
modifiers: [
interact.modifiers.restrictEdges({
outer: 'parent',
endOnly: true
}),
interact.modifiers.restrictSize({
min: {
width: initialContentWidth,
height: 0
}
})
]
}).on('resizemove', function (event) {
var style = event.target.style;
// Double the amount of change because the page is centered.
contentWidth += event.deltaRect.width * 2;
style.maxWidth = contentWidth + 'px';
centerPage();
});
}
})(); | Java |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the Apache License Version 2.0.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
package com.microsoft.uprove;
import java.util.Arrays;
/**
* Specifies a U-Prove token.
*/
public class UProveToken {
private byte[] issuerParametersUID;
private byte[] publicKey;
private byte[] tokenInformation;
private byte[] proverInformation;
private byte[] sigmaZ;
private byte[] sigmaC;
private byte[] sigmaR;
private boolean isDeviceProtected = false;
/**
* Constructs a new U-Prove token.
*/
public UProveToken() {
super();
}
/**
* Constructs a new U-Prove token.
* @param issuerParametersUID an issuer parameters UID.
* @param publicKey a public key.
* @param tokenInformation a token information value.
* @param proverInformation a prover information value.
* @param sigmaZ a sigmaZ value.
* @param sigmaC a sigmaC value.
* @param sigmaR a sigmaR value.
* @param isDeviceProtected indicates if the token is Device-protected.
*/
public UProveToken(byte[] issuerParametersUID, byte[] publicKey,
byte[] tokenInformation, byte[] proverInformation,
byte[] sigmaZ, byte[] sigmaC,
byte[] sigmaR, boolean isDeviceProtected) {
super();
this.issuerParametersUID = issuerParametersUID;
this.publicKey = publicKey;
this.tokenInformation = tokenInformation;
this.proverInformation = proverInformation;
this.sigmaZ = sigmaZ;
this.sigmaC = sigmaC;
this.sigmaR = sigmaR;
this.isDeviceProtected = isDeviceProtected;
}
/**
* Gets the issuer parameters UID value.
* @return the issuerParameters UID value.
*/
public byte[] getIssuerParametersUID() {
return issuerParametersUID;
}
/**
* Sets the issuer parameters UID value.
* @param issuerParametersUID the issuerParameters UID value to set.
*/
public void setIssuerParametersUID(byte[] issuerParametersUID) {
this.issuerParametersUID = issuerParametersUID;
}
/**
* Gets the public key value.
* @return the publicKey value.
*/
public byte[] getPublicKey() {
return publicKey;
}
/**
* Sets the public key value.
* @param publicKey the public key value to set.
*/
public void setPublicKey(byte[] publicKey) {
this.publicKey = publicKey;
}
/**
* Gets the token information value.
* @return the token information value.
*/
public byte[] getTokenInformation() {
return tokenInformation;
}
/**
* Sets the token information value.
* @param tokenInformation the token information value to set.
*/
public void setTokenInformation(byte[] tokenInformation) {
this.tokenInformation = tokenInformation;
}
/**
* Gets the prover information value.
* @return the prover information value.
*/
public byte[] getProverInformation() {
return proverInformation;
}
/**
* Sets the prover information value.
* @param proverInformation the prover information value to set.
*/
public void setProverInformation(byte[] proverInformation) {
this.proverInformation = proverInformation;
}
/**
* Gets the sigmaZ value.
* @return the sigmaZ value.
*/
public byte[] getSigmaZ() {
return sigmaZ;
}
/**
* Sets the sigmaZ value.
* @param sigmaZ the sigmaZ value to set.
*/
public void setSigmaZ(byte[] sigmaZ) {
this.sigmaZ = sigmaZ;
}
/**
* Gets the sigmaC value.
* @return the sigmaC value.
*/
public byte[] getSigmaC() {
return sigmaC;
}
/**
* Sets the sigmaC value.
* @param sigmaC the sigmaC value to set.
*/
public void setSigmaC(byte[] sigmaC) {
this.sigmaC = sigmaC;
}
/**
* Gets the sigmaR value.
* @return the sigmaR value.
*/
public byte[] getSigmaR() {
return sigmaR;
}
/**
* Sets the sigmaR value.
* @param sigmaR the sigmaR value to set.
*/
public void setSigmaR(byte[] sigmaR) {
this.sigmaR = sigmaR;
}
/**
* Returns true if the token is Device-protected, false otherwise.
* @return the Device-protected boolean.
*/
boolean isDeviceProtected() {
return isDeviceProtected;
}
/**
* Sets the boolean indicating if the token is Device-protected.
* @param isDeviceProtected true if the token is Device-protected.
*/
void setIsDeviceProtected(boolean isDeviceProtected) {
this.isDeviceProtected = isDeviceProtected;
}
/**
* Indicates whether some other object is "equal to" this one.
* @param o the reference object with which to compare.
* @return <code>true</code> if this object is the same as the
* <code>o</code> argument; <code>false</code> otherwise.
*/
public boolean equals(final Object o) {
if (o == this) {
return true;
}
if (!(o instanceof UProveToken)) {
return false;
}
UProveToken upt = (UProveToken) o;
return
Arrays.equals(this.issuerParametersUID, upt.issuerParametersUID) &&
Arrays.equals(this.publicKey, upt.publicKey) &&
Arrays.equals(this.tokenInformation, upt.tokenInformation) &&
Arrays.equals(this.proverInformation, upt.proverInformation) &&
Arrays.equals(this.sigmaZ, upt.sigmaZ) &&
Arrays.equals(this.sigmaC, upt.sigmaC) &&
Arrays.equals(this.sigmaR, upt.sigmaR) &&
this.isDeviceProtected == upt.isDeviceProtected;
}
/**
* Returns a hash code value for the object.
* @return a hash code value for the object.
*/
public int hashCode() {
int result = 237;
result = 201 * result + Arrays.hashCode(this.issuerParametersUID);
result = 201 * result + Arrays.hashCode(this.publicKey);
result = 201 * result + Arrays.hashCode(this.tokenInformation);
result = 201 * result + Arrays.hashCode(this.proverInformation);
result = 201 * result + Arrays.hashCode(this.sigmaZ);
result = 201 * result + Arrays.hashCode(this.sigmaC);
result = 201 * result + Arrays.hashCode(this.sigmaR);
result = result + (this.isDeviceProtected ? 201 : 0);
return result;
}
}
| Java |
<?php
/*
* Copyright 2014 Google 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.
*/
namespace Google\Service\ServiceNetworking;
class LabelDescriptor extends \Google\Model
{
/**
* @var string
*/
public $description;
/**
* @var string
*/
public $key;
/**
* @var string
*/
public $valueType;
/**
* @param string
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* @param string
*/
public function setKey($key)
{
$this->key = $key;
}
/**
* @return string
*/
public function getKey()
{
return $this->key;
}
/**
* @param string
*/
public function setValueType($valueType)
{
$this->valueType = $valueType;
}
/**
* @return string
*/
public function getValueType()
{
return $this->valueType;
}
}
// Adding a class alias for backwards compatibility with the previous class name.
class_alias(LabelDescriptor::class, 'Google_Service_ServiceNetworking_LabelDescriptor');
| 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.olio.webapp.cache;
/**
* The cache interface provides all operations necessary for the cache.
* We could have extended java.util.Map but that would make a lot of
* unnecessary work for the scope of this project. We can always implement that
* interface later if desired.
*/
public interface Cache {
/**
* Gets the cached value based on a key.
* @param key The key
* @return The cached object, or null if none is available
*/
Object get(String key);
/**
* Sets a cached item using a key.
* @param key The key
* @param value The object to cache.
*/
void put(String key, Object value);
/**
* Sets a cached item using a key.
* @param key The key
* @param value The object to cache.
* @param timeToLive Time to cache this object in seconds
*/
void put(String key, Object value, long timeToLive);
/**
* Invalidates a cached item using a key
* @param key
* @return success
*/
boolean invalidate(String key);
/*
* Check if cache needs refresh based on existence cached object and of Semaphore
* @param key The key
* @param cacheObjPresent false if the cache object for this key exists
* @return true if the cache object needs a refresh
*/
boolean needsRefresh (boolean cacheObjPresent, String key);
void doneRefresh (String key, long timeToNextRefresh) throws CacheException;
boolean isLocal();
}
| 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.
*/
// script.aculo.us unittest.js v1.8.0_pre1, Fri Oct 12 21:34:51 +0200 2007
// Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// (c) 2005-2007 Jon Tirsen (http://www.tirsen.com)
// (c) 2005-2007 Michael Schuerig (http://www.schuerig.de/michael/)
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
// experimental, Firefox-only
Event.simulateMouse = function(element, eventName) {
var options = Object.extend({
pointerX: 0,
pointerY: 0,
buttons: 0,
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false
}, arguments[2] || {});
var oEvent = document.createEvent("MouseEvents");
oEvent.initMouseEvent(eventName, true, true, document.defaultView,
options.buttons, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, 0, $(element));
if(this.mark) Element.remove(this.mark);
this.mark = document.createElement('div');
this.mark.appendChild(document.createTextNode(" "));
document.body.appendChild(this.mark);
this.mark.style.position = 'absolute';
this.mark.style.top = options.pointerY + "px";
this.mark.style.left = options.pointerX + "px";
this.mark.style.width = "5px";
this.mark.style.height = "5px;";
this.mark.style.borderTop = "1px solid red;"
this.mark.style.borderLeft = "1px solid red;"
if(this.step)
alert('['+new Date().getTime().toString()+'] '+eventName+'/'+Test.Unit.inspect(options));
$(element).dispatchEvent(oEvent);
};
// Note: Due to a fix in Firefox 1.0.5/6 that probably fixed "too much", this doesn't work in 1.0.6 or DP2.
// You need to downgrade to 1.0.4 for now to get this working
// See https://bugzilla.mozilla.org/show_bug.cgi?id=289940 for the fix that fixed too much
Event.simulateKey = function(element, eventName) {
var options = Object.extend({
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false,
keyCode: 0,
charCode: 0
}, arguments[2] || {});
var oEvent = document.createEvent("KeyEvents");
oEvent.initKeyEvent(eventName, true, true, window,
options.ctrlKey, options.altKey, options.shiftKey, options.metaKey,
options.keyCode, options.charCode );
$(element).dispatchEvent(oEvent);
};
Event.simulateKeys = function(element, command) {
for(var i=0; i<command.length; i++) {
Event.simulateKey(element,'keypress',{charCode:command.charCodeAt(i)});
}
};
var Test = {}
Test.Unit = {};
// security exception workaround
Test.Unit.inspect = Object.inspect;
Test.Unit.Logger = Class.create();
Test.Unit.Logger.prototype = {
initialize: function(log) {
this.log = $(log);
if (this.log) {
this._createLogTable();
}
},
start: function(testName) {
if (!this.log) return;
this.testName = testName;
this.lastLogLine = document.createElement('tr');
this.statusCell = document.createElement('td');
this.nameCell = document.createElement('td');
this.nameCell.className = "nameCell";
this.nameCell.appendChild(document.createTextNode(testName));
this.messageCell = document.createElement('td');
this.lastLogLine.appendChild(this.statusCell);
this.lastLogLine.appendChild(this.nameCell);
this.lastLogLine.appendChild(this.messageCell);
this.loglines.appendChild(this.lastLogLine);
},
finish: function(status, summary) {
if (!this.log) return;
this.lastLogLine.className = status;
this.statusCell.innerHTML = status;
this.messageCell.innerHTML = this._toHTML(summary);
this.addLinksToResults();
},
message: function(message) {
if (!this.log) return;
this.messageCell.innerHTML = this._toHTML(message);
},
summary: function(summary) {
if (!this.log) return;
this.logsummary.innerHTML = this._toHTML(summary);
},
_createLogTable: function() {
this.log.innerHTML =
'<div id="logsummary"></div>' +
'<table id="logtable">' +
'<thead><tr><th>Status</th><th>Test</th><th>Message</th></tr></thead>' +
'<tbody id="loglines"></tbody>' +
'</table>';
this.logsummary = $('logsummary')
this.loglines = $('loglines');
},
_toHTML: function(txt) {
return txt.escapeHTML().replace(/\n/g,"<br/>");
},
addLinksToResults: function(){
$$("tr.failed .nameCell").each( function(td){ // todo: limit to children of this.log
td.title = "Run only this test"
Event.observe(td, 'click', function(){ window.location.search = "?tests=" + td.innerHTML;});
});
$$("tr.passed .nameCell").each( function(td){ // todo: limit to children of this.log
td.title = "Run all tests"
Event.observe(td, 'click', function(){ window.location.search = "";});
});
}
}
Test.Unit.Runner = Class.create();
Test.Unit.Runner.prototype = {
initialize: function(testcases) {
this.options = Object.extend({
testLog: 'testlog'
}, arguments[1] || {});
this.options.resultsURL = this.parseResultsURLQueryParameter();
this.options.tests = this.parseTestsQueryParameter();
if (this.options.testLog) {
this.options.testLog = $(this.options.testLog) || null;
}
if(this.options.tests) {
this.tests = [];
for(var i = 0; i < this.options.tests.length; i++) {
if(/^test/.test(this.options.tests[i])) {
this.tests.push(new Test.Unit.Testcase(this.options.tests[i], testcases[this.options.tests[i]], testcases["setup"], testcases["teardown"]));
}
}
} else {
if (this.options.test) {
this.tests = [new Test.Unit.Testcase(this.options.test, testcases[this.options.test], testcases["setup"], testcases["teardown"])];
} else {
this.tests = [];
for(var testcase in testcases) {
if(/^test/.test(testcase)) {
this.tests.push(
new Test.Unit.Testcase(
this.options.context ? ' -> ' + this.options.titles[testcase] : testcase,
testcases[testcase], testcases["setup"], testcases["teardown"]
));
}
}
}
}
this.currentTest = 0;
this.logger = new Test.Unit.Logger(this.options.testLog);
setTimeout(this.runTests.bind(this), 1000);
},
parseResultsURLQueryParameter: function() {
return window.location.search.parseQuery()["resultsURL"];
},
parseTestsQueryParameter: function(){
if (window.location.search.parseQuery()["tests"]){
return window.location.search.parseQuery()["tests"].split(',');
};
},
// Returns:
// "ERROR" if there was an error,
// "FAILURE" if there was a failure, or
// "SUCCESS" if there was neither
getResult: function() {
var hasFailure = false;
for(var i=0;i<this.tests.length;i++) {
if (this.tests[i].errors > 0) {
return "ERROR";
}
if (this.tests[i].failures > 0) {
hasFailure = true;
}
}
if (hasFailure) {
return "FAILURE";
} else {
return "SUCCESS";
}
},
postResults: function() {
if (this.options.resultsURL) {
new Ajax.Request(this.options.resultsURL,
{ method: 'get', parameters: 'result=' + this.getResult(), asynchronous: false });
}
},
runTests: function() {
var test = this.tests[this.currentTest];
if (!test) {
// finished!
this.postResults();
this.logger.summary(this.summary());
return;
}
if(!test.isWaiting) {
this.logger.start(test.name);
}
test.run();
if(test.isWaiting) {
this.logger.message("Waiting for " + test.timeToWait + "ms");
setTimeout(this.runTests.bind(this), test.timeToWait || 1000);
} else {
this.logger.finish(test.status(), test.summary());
this.currentTest++;
// tail recursive, hopefully the browser will skip the stackframe
this.runTests();
}
},
summary: function() {
var assertions = 0;
var failures = 0;
var errors = 0;
var messages = [];
for(var i=0;i<this.tests.length;i++) {
assertions += this.tests[i].assertions;
failures += this.tests[i].failures;
errors += this.tests[i].errors;
}
return (
(this.options.context ? this.options.context + ': ': '') +
this.tests.length + " tests, " +
assertions + " assertions, " +
failures + " failures, " +
errors + " errors");
}
}
Test.Unit.Assertions = Class.create();
Test.Unit.Assertions.prototype = {
initialize: function() {
this.assertions = 0;
this.failures = 0;
this.errors = 0;
this.messages = [];
},
summary: function() {
return (
this.assertions + " assertions, " +
this.failures + " failures, " +
this.errors + " errors" + "\n" +
this.messages.join("\n"));
},
pass: function() {
this.assertions++;
},
fail: function(message) {
this.failures++;
this.messages.push("Failure: " + message);
},
info: function(message) {
this.messages.push("Info: " + message);
},
error: function(error) {
this.errors++;
this.messages.push(error.name + ": "+ error.message + "(" + Test.Unit.inspect(error) +")");
},
status: function() {
if (this.failures > 0) return 'failed';
if (this.errors > 0) return 'error';
return 'passed';
},
assert: function(expression) {
var message = arguments[1] || 'assert: got "' + Test.Unit.inspect(expression) + '"';
try { expression ? this.pass() :
this.fail(message); }
catch(e) { this.error(e); }
},
assertEqual: function(expected, actual) {
var message = arguments[2] || "assertEqual";
try { (expected == actual) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertInspect: function(expected, actual) {
var message = arguments[2] || "assertInspect";
try { (expected == actual.inspect()) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertEnumEqual: function(expected, actual) {
var message = arguments[2] || "assertEnumEqual";
try { $A(expected).length == $A(actual).length &&
expected.zip(actual).all(function(pair) { return pair[0] == pair[1] }) ?
this.pass() : this.fail(message + ': expected ' + Test.Unit.inspect(expected) +
', actual ' + Test.Unit.inspect(actual)); }
catch(e) { this.error(e); }
},
assertNotEqual: function(expected, actual) {
var message = arguments[2] || "assertNotEqual";
try { (expected != actual) ? this.pass() :
this.fail(message + ': got "' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertIdentical: function(expected, actual) {
var message = arguments[2] || "assertIdentical";
try { (expected === actual) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertNotIdentical: function(expected, actual) {
var message = arguments[2] || "assertNotIdentical";
try { !(expected === actual) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertNull: function(obj) {
var message = arguments[1] || 'assertNull'
try { (obj==null) ? this.pass() :
this.fail(message + ': got "' + Test.Unit.inspect(obj) + '"'); }
catch(e) { this.error(e); }
},
assertMatch: function(expected, actual) {
var message = arguments[2] || 'assertMatch';
var regex = new RegExp(expected);
try { (regex.exec(actual)) ? this.pass() :
this.fail(message + ' : regex: "' + Test.Unit.inspect(expected) + ' did not match: ' + Test.Unit.inspect(actual) + '"'); }
catch(e) { this.error(e); }
},
assertHidden: function(element) {
var message = arguments[1] || 'assertHidden';
this.assertEqual("none", element.style.display, message);
},
assertNotNull: function(object) {
var message = arguments[1] || 'assertNotNull';
this.assert(object != null, message);
},
assertType: function(expected, actual) {
var message = arguments[2] || 'assertType';
try {
(actual.constructor == expected) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + (actual.constructor) + '"'); }
catch(e) { this.error(e); }
},
assertNotOfType: function(expected, actual) {
var message = arguments[2] || 'assertNotOfType';
try {
(actual.constructor != expected) ? this.pass() :
this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
'", actual "' + (actual.constructor) + '"'); }
catch(e) { this.error(e); }
},
assertInstanceOf: function(expected, actual) {
var message = arguments[2] || 'assertInstanceOf';
try {
(actual instanceof expected) ? this.pass() :
this.fail(message + ": object was not an instance of the expected type"); }
catch(e) { this.error(e); }
},
assertNotInstanceOf: function(expected, actual) {
var message = arguments[2] || 'assertNotInstanceOf';
try {
!(actual instanceof expected) ? this.pass() :
this.fail(message + ": object was an instance of the not expected type"); }
catch(e) { this.error(e); }
},
assertRespondsTo: function(method, obj) {
var message = arguments[2] || 'assertRespondsTo';
try {
(obj[method] && typeof obj[method] == 'function') ? this.pass() :
this.fail(message + ": object doesn't respond to [" + method + "]"); }
catch(e) { this.error(e); }
},
assertReturnsTrue: function(method, obj) {
var message = arguments[2] || 'assertReturnsTrue';
try {
var m = obj[method];
if(!m) m = obj['is'+method.charAt(0).toUpperCase()+method.slice(1)];
m() ? this.pass() :
this.fail(message + ": method returned false"); }
catch(e) { this.error(e); }
},
assertReturnsFalse: function(method, obj) {
var message = arguments[2] || 'assertReturnsFalse';
try {
var m = obj[method];
if(!m) m = obj['is'+method.charAt(0).toUpperCase()+method.slice(1)];
!m() ? this.pass() :
this.fail(message + ": method returned true"); }
catch(e) { this.error(e); }
},
assertRaise: function(exceptionName, method) {
var message = arguments[2] || 'assertRaise';
try {
method();
this.fail(message + ": exception expected but none was raised"); }
catch(e) {
((exceptionName == null) || (e.name==exceptionName)) ? this.pass() : this.error(e);
}
},
assertElementsMatch: function() {
var expressions = $A(arguments), elements = $A(expressions.shift());
if (elements.length != expressions.length) {
this.fail('assertElementsMatch: size mismatch: ' + elements.length + ' elements, ' + expressions.length + ' expressions');
return false;
}
elements.zip(expressions).all(function(pair, index) {
var element = $(pair.first()), expression = pair.last();
if (element.match(expression)) return true;
this.fail('assertElementsMatch: (in index ' + index + ') expected ' + expression.inspect() + ' but got ' + element.inspect());
}.bind(this)) && this.pass();
},
assertElementMatches: function(element, expression) {
this.assertElementsMatch([element], expression);
},
benchmark: function(operation, iterations) {
var startAt = new Date();
(iterations || 1).times(operation);
var timeTaken = ((new Date())-startAt);
this.info((arguments[2] || 'Operation') + ' finished ' +
iterations + ' iterations in ' + (timeTaken/1000)+'s' );
return timeTaken;
},
_isVisible: function(element) {
element = $(element);
if(!element.parentNode) return true;
this.assertNotNull(element);
if(element.style && Element.getStyle(element, 'display') == 'none')
return false;
return this._isVisible(element.parentNode);
},
assertNotVisible: function(element) {
this.assert(!this._isVisible(element), Test.Unit.inspect(element) + " was not hidden and didn't have a hidden parent either. " + ("" || arguments[1]));
},
assertVisible: function(element) {
this.assert(this._isVisible(element), Test.Unit.inspect(element) + " was not visible. " + ("" || arguments[1]));
},
benchmark: function(operation, iterations) {
var startAt = new Date();
(iterations || 1).times(operation);
var timeTaken = ((new Date())-startAt);
this.info((arguments[2] || 'Operation') + ' finished ' +
iterations + ' iterations in ' + (timeTaken/1000)+'s' );
return timeTaken;
}
}
Test.Unit.Testcase = Class.create();
Object.extend(Object.extend(Test.Unit.Testcase.prototype, Test.Unit.Assertions.prototype), {
initialize: function(name, test, setup, teardown) {
Test.Unit.Assertions.prototype.initialize.bind(this)();
this.name = name;
if(typeof test == 'string') {
test = test.gsub(/(\.should[^\(]+\()/,'#{0}this,');
test = test.gsub(/(\.should[^\(]+)\(this,\)/,'#{1}(this)');
this.test = function() {
eval('with(this){'+test+'}');
}
} else {
this.test = test || function() {};
}
this.setup = setup || function() {};
this.teardown = teardown || function() {};
this.isWaiting = false;
this.timeToWait = 1000;
},
wait: function(time, nextPart) {
this.isWaiting = true;
this.test = nextPart;
this.timeToWait = time;
},
run: function() {
try {
try {
if (!this.isWaiting) this.setup.bind(this)();
this.isWaiting = false;
this.test.bind(this)();
} finally {
if(!this.isWaiting) {
this.teardown.bind(this)();
}
}
}
catch(e) { this.error(e); }
}
});
// *EXPERIMENTAL* BDD-style testing to please non-technical folk
// This draws many ideas from RSpec http://rspec.rubyforge.org/
Test.setupBDDExtensionMethods = function(){
var METHODMAP = {
shouldEqual: 'assertEqual',
shouldNotEqual: 'assertNotEqual',
shouldEqualEnum: 'assertEnumEqual',
shouldBeA: 'assertType',
shouldNotBeA: 'assertNotOfType',
shouldBeAn: 'assertType',
shouldNotBeAn: 'assertNotOfType',
shouldBeNull: 'assertNull',
shouldNotBeNull: 'assertNotNull',
shouldBe: 'assertReturnsTrue',
shouldNotBe: 'assertReturnsFalse',
shouldRespondTo: 'assertRespondsTo'
};
var makeAssertion = function(assertion, args, object) {
this[assertion].apply(this,(args || []).concat([object]));
}
Test.BDDMethods = {};
$H(METHODMAP).each(function(pair) {
Test.BDDMethods[pair.key] = function() {
var args = $A(arguments);
var scope = args.shift();
makeAssertion.apply(scope, [pair.value, args, this]); };
});
[Array.prototype, String.prototype, Number.prototype, Boolean.prototype].each(
function(p){ Object.extend(p, Test.BDDMethods) }
);
}
Test.context = function(name, spec, log){
Test.setupBDDExtensionMethods();
var compiledSpec = {};
var titles = {};
for(specName in spec) {
switch(specName){
case "setup":
case "teardown":
compiledSpec[specName] = spec[specName];
break;
default:
var testName = 'test'+specName.gsub(/\s+/,'-').camelize();
var body = spec[specName].toString().split('\n').slice(1);
if(/^\{/.test(body[0])) body = body.slice(1);
body.pop();
body = body.map(function(statement){
return statement.strip()
});
compiledSpec[testName] = body.join('\n');
titles[testName] = specName;
}
}
new Test.Unit.Runner(compiledSpec, { titles: titles, testLog: log || 'testlog', context: name });
}; | Java |
/*
* Copyright (c) 2020 Nordic Semiconductor ASA
*
* SPDX-License-Identifier: Apache-2.0
*/
/* Performs initialization of Direction Finding in Host */
int le_df_init(void);
void hci_df_prepare_connectionless_iq_report(struct net_buf *buf,
struct bt_df_per_adv_sync_iq_samples_report *report,
struct bt_le_per_adv_sync **per_adv_sync_to_report);
| 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 Thu Nov 13 21:22:01 UTC 2014 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class org.apache.hadoop.yarn.applications.distributedshell.ApplicationMaster (Apache Hadoop Main 2.6.0 API)
</TITLE>
<META NAME="date" CONTENT="2014-11-13">
<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.yarn.applications.distributedshell.ApplicationMaster (Apache Hadoop Main 2.6.0 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/yarn/applications/distributedshell/ApplicationMaster.html" title="class in org.apache.hadoop.yarn.applications.distributedshell"><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/yarn/applications/distributedshell//class-useApplicationMaster.html" target="_top"><B>FRAMES</B></A>
<A HREF="ApplicationMaster.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.yarn.applications.distributedshell.ApplicationMaster</B></H2>
</CENTER>
No usage of org.apache.hadoop.yarn.applications.distributedshell.ApplicationMaster
<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/yarn/applications/distributedshell/ApplicationMaster.html" title="class in org.apache.hadoop.yarn.applications.distributedshell"><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/yarn/applications/distributedshell//class-useApplicationMaster.html" target="_top"><B>FRAMES</B></A>
<A HREF="ApplicationMaster.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">Apache Software Foundation</a>. All Rights Reserved.
</BODY>
</HTML>
| Java |
// Copyright 2004 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.apache.tapestry.vlib.ejb;
import java.rmi.RemoteException;
import javax.ejb.EJBObject;
/**
* Remote interface for the BookQuery stateless session bean.
*
* @version $Id$
* @author Howard Lewis Ship
*
**/
public interface IBookQuery extends EJBObject
{
/**
* Returns the total number of results rows in the query.
*
**/
public int getResultCount() throws RemoteException;
/**
* Returns a selected subset of the results.
*
**/
public Book[] get(int offset, int length) throws RemoteException;
/**
* Performs a query of books with the matching title and (optionally) publisher.
*
* @param parameters defines subset of books to return.
* @param sortOrdering order of items in result set.
*
**/
public int masterQuery(MasterQueryParameters parameters, SortOrdering sortOrdering) throws RemoteException;
/**
* Queries on books owned by a given person.
*
**/
public int ownerQuery(Integer ownerPK, SortOrdering sortOrdering) throws RemoteException;
/**
* Queries on books held by a given person.
*
**/
public int holderQuery(Integer holderPK, SortOrdering sortOrdering) throws RemoteException;
/**
* Queries the list of books held by the borrower but not owned by the borrower.
*
**/
public int borrowerQuery(Integer borrowerPK, SortOrdering sortOrdering) throws RemoteException;
} | Java |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.structuralsearch.impl.matcher.compiler;
import com.intellij.codeInsight.template.Template;
import com.intellij.codeInsight.template.TemplateManager;
import com.intellij.dupLocator.util.NodeFilter;
import com.intellij.lang.Language;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.LanguageFileType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiErrorElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiRecursiveElementWalkingVisitor;
import com.intellij.psi.impl.source.tree.LeafElement;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.structuralsearch.*;
import com.intellij.structuralsearch.impl.matcher.CompiledPattern;
import com.intellij.structuralsearch.impl.matcher.MatcherImplUtil;
import com.intellij.structuralsearch.impl.matcher.PatternTreeContext;
import com.intellij.structuralsearch.impl.matcher.filters.LexicalNodesFilter;
import com.intellij.structuralsearch.impl.matcher.handlers.MatchingHandler;
import com.intellij.structuralsearch.impl.matcher.handlers.SubstitutionHandler;
import com.intellij.structuralsearch.impl.matcher.predicates.*;
import com.intellij.structuralsearch.plugin.ui.Configuration;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.SmartList;
import gnu.trove.TIntArrayList;
import gnu.trove.TIntHashSet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Compiles the handlers for usability
*/
public class PatternCompiler {
private static CompileContext lastTestingContext;
public static CompiledPattern compilePattern(final Project project, final MatchOptions options)
throws MalformedPatternException, NoMatchFoundException, UnsupportedOperationException {
FileType fileType = options.getFileType();
assert fileType instanceof LanguageFileType;
Language language = ((LanguageFileType)fileType).getLanguage();
StructuralSearchProfile profile = StructuralSearchUtil.getProfileByLanguage(language);
assert profile != null;
CompiledPattern result = profile.createCompiledPattern();
final String[] prefixes = result.getTypedVarPrefixes();
assert prefixes.length > 0;
final CompileContext context = new CompileContext(result, options, project);
if (ApplicationManager.getApplication().isUnitTestMode()) lastTestingContext = context;
try {
List<PsiElement> elements = compileByAllPrefixes(project, options, result, context, prefixes);
final CompiledPattern pattern = context.getPattern();
checkForUnknownVariables(pattern, elements);
pattern.setNodes(elements);
if (context.getSearchHelper().doOptimizing() && context.getSearchHelper().isScannedSomething()) {
final Set<PsiFile> set = context.getSearchHelper().getFilesSetToScan();
final List<PsiFile> filesToScan = new SmartList<>();
final GlobalSearchScope scope = (GlobalSearchScope)options.getScope();
for (final PsiFile file : set) {
if (!scope.contains(file.getVirtualFile())) {
continue;
}
filesToScan.add(file);
}
if (filesToScan.size() == 0) {
throw new NoMatchFoundException(SSRBundle.message("ssr.will.not.find.anything", scope.getDisplayName()));
}
result.setScope(new LocalSearchScope(PsiUtilCore.toPsiElementArray(filesToScan)));
}
} finally {
context.clear();
}
return result;
}
private static void checkForUnknownVariables(final CompiledPattern pattern, List<PsiElement> elements) {
for (PsiElement element : elements) {
element.accept(new PsiRecursiveElementWalkingVisitor() {
@Override
public void visitElement(PsiElement element) {
if (element.getUserData(CompiledPattern.HANDLER_KEY) != null) {
return;
}
super.visitElement(element);
if (!(element instanceof LeafElement) || !pattern.isTypedVar(element)) {
return;
}
final MatchingHandler handler = pattern.getHandler(pattern.getTypedVarString(element));
if (handler == null) {
throw new MalformedPatternException();
}
}
});
}
}
public static String getLastFindPlan() {
return ((TestModeOptimizingSearchHelper)lastTestingContext.getSearchHelper()).getSearchPlan();
}
@NotNull
private static List<PsiElement> compileByAllPrefixes(Project project,
MatchOptions options,
CompiledPattern pattern,
CompileContext context,
String[] applicablePrefixes) throws MalformedPatternException {
if (applicablePrefixes.length == 0) {
return Collections.emptyList();
}
List<PsiElement> elements = doCompile(project, options, pattern, new ConstantPrefixProvider(applicablePrefixes[0]), context);
if (elements.isEmpty()) {
return elements;
}
final PsiFile file = elements.get(0).getContainingFile();
if (file == null) {
return elements;
}
final PsiElement last = elements.get(elements.size() - 1);
final Pattern[] patterns = new Pattern[applicablePrefixes.length];
for (int i = 0; i < applicablePrefixes.length; i++) {
patterns[i] = Pattern.compile(StructuralSearchUtil.shieldRegExpMetaChars(applicablePrefixes[i]) + "\\w+\\b");
}
final int[] varEndOffsets = findAllTypedVarOffsets(file, patterns);
final int patternEndOffset = last.getTextRange().getEndOffset();
if (elements.size() == 0 ||
checkErrorElements(file, patternEndOffset, patternEndOffset, varEndOffsets, true) != Boolean.TRUE) {
return elements;
}
final int varCount = varEndOffsets.length;
final String[] prefixSequence = new String[varCount];
for (int i = 0; i < varCount; i++) {
prefixSequence[i] = applicablePrefixes[0];
}
final List<PsiElement> finalElements =
compileByPrefixes(project, options, pattern, context, applicablePrefixes, patterns, prefixSequence, 0);
return finalElements != null
? finalElements
: doCompile(project, options, pattern, new ConstantPrefixProvider(applicablePrefixes[0]), context);
}
@Nullable
private static List<PsiElement> compileByPrefixes(Project project,
MatchOptions options,
CompiledPattern pattern,
CompileContext context,
String[] applicablePrefixes,
Pattern[] substitutionPatterns,
String[] prefixSequence,
int index) throws MalformedPatternException {
if (index >= prefixSequence.length) {
final List<PsiElement> elements = doCompile(project, options, pattern, new ArrayPrefixProvider(prefixSequence), context);
if (elements.isEmpty()) {
return elements;
}
final PsiElement parent = elements.get(0).getParent();
final PsiElement last = elements.get(elements.size() - 1);
final int[] varEndOffsets = findAllTypedVarOffsets(parent.getContainingFile(), substitutionPatterns);
final int patternEndOffset = last.getTextRange().getEndOffset();
return checkErrorElements(parent, patternEndOffset, patternEndOffset, varEndOffsets, false) != Boolean.TRUE
? elements
: null;
}
String[] alternativeVariant = null;
for (String applicablePrefix : applicablePrefixes) {
prefixSequence[index] = applicablePrefix;
List<PsiElement> elements = doCompile(project, options, pattern, new ArrayPrefixProvider(prefixSequence), context);
if (elements.isEmpty()) {
return elements;
}
final PsiFile file = elements.get(0).getContainingFile();
if (file == null) {
return elements;
}
final int[] varEndOffsets = findAllTypedVarOffsets(file, substitutionPatterns);
final int offset = varEndOffsets[index];
final int patternEndOffset = elements.get(elements.size() - 1).getTextRange().getEndOffset();
final Boolean result = checkErrorElements(file, offset, patternEndOffset, varEndOffsets, false);
if (result == Boolean.TRUE) {
continue;
}
if (result == Boolean.FALSE || (result == null && alternativeVariant == null)) {
final List<PsiElement> finalElements =
compileByPrefixes(project, options, pattern, context, applicablePrefixes, substitutionPatterns, prefixSequence, index + 1);
if (finalElements != null) {
if (result == Boolean.FALSE) {
return finalElements;
}
alternativeVariant = new String[prefixSequence.length];
System.arraycopy(prefixSequence, 0, alternativeVariant, 0, prefixSequence.length);
}
}
}
return alternativeVariant != null ?
compileByPrefixes(project, options, pattern, context, applicablePrefixes, substitutionPatterns, alternativeVariant, index + 1) :
null;
}
@NotNull
private static int[] findAllTypedVarOffsets(final PsiFile file, final Pattern[] substitutionPatterns) {
final TIntHashSet result = new TIntHashSet();
file.accept(new PsiRecursiveElementWalkingVisitor() {
@Override
public void visitElement(PsiElement element) {
super.visitElement(element);
if (element instanceof LeafElement) {
final String text = element.getText();
for (Pattern pattern : substitutionPatterns) {
final Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
result.add(element.getTextRange().getStartOffset() + matcher.end());
}
}
}
}
});
final int[] resultArray = result.toArray();
Arrays.sort(resultArray);
return resultArray;
}
/**
* False: there are no error elements before offset, except patternEndOffset
* Null: there are only error elements located exactly after template variables or at the end of the pattern
* True: otherwise
*/
@Nullable
private static Boolean checkErrorElements(PsiElement element,
final int offset,
final int patternEndOffset,
final int[] varEndOffsets,
final boolean strict) {
final TIntArrayList errorOffsets = new TIntArrayList();
final boolean[] containsErrorTail = {false};
final TIntHashSet varEndOffsetsSet = new TIntHashSet(varEndOffsets);
element.accept(new PsiRecursiveElementWalkingVisitor() {
@Override
public void visitErrorElement(PsiErrorElement element) {
super.visitErrorElement(element);
final int startOffset = element.getTextRange().getStartOffset();
if ((strict || !varEndOffsetsSet.contains(startOffset)) && startOffset != patternEndOffset) {
errorOffsets.add(startOffset);
}
if (startOffset == offset) {
containsErrorTail[0] = true;
}
}
});
for (int i = 0; i < errorOffsets.size(); i++) {
final int errorOffset = errorOffsets.get(i);
if (errorOffset <= offset) {
return true;
}
}
return containsErrorTail[0] ? null : false;
}
private interface PrefixProvider {
String getPrefix(int varIndex);
}
private static class ConstantPrefixProvider implements PrefixProvider {
private final String myPrefix;
ConstantPrefixProvider(String prefix) {
myPrefix = prefix;
}
@Override
public String getPrefix(int varIndex) {
return myPrefix;
}
}
private static class ArrayPrefixProvider implements PrefixProvider {
private final String[] myPrefixes;
ArrayPrefixProvider(String[] prefixes) {
myPrefixes = prefixes;
}
@Override
public String getPrefix(int varIndex) {
if (varIndex >= myPrefixes.length) return null;
return myPrefixes[varIndex];
}
}
private static List<PsiElement> doCompile(Project project,
MatchOptions options,
CompiledPattern result,
PrefixProvider prefixProvider,
CompileContext context) throws MalformedPatternException {
result.clearHandlers();
final StringBuilder buf = new StringBuilder();
Template template = TemplateManager.getInstance(project).createTemplate("","",options.getSearchPattern());
int segmentsCount = template.getSegmentsCount();
String text = template.getTemplateText();
int prevOffset = 0;
for(int i=0;i<segmentsCount;++i) {
final int offset = template.getSegmentOffset(i);
final String name = template.getSegmentName(i);
final String prefix = prefixProvider.getPrefix(i);
if (prefix == null) {
throw new MalformedPatternException();
}
buf.append(text.substring(prevOffset,offset));
buf.append(prefix);
buf.append(name);
MatchVariableConstraint constraint = options.getVariableConstraint(name);
if (constraint==null) {
// we do not edited the constraints
constraint = new MatchVariableConstraint();
constraint.setName( name );
options.addVariableConstraint(constraint);
}
SubstitutionHandler handler = result.createSubstitutionHandler(
name,
prefix + name,
constraint.isPartOfSearchResults(),
constraint.getMinCount(),
constraint.getMaxCount(),
constraint.isGreedy()
);
if(constraint.isWithinHierarchy()) {
handler.setSubtype(true);
}
if(constraint.isStrictlyWithinHierarchy()) {
handler.setStrictSubtype(true);
}
MatchPredicate predicate;
if (!StringUtil.isEmptyOrSpaces(constraint.getRegExp())) {
predicate = new RegExpPredicate(
constraint.getRegExp(),
options.isCaseSensitiveMatch(),
name,
constraint.isWholeWordsOnly(),
constraint.isPartOfSearchResults()
);
if (constraint.isInvertRegExp()) {
predicate = new NotPredicate(predicate);
}
addPredicate(handler,predicate);
}
if (constraint.isReference()) {
predicate = new ReferencePredicate( constraint.getNameOfReferenceVar() );
if (constraint.isInvertReference()) {
predicate = new NotPredicate(predicate);
}
addPredicate(handler,predicate);
}
addExtensionPredicates(options, constraint, handler);
addScriptConstraint(project, name, constraint, handler);
if (!StringUtil.isEmptyOrSpaces(constraint.getContainsConstraint())) {
predicate = new ContainsPredicate(name, constraint.getContainsConstraint());
if (constraint.isInvertContainsConstraint()) {
predicate = new NotPredicate(predicate);
}
addPredicate(handler,predicate);
}
if (!StringUtil.isEmptyOrSpaces(constraint.getWithinConstraint())) {
assert false;
}
prevOffset = offset;
}
MatchVariableConstraint constraint = options.getVariableConstraint(Configuration.CONTEXT_VAR_NAME);
if (constraint != null) {
SubstitutionHandler handler = result.createSubstitutionHandler(
Configuration.CONTEXT_VAR_NAME,
Configuration.CONTEXT_VAR_NAME,
constraint.isPartOfSearchResults(),
constraint.getMinCount(),
constraint.getMaxCount(),
constraint.isGreedy()
);
if (!StringUtil.isEmptyOrSpaces(constraint.getWithinConstraint())) {
MatchPredicate predicate = new WithinPredicate(constraint.getWithinConstraint(), options.getFileType(), project);
if (constraint.isInvertWithinConstraint()) {
predicate = new NotPredicate(predicate);
}
addPredicate(handler,predicate);
}
addExtensionPredicates(options, constraint, handler);
addScriptConstraint(project, Configuration.CONTEXT_VAR_NAME, constraint, handler);
}
buf.append(text.substring(prevOffset,text.length()));
PsiElement[] matchStatements;
try {
matchStatements = MatcherImplUtil.createTreeFromText(buf.toString(), PatternTreeContext.Block, options.getFileType(),
options.getDialect(), options.getPatternContext(), project, false);
if (matchStatements.length==0) throw new MalformedPatternException();
} catch (IncorrectOperationException e) {
throw new MalformedPatternException(e.getMessage());
}
NodeFilter filter = LexicalNodesFilter.getInstance();
GlobalCompilingVisitor compilingVisitor = new GlobalCompilingVisitor();
compilingVisitor.compile(matchStatements,context);
List<PsiElement> elements = new SmartList<>();
for (PsiElement matchStatement : matchStatements) {
if (!filter.accepts(matchStatement)) {
elements.add(matchStatement);
}
}
new DeleteNodesAction(compilingVisitor.getLexicalNodes()).run();
return elements;
}
private static void addExtensionPredicates(MatchOptions options, MatchVariableConstraint constraint, SubstitutionHandler handler) {
Set<MatchPredicate> predicates = new LinkedHashSet<>();
for (MatchPredicateProvider matchPredicateProvider : Extensions.getExtensions(MatchPredicateProvider.EP_NAME)) {
matchPredicateProvider.collectPredicates(constraint, handler.getName(), options, predicates);
}
for (MatchPredicate matchPredicate : predicates) {
addPredicate(handler, matchPredicate);
}
}
private static void addScriptConstraint(Project project, String name, MatchVariableConstraint constraint, SubstitutionHandler handler)
throws MalformedPatternException {
if (constraint.getScriptCodeConstraint()!= null && constraint.getScriptCodeConstraint().length() > 2) {
final String script = StringUtil.unquoteString(constraint.getScriptCodeConstraint());
final String problem = ScriptSupport.checkValidScript(script);
if (problem != null) {
throw new MalformedPatternException("Script constraint for " + constraint.getName() + " has problem " + problem);
}
addPredicate(handler, new ScriptPredicate(project, name, script));
}
}
private static void addPredicate(SubstitutionHandler handler, MatchPredicate predicate) {
if (handler.getPredicate()==null) {
handler.setPredicate(predicate);
} else {
handler.setPredicate(new AndPredicate(handler.getPredicate(), predicate));
}
}
} | Java |
package examples.model;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
@Entity
public class Department {
@Id
private int id;
private String name;
@OneToMany(mappedBy="department")
private Collection<Employee> employees;
public Department() {
employees = new ArrayList<Employee>();
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public Collection<Employee> getEmployees() {
return employees;
}
public String toString() {
return "Department no: " + getId() +
", name: " + getName();
}
}
| Java |
##===- lib/Transforms/NaCl/Makefile-------------------------*- Makefile -*-===##
#
# The LLVM Compiler Infrastructure
#
# This file is distributed under the University of Illinois Open Source
# License. See LICENSE.TXT for details.
#
##===----------------------------------------------------------------------===##
LEVEL = ../../..
LIBRARYNAME = LLVMNaClTransforms
BUILD_ARCHIVE = 1
include $(LEVEL)/Makefile.common
| Java |
/**
* @file
* CSS for Cesium Cartesian3.
*/
div.form-item table .form-type-textfield,
div.form-item table .form-type-textfield * {
display: inline-block;
}
| Java |
export const FILLPATTERN = {
none: '',
crossHatched: 'Crosshatched',
hatched: 'Hatched',
solid: 'Solid'
};
export const STROKEPATTERN = {
none: '',
dashed: 'Dashed',
dotted: 'Dotted',
solid: 'Solid'
};
export const ALTITUDEMODE = {
NONE: '',
ABSOLUTE: 'Absolute',
RELATIVE_TO_GROUND: 'Relative to ground',
CLAMP_TO_GROUND: 'Clamp to ground'
};
export const ICONSIZE = {
none: '',
verySmall: 'Very Small',
small: 'Small',
medium: 'Medium',
large: 'Large',
extraLarge: 'Extra Large'
};
export const ACMATTRIBUTES = {
innerRadius: 'Inner Radius',
leftAzimuth: 'Left Azimuth',
rightAzimuth: 'Right Azimuth',
minAlt: 'Minimum Altitude',
maxAlt: 'Maximum Altitude',
leftWidth: 'Left Width',
rightWidth: 'Right Width',
radius: 'Radius',
turn: 'Turn',
width: 'Width'
};
export const WMSVERSION = {
WMS: 'none',
WMS1_1: '1.0',
WMS1_1_1: '1.1.1',
WMS1_3_0: '1.3.0'
};
export const WMTSVERSION = {
WMTS: 'none',
WMTS1_0_0: '1.0.0'
};
| Java |
// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------
using System;
using System.IO;
namespace Microsoft.WindowsAzure.MobileServices
{
/// <summary>
/// Provides access to platform specific functionality for the current client platform.
/// </summary>
public class CurrentPlatform : IPlatform
{
/// <summary>
/// You must call this method from your application in order to ensure
/// that this platform specific assembly is included in your app.
/// </summary>
public static void Init()
{
}
/// <summary>
/// Returns a platform-specific implemention of application storage.
/// </summary>
IApplicationStorage IPlatform.ApplicationStorage
{
get { return ApplicationStorage.Instance; }
}
/// <summary>
/// Returns a platform-specific implemention of platform information.
/// </summary>
IPlatformInformation IPlatform.PlatformInformation
{
get { return PlatformInformation.Instance; }
}
/// <summary>
/// Returns a platform-specific implementation of a utility class
/// that provides functionality for manipulating
/// <see cref="System.Linq.Expressions.Expression"/> instances.
/// </summary>
IExpressionUtility IPlatform.ExpressionUtility
{
get { return ExpressionUtility.Instance; }
}
/// <summary>
/// Returns a platform-specific implementation of a utility class
/// that provides functionality for platform-specifc push capabilities.
/// </summary>
IPushUtility IPlatform.PushUtility { get { return Microsoft.WindowsAzure.MobileServices.PushUtility.Instance; } }
/// <summary>
/// Returns a platform-specific path for storing offline databases
/// that are not fully-qualified.
/// </summary>
string IPlatform.DefaultDatabasePath
{
get
{
return Environment.GetFolderPath(Environment.SpecialFolder.Personal);
}
}
/// <summary>
/// Retrieves an ApplicationStorage where all items stored are segmented from other stored items
/// </summary>
/// <param name="name">The name of the segemented area in application storage</param>
/// <returns>The specific instance of that segment</returns>
IApplicationStorage IPlatform.GetNamedApplicationStorage(string name)
{
return new ApplicationStorage(name);
}
/// <summary>
/// Ensures that a file exists, creating it if necessary
/// </summary>
/// <param name="path">The fully-qualified pathname to check</param>
public void EnsureFileExists(string path)
{
if (!File.Exists(path))
{
File.Create(path);
}
}
}
} | Java |
<?php
/*
* Copyright 2014 Google 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.
*/
namespace Google\Service\ChromePolicy;
class GoogleChromePolicyV1PolicySchemaFieldDescription extends \Google\Collection
{
protected $collection_key = 'nestedFieldDescriptions';
/**
* @var string
*/
public $description;
/**
* @var string
*/
public $field;
protected $fieldDependenciesType = GoogleChromePolicyV1PolicySchemaFieldDependencies::class;
protected $fieldDependenciesDataType = 'array';
/**
* @var string
*/
public $inputConstraint;
protected $knownValueDescriptionsType = GoogleChromePolicyV1PolicySchemaFieldKnownValueDescription::class;
protected $knownValueDescriptionsDataType = 'array';
protected $nestedFieldDescriptionsType = GoogleChromePolicyV1PolicySchemaFieldDescription::class;
protected $nestedFieldDescriptionsDataType = 'array';
/**
* @param string
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* @param string
*/
public function setField($field)
{
$this->field = $field;
}
/**
* @return string
*/
public function getField()
{
return $this->field;
}
/**
* @param GoogleChromePolicyV1PolicySchemaFieldDependencies[]
*/
public function setFieldDependencies($fieldDependencies)
{
$this->fieldDependencies = $fieldDependencies;
}
/**
* @return GoogleChromePolicyV1PolicySchemaFieldDependencies[]
*/
public function getFieldDependencies()
{
return $this->fieldDependencies;
}
/**
* @param string
*/
public function setInputConstraint($inputConstraint)
{
$this->inputConstraint = $inputConstraint;
}
/**
* @return string
*/
public function getInputConstraint()
{
return $this->inputConstraint;
}
/**
* @param GoogleChromePolicyV1PolicySchemaFieldKnownValueDescription[]
*/
public function setKnownValueDescriptions($knownValueDescriptions)
{
$this->knownValueDescriptions = $knownValueDescriptions;
}
/**
* @return GoogleChromePolicyV1PolicySchemaFieldKnownValueDescription[]
*/
public function getKnownValueDescriptions()
{
return $this->knownValueDescriptions;
}
/**
* @param GoogleChromePolicyV1PolicySchemaFieldDescription[]
*/
public function setNestedFieldDescriptions($nestedFieldDescriptions)
{
$this->nestedFieldDescriptions = $nestedFieldDescriptions;
}
/**
* @return GoogleChromePolicyV1PolicySchemaFieldDescription[]
*/
public function getNestedFieldDescriptions()
{
return $this->nestedFieldDescriptions;
}
}
// Adding a class alias for backwards compatibility with the previous class name.
class_alias(GoogleChromePolicyV1PolicySchemaFieldDescription::class, 'Google_Service_ChromePolicy_GoogleChromePolicyV1PolicySchemaFieldDescription');
| Java |
#dcwp-avatar {float: left; display: block; width: 32px; height: 32px; background: url(images/dc_icon32.png) no-repeat 0 0; margin: 0 5px 0 0;}
.dcwp-box.postbox {margin-bottom: 10px;}
.dcwp-box .hndle {margin-bottom: 10px;}
.dcwp-box p, .dcwp-box ul, .widget .widget-inside p.dcwp-box {padding: 0 10px; margin: 0 0 3px 0; line-height: 1.5em;}
.dcwp-box ul.bullet, ul.dcwp-rss {list-style: square; margin-left: 15px;}
.dcwp-form {padding: 0 10px;}
.dcwp-intro {padding: 10px;}
.dcwp-form li {display: block; width: 100%; overflow: hidden; margin: 0 0 5px 0; padding: 5px 0; clear: both; }
.dcwp-form li h4 {margin: 15px 0 0 0;}
.dcwp-form li label {float: left; width: 25%; display: block; padding: 5px 0 0 0;}
span.dcwp-note {display: block; padding: 5px 0 0 25%; font-size: 11px;}
label span.dcwp-note {padding: 2px 0 0 0; font-size: 11px;}
.dcwp-checkbox {}
.dcwp-rss-item {}
.dcwp-icon-rss {}
.dcwp-icon-twitter {}
.dcwp-input-l {width: 70%;}
.dcwp-input-m {width: 50%;}
.dcwp-input-s {width: 30%;}
.dcwp-textarea {width: 70%;}
#social-media-tabs-donatebox.dcwp-box {border: 1px solid #016f02; background: #fff;}
#social-media-tabs-donatebox.dcwp-box h3 {color: #016f02; padding: 7px 15px;}
#social-media-tabs-donatebox.dcwp-box p {padding: 0 7px;}
#form-dcwp-donate {text-align: center; padding-bottom: 10px;}
/* Widgets */
.dcwp-widget-text {width: 98%; height: 65px;}
.dcwp-widget-input {width: 100%;}
.dcwp-widget-label {display: block;}
p.dcwp-row {margin-bottom: 3px; width: 100%; overflow: hidden;}
p.dcwp-row.half {width: 50%; float: left;}
p.dcwp-row label {float: left; width: 70px; padding-top: 3px; display: block;}
.dcsmt-ul li {width: 100%; overflow: hidden;}
.dcsmt-ul .dcwp-widget-input, .dcsmt-ul h4.left {float: left; width: 60%;}
.dcsmt-ul select, .dcsmt-ul h4.right {float: right; width: 35%;}
.dcsmt-ul h4 {margin: 0;}
.dcsmt-ul label {display: none;}
.dcsmt-ul select, .dcsmt-ul .dcwp-widget-input {font-size: 11px;}
/* Share */
.dcwp-box ul#dc-share {width: 100%; overflow: hidden; margin: 0; padding: 0; line-height: 1em;}
.dcwp-box ul#dc-share li {float: left; padding: 0 3px; margin: 0; height: 75px;}
/* Plugin Specific */
#dcsmt_redirect {width: 140px;}
.dcwp-form li.dcsmt-icon {position: relative; width: 48%; float: left; height: 26px; clear: none; margin-right: 2%;}
.dcwp-form li.dcsmt-icon label {text-transform: capitalize;}
.dcsmt-icon img {position: absolute; top: 0; right: 0;}
| Java |
package water.jdbc;
import org.junit.Test;
import org.junit.runner.RunWith;
import water.Key;
import water.Keyed;
import water.fvec.Frame;
import water.runner.CloudSize;
import water.runner.H2ORunner;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.junit.Assert.*;
@RunWith(H2ORunner.class)
@CloudSize(1)
public class SQLManagerKeyOverwiteTest {
@Test public void nextKeyHasRightPrefixAndPostfix() {
final String prefix = "foo";
final String postfix = "bar";
final Key<Frame> key = SQLManager.nextTableKey(prefix, postfix);
assertTrue(key.toString().startsWith(prefix));
assertTrue(key.toString().endsWith(postfix));
}
@Test public void nextKeyKeyHasNoWhitechars() {
final Key<Frame> key = SQLManager.nextTableKey("f o o ", "b a r");
assertFalse(key.toString().contains("\\W"));
}
@Test public void makeRandomKeyCreatesUniqueKeys() {
final int count = 1000;
final long actualCount = IntStream.range(0, count)
.boxed()
.parallel()
.map(i -> SQLManager.nextTableKey("foo", "bar"))
.map(Key::toString)
.count();
assertEquals(count, actualCount);
}
}
| Java |
<?php
namespace EventEspresso\core\services\commands\registration;
use EventEspresso\core\services\commands\Command;
if ( ! defined( 'EVENT_ESPRESSO_VERSION' ) ) {
exit( 'No direct script access allowed' );
}
/**
* Class SingleRegistrationCommand
* DTO for passing data a single EE_Registration object to a CommandHandler
*
* @package Event Espresso
* @author Brent Christensen
* @since 4.9.0
*/
abstract class SingleRegistrationCommand extends Command
{
/**
* @var \EE_Registration $registration
*/
private $registration;
/**
* CancelRegistrationAndTicketLineItemCommand constructor.
*
* @param \EE_Registration $registration
*/
public function __construct(
\EE_Registration $registration
) {
$this->registration = $registration;
}
/**
* @return \EE_Registration
*/
public function registration()
{
return $this->registration;
}
}
// End of file SingleRegistrationCommand.php
// Location: /SingleRegistrationCommand.php | Java |
<?php
/*
* Copyright 2014 Google 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.
*/
/**
* Service definition for FactCheckTools (v1alpha1).
*
* <p>
</p>
*
* <p>
* For more information about this service, see the API
* <a href="https://developers.google.com/fact-check/tools/api/" target="_blank">Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class Google_Service_FactCheckTools extends Google_Service
{
/** View your email address. */
const USERINFO_EMAIL =
"https://www.googleapis.com/auth/userinfo.email";
public $claims;
public $pages;
/**
* Constructs the internal representation of the FactCheckTools service.
*
* @param Google_Client $client The client used to deliver requests.
* @param string $rootUrl The root URL used for requests to the service.
*/
public function __construct(Google_Client $client, $rootUrl = null)
{
parent::__construct($client);
$this->rootUrl = $rootUrl ?: 'https://factchecktools.googleapis.com/';
$this->servicePath = '';
$this->batchPath = 'batch';
$this->version = 'v1alpha1';
$this->serviceName = 'factchecktools';
$this->claims = new Google_Service_FactCheckTools_Resource_Claims(
$this,
$this->serviceName,
'claims',
array(
'methods' => array(
'search' => array(
'path' => 'v1alpha1/claims:search',
'httpMethod' => 'GET',
'parameters' => array(
'languageCode' => array(
'location' => 'query',
'type' => 'string',
),
'maxAgeDays' => array(
'location' => 'query',
'type' => 'integer',
),
'offset' => array(
'location' => 'query',
'type' => 'integer',
),
'pageSize' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'query' => array(
'location' => 'query',
'type' => 'string',
),
'reviewPublisherSiteFilter' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->pages = new Google_Service_FactCheckTools_Resource_Pages(
$this,
$this->serviceName,
'pages',
array(
'methods' => array(
'create' => array(
'path' => 'v1alpha1/pages',
'httpMethod' => 'POST',
'parameters' => array(),
),'delete' => array(
'path' => 'v1alpha1/{+name}',
'httpMethod' => 'DELETE',
'parameters' => array(
'name' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'get' => array(
'path' => 'v1alpha1/{+name}',
'httpMethod' => 'GET',
'parameters' => array(
'name' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'list' => array(
'path' => 'v1alpha1/pages',
'httpMethod' => 'GET',
'parameters' => array(
'offset' => array(
'location' => 'query',
'type' => 'integer',
),
'organization' => array(
'location' => 'query',
'type' => 'string',
),
'pageSize' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'url' => array(
'location' => 'query',
'type' => 'string',
),
),
),'update' => array(
'path' => 'v1alpha1/{+name}',
'httpMethod' => 'PUT',
'parameters' => array(
'name' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),
)
)
);
}
}
| Java |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.impl.statistics;
import com.intellij.execution.Executor;
import com.intellij.execution.configurations.ConfigurationFactory;
import com.intellij.execution.configurations.ConfigurationType;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.execution.executors.ExecutorGroup;
import com.intellij.execution.target.TargetEnvironmentAwareRunProfile;
import com.intellij.execution.target.TargetEnvironmentConfiguration;
import com.intellij.execution.target.TargetEnvironmentType;
import com.intellij.execution.target.TargetEnvironmentsManager;
import com.intellij.internal.statistic.IdeActivityDefinition;
import com.intellij.internal.statistic.StructuredIdeActivity;
import com.intellij.internal.statistic.eventLog.EventLogGroup;
import com.intellij.internal.statistic.eventLog.events.*;
import com.intellij.internal.statistic.eventLog.validator.ValidationResultType;
import com.intellij.internal.statistic.eventLog.validator.rules.EventContext;
import com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule;
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector;
import com.intellij.internal.statistic.utils.PluginInfo;
import com.intellij.internal.statistic.utils.PluginInfoDetectorKt;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.concurrency.NonUrgentExecutor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.List;
import static com.intellij.execution.impl.statistics.RunConfigurationTypeUsagesCollector.createFeatureUsageData;
public final class RunConfigurationUsageTriggerCollector extends CounterUsagesCollector {
public static final String GROUP_NAME = "run.configuration.exec";
private static final EventLogGroup GROUP = new EventLogGroup(GROUP_NAME, 62);
private static final ObjectEventField ADDITIONAL_FIELD = EventFields.createAdditionalDataField(GROUP_NAME, "started");
private static final StringEventField EXECUTOR = EventFields.StringValidatedByCustomRule("executor", "run_config_executor");
private static final StringEventField TARGET =
EventFields.StringValidatedByCustomRule("target", RunConfigurationUsageTriggerCollector.RunTargetValidator.RULE_ID);
private static final EnumEventField<RunConfigurationFinishType> FINISH_TYPE =
EventFields.Enum("finish_type", RunConfigurationFinishType.class);
private static final IdeActivityDefinition ACTIVITY_GROUP = GROUP.registerIdeActivity(null,
new EventField<?>[]{ADDITIONAL_FIELD, EXECUTOR,
TARGET,
RunConfigurationTypeUsagesCollector.FACTORY_FIELD,
RunConfigurationTypeUsagesCollector.ID_FIELD,
EventFields.PluginInfo},
new EventField<?>[]{FINISH_TYPE});
public static final VarargEventId UI_SHOWN_STAGE = ACTIVITY_GROUP.registerStage("ui.shown");
@Override
public EventLogGroup getGroup() {
return GROUP;
}
@NotNull
public static StructuredIdeActivity trigger(@NotNull Project project,
@NotNull ConfigurationFactory factory,
@NotNull Executor executor,
@Nullable RunConfiguration runConfiguration) {
return ACTIVITY_GROUP
.startedAsync(project, () -> ReadAction.nonBlocking(() -> buildContext(project, factory, executor, runConfiguration))
.expireWith(project)
.submit(NonUrgentExecutor.getInstance()));
}
private static @NotNull List<EventPair<?>> buildContext(@NotNull Project project,
@NotNull ConfigurationFactory factory,
@NotNull Executor executor,
@Nullable RunConfiguration runConfiguration) {
final ConfigurationType configurationType = factory.getType();
List<EventPair<?>> eventPairs = createFeatureUsageData(configurationType, factory);
ExecutorGroup<?> group = ExecutorGroup.getGroupIfProxy(executor);
eventPairs.add(EXECUTOR.with(group != null ? group.getId() : executor.getId()));
if (runConfiguration instanceof FusAwareRunConfiguration) {
List<EventPair<?>> additionalData = ((FusAwareRunConfiguration)runConfiguration).getAdditionalUsageData();
ObjectEventData objectEventData = new ObjectEventData(additionalData);
eventPairs.add(ADDITIONAL_FIELD.with(objectEventData));
}
if (runConfiguration instanceof TargetEnvironmentAwareRunProfile) {
String defaultTargetName = ((TargetEnvironmentAwareRunProfile)runConfiguration).getDefaultTargetName();
if (defaultTargetName != null) {
TargetEnvironmentConfiguration target = TargetEnvironmentsManager.getInstance(project).getTargets().findByName(defaultTargetName);
if (target != null) {
eventPairs.add(TARGET.with(target.getTypeId()));
}
}
}
return eventPairs;
}
public static void logProcessFinished(@Nullable StructuredIdeActivity activity,
RunConfigurationFinishType finishType) {
if (activity != null) {
activity.finished(() -> Collections.singletonList(FINISH_TYPE.with(finishType)));
}
}
public static class RunConfigurationExecutorUtilValidator extends CustomValidationRule {
@Override
public boolean acceptRuleId(@Nullable String ruleId) {
return "run_config_executor".equals(ruleId);
}
@NotNull
@Override
protected ValidationResultType doValidate(@NotNull String data, @NotNull EventContext context) {
for (Executor executor : Executor.EXECUTOR_EXTENSION_NAME.getExtensions()) {
if (StringUtil.equals(executor.getId(), data)) {
final PluginInfo info = PluginInfoDetectorKt.getPluginInfo(executor.getClass());
return info.isSafeToReport() ? ValidationResultType.ACCEPTED : ValidationResultType.THIRD_PARTY;
}
}
return ValidationResultType.REJECTED;
}
}
public static class RunTargetValidator extends CustomValidationRule {
public static final String RULE_ID = "run_target";
@Override
public boolean acceptRuleId(@Nullable String ruleId) {
return RULE_ID.equals(ruleId);
}
@NotNull
@Override
protected ValidationResultType doValidate(@NotNull String data, @NotNull EventContext context) {
for (TargetEnvironmentType<?> type : TargetEnvironmentType.EXTENSION_NAME.getExtensions()) {
if (StringUtil.equals(type.getId(), data)) {
final PluginInfo info = PluginInfoDetectorKt.getPluginInfo(type.getClass());
return info.isSafeToReport() ? ValidationResultType.ACCEPTED : ValidationResultType.THIRD_PARTY;
}
}
return ValidationResultType.REJECTED;
}
}
public enum RunConfigurationFinishType {FAILED_TO_START, UNKNOWN}
}
| Java |
# ******************************************************************************
# Copyright 2014-2018 Intel 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.
# ******************************************************************************
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.