code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
package org.jboss.resteasy.reactive.server.core.request;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import javax.ws.rs.BadRequestException;
import javax.ws.rs.core.MediaType;
/**
* @author Pascal S. de Kloe
*/
public class AcceptHeaders {
/**
* Gets the strings from a comma-separated list.
* All "*" entries are replaced with {@code null} keys.
*
* @param header the header value.
* @return the listed items in order of appearance or {@code null} if the header didn't contain any entries.
*/
public static Map<String, QualityValue> getStringQualityValues(String header) {
if (header == null) {
return null;
}
header = header.trim();
if (header.length() == 0) {
return null;
}
Map<String, QualityValue> result = new LinkedHashMap<String, QualityValue>();
int offset = 0;
while (true) {
int endIndex = header.indexOf(',', offset);
String content;
if (endIndex < 0) {
content = header.substring(offset);
} else {
content = header.substring(offset, endIndex);
}
QualityValue qualityValue = QualityValue.DEFAULT;
int qualityIndex = content.indexOf(';');
if (qualityIndex >= 0) {
String parameter = content.substring(qualityIndex + 1);
content = content.substring(0, qualityIndex);
int equalsIndex = parameter.indexOf('=');
if (equalsIndex < 0) {
throw new BadRequestException("Malformed parameter: " + parameter);
}
String name = parameter.substring(0, equalsIndex).trim();
if (!"q".equals(name)) {
throw new BadRequestException("Unsupported parameter: " + parameter);
}
String value = parameter.substring(equalsIndex + 1).trim();
qualityValue = QualityValue.valueOf(value);
}
content = content.trim();
if (content.length() == 0) {
throw new BadRequestException("Empty Field in header: " + header);
}
if (content.equals("*")) {
result.put(null, qualityValue);
} else {
result.put(content, qualityValue);
}
if (endIndex < 0) {
break;
}
offset = endIndex + 1;
}
return result;
}
/**
* Gets the locales from a comma-separated list.
* Any "*" entries are replaced with {@code null} keys.
*
* @param header the header value.
* @return the listed items in order of appearance or {@code null} if the header didn't contain any entries.
*/
public static Map<Locale, QualityValue> getLocaleQualityValues(String header) {
Map<String, QualityValue> stringResult = getStringQualityValues(header);
if (stringResult == null)
return null;
Map<Locale, QualityValue> result = new LinkedHashMap<Locale, QualityValue>(stringResult.size() * 2);
for (Entry<String, QualityValue> entry : stringResult.entrySet()) {
QualityValue quality = entry.getValue();
Locale locale = null;
String value = entry.getKey();
if (value != null) {
int length = value.length();
if (length == 2) {
locale = new Locale(value);
} else if (length == 5 && value.charAt(2) == '-') {
String language = value.substring(0, 2);
String country = value.substring(3, 5);
locale = new Locale(language, country);
} else {
//LogMessages.LOGGER.ignoringUnsupportedLocale(value);
continue;
}
}
result.put(locale, quality);
}
//LogMessages.LOGGER.debug(result.toString());
return result;
}
/**
* Gets the media types from a comma-separated list.
*
* @param header the header value.
* @return the listed items in order of appearance or {@code null} if the header didn't contain any entries.
*/
public static Map<MediaType, QualityValue> getMediaTypeQualityValues(String header) {
if (header == null)
return null;
header = header.trim();
if (header.length() == 0)
return null;
Map<MediaType, QualityValue> result = new LinkedHashMap<MediaType, QualityValue>();
int offset = 0;
while (offset >= 0) {
int slashIndex = header.indexOf('/', offset);
if (slashIndex < 0)
throw new BadRequestException("Malformed media type: " + header);
String type = header.substring(offset, slashIndex);
String subtype;
Map<String, String> parameters = null;
QualityValue qualityValue = QualityValue.DEFAULT;
offset = slashIndex + 1;
int parameterStartIndex = header.indexOf(';', offset);
int itemEndIndex = header.indexOf(',', offset);
if (parameterStartIndex == itemEndIndex) {
assert itemEndIndex == -1;
subtype = header.substring(offset);
offset = -1;
} else if (itemEndIndex < 0 || (parameterStartIndex >= 0 && parameterStartIndex < itemEndIndex)) {
subtype = header.substring(offset, parameterStartIndex);
offset = parameterStartIndex + 1;
parameters = new LinkedHashMap<String, String>();
offset = parseParameters(parameters, header, offset);
qualityValue = evaluateAcceptParameters(parameters);
} else {
subtype = header.substring(offset, itemEndIndex);
offset = itemEndIndex + 1;
}
result.put(new MediaType(type.trim(), subtype.trim(), parameters), qualityValue);
}
//LogMessages.LOGGER.debug(result.toString());
return result;
}
private static int parseParameters(Map<String, String> parameters, String header, int offset) {
while (true) {
int equalsIndex = header.indexOf('=', offset);
if (equalsIndex < 0)
throw new BadRequestException("Malformed parameters: " + header);
String name = header.substring(offset, equalsIndex).trim();
offset = equalsIndex + 1;
if (header.charAt(offset) == '"') {
int end = offset;
++offset;
do {
end = header.indexOf('"', ++end);
if (end < 0)
throw new BadRequestException("Unclosed quotes:" + header);
} while (header.charAt(end - 1) == '\\');
String value = header.substring(offset, end);
parameters.put(name, value);
offset = end + 1;
int parameterEndIndex = header.indexOf(';', offset);
int itemEndIndex = header.indexOf(',', offset);
if (parameterEndIndex == itemEndIndex) {
assert itemEndIndex == -1;
if (header.substring(offset).trim().length() != 0)
throw new BadRequestException("Extra characters after quoted string:" + header);
return -1;
} else if (parameterEndIndex < 0 || (itemEndIndex >= 0 && itemEndIndex < parameterEndIndex)) {
if (header.substring(offset, itemEndIndex).trim().length() != 0)
throw new BadRequestException("Extra characters after quoted string:" + header);
return itemEndIndex + 1;
} else {
if (header.substring(offset, parameterEndIndex).trim().length() != 0)
throw new BadRequestException("Extra characters after quoted string:" + header);
offset = parameterEndIndex + 1;
}
} else {
int parameterEndIndex = header.indexOf(';', offset);
int itemEndIndex = header.indexOf(',', offset);
if (parameterEndIndex == itemEndIndex) {
assert itemEndIndex == -1;
String value = header.substring(offset).trim();
parameters.put(name, value);
return -1;
} else if (parameterEndIndex < 0 || (itemEndIndex >= 0 && itemEndIndex < parameterEndIndex)) {
String value = header.substring(offset, itemEndIndex).trim();
parameters.put(name, value);
return itemEndIndex + 1;
} else {
String value = header.substring(offset, parameterEndIndex).trim();
parameters.put(name, value);
offset = parameterEndIndex + 1;
}
}
}
}
/**
* Evaluates and removes the accept parameters.
*
* <pre>
* accept-params = ";" "q" "=" qvalue *( accept-extension )
* accept-extension = ";" token [ "=" ( token | quoted-string ) ]
* </pre>
*
* @param parameters all parameters in order of appearance.
* @return the qvalue.
* @see "accept-params
*/
private static QualityValue evaluateAcceptParameters(Map<String, String> parameters) {
Iterator<String> i = parameters.keySet().iterator();
while (i.hasNext()) {
String name = i.next();
if ("q".equals(name)) {
if (i.hasNext()) {
//LogMessages.LOGGER.acceptExtensionsNotSupported();
i.remove();
do {
i.next();
i.remove();
} while (i.hasNext());
return QualityValue.NOT_ACCEPTABLE;
} else {
String value = parameters.get(name);
i.remove();
return QualityValue.valueOf(value);
}
}
}
return QualityValue.DEFAULT;
}
}
| quarkusio/quarkus | independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/core/request/AcceptHeaders.java | Java | apache-2.0 | 10,428 |
/*
*
* 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.wso2.andes.server.exchange;
import org.apache.log4j.Logger;
import org.wso2.andes.AMQException;
import org.wso2.andes.framing.AMQShortString;
import org.wso2.andes.server.binding.Binding;
import org.wso2.andes.server.configuration.ConfigStore;
import org.wso2.andes.server.configuration.ConfiguredObject;
import org.wso2.andes.server.configuration.ExchangeConfigType;
import org.wso2.andes.server.logging.LogSubject;
import org.wso2.andes.server.logging.actors.CurrentActor;
import org.wso2.andes.server.logging.messages.ExchangeMessages;
import org.wso2.andes.server.logging.subjects.ExchangeLogSubject;
import org.wso2.andes.server.management.Managable;
import org.wso2.andes.server.management.ManagedObject;
import org.wso2.andes.server.message.InboundMessage;
import org.wso2.andes.server.queue.AMQQueue;
import org.wso2.andes.server.queue.BaseQueue;
import org.wso2.andes.server.queue.QueueRegistry;
import org.wso2.andes.server.virtualhost.VirtualHost;
import javax.management.JMException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
public abstract class AbstractExchange implements Exchange, Managable
{
private AMQShortString _name;
private final AtomicBoolean _closed = new AtomicBoolean();
private Exchange _alternateExchange;
protected boolean _durable;
protected int _ticket;
private VirtualHost _virtualHost;
private final List<Exchange.Task> _closeTaskList = new CopyOnWriteArrayList<Exchange.Task>();
protected AbstractExchangeMBean _exchangeMbean;
/**
* Whether the exchange is automatically deleted once all queues have detached from it
*/
protected boolean _autoDelete;
//The logSubject for ths exchange
private LogSubject _logSubject;
private Map<ExchangeReferrer,Object> _referrers = new ConcurrentHashMap<ExchangeReferrer,Object>();
private final CopyOnWriteArrayList<Binding> _bindings = new CopyOnWriteArrayList<Binding>();
private final ExchangeType<? extends Exchange> _type;
private UUID _id;
private final AtomicInteger _bindingCountHigh = new AtomicInteger();
private final AtomicLong _receivedMessageCount = new AtomicLong();
private final AtomicLong _receivedMessageSize = new AtomicLong();
private final AtomicLong _routedMessageCount = new AtomicLong();
private final AtomicLong _routedMessageSize = new AtomicLong();
private final CopyOnWriteArrayList<Exchange.BindingListener> _listeners = new CopyOnWriteArrayList<Exchange.BindingListener>();
//TODO : persist creation time
private long _createTime = System.currentTimeMillis();
public AbstractExchange(final ExchangeType<? extends Exchange> type)
{
_type = type;
}
public AMQShortString getNameShortString()
{
return _name;
}
public final AMQShortString getTypeShortString()
{
return _type.getName();
}
/**
* Concrete exchanges must implement this method in order to create the managed representation. This is
* called during initialisation (template method pattern).
* @return the MBean
*/
protected abstract AbstractExchangeMBean createMBean() throws JMException;
public void initialise(VirtualHost host, AMQShortString name, boolean durable, int ticket, boolean autoDelete)
throws AMQException
{
_virtualHost = host;
_name = name;
_durable = durable;
_autoDelete = autoDelete;
_ticket = ticket;
// TODO - fix
_id = getConfigStore().createId();
getConfigStore().addConfiguredObject(this);
try
{
_exchangeMbean = createMBean();
_exchangeMbean.register();
}
catch (JMException e)
{
getLogger().error(e);
}
_logSubject = new ExchangeLogSubject(this, this.getVirtualHost());
// Log Exchange creation
CurrentActor.get().message(ExchangeMessages.CREATED(String.valueOf(getTypeShortString()), String.valueOf(name), durable));
}
public ConfigStore getConfigStore()
{
return getVirtualHost().getConfigStore();
}
public abstract Logger getLogger();
public boolean isDurable()
{
return _durable;
}
public boolean isAutoDelete()
{
return _autoDelete;
}
public int getTicket()
{
return _ticket;
}
public void close() throws AMQException
{
if(_closed.compareAndSet(false,true))
{
if (_exchangeMbean != null)
{
_exchangeMbean.unregister();
}
getConfigStore().removeConfiguredObject(this);
if(_alternateExchange != null)
{
_alternateExchange.removeReference(this);
}
CurrentActor.get().message(_logSubject, ExchangeMessages.DELETED());
for(Task task : _closeTaskList)
{
task.onClose(this);
}
_closeTaskList.clear();
}
}
public String toString()
{
return getClass().getSimpleName() + "[" + getNameShortString() +"]";
}
public ManagedObject getManagedObject()
{
return _exchangeMbean;
}
public VirtualHost getVirtualHost()
{
return _virtualHost;
}
public QueueRegistry getQueueRegistry()
{
return getVirtualHost().getQueueRegistry();
}
public boolean isBound(String bindingKey, Map<String,Object> arguments, AMQQueue queue)
{
return isBound(new AMQShortString(bindingKey), queue);
}
public boolean isBound(String bindingKey, AMQQueue queue)
{
return isBound(new AMQShortString(bindingKey), queue);
}
public boolean isBound(String bindingKey)
{
return isBound(new AMQShortString(bindingKey));
}
public Exchange getAlternateExchange()
{
return _alternateExchange;
}
public void setAlternateExchange(Exchange exchange)
{
if(_alternateExchange != null)
{
_alternateExchange.removeReference(this);
}
if(exchange != null)
{
exchange.addReference(this);
}
_alternateExchange = exchange;
}
public void removeReference(ExchangeReferrer exchange)
{
_referrers.remove(exchange);
}
public void addReference(ExchangeReferrer exchange)
{
_referrers.put(exchange, Boolean.TRUE);
}
public boolean hasReferrers()
{
return !_referrers.isEmpty();
}
public void addCloseTask(final Task task)
{
_closeTaskList.add(task);
}
public void removeCloseTask(final Task task)
{
_closeTaskList.remove(task);
}
public final void addBinding(final Binding binding)
{
_bindings.add(binding);
int bindingCountSize = _bindings.size();
int maxBindingsSize;
while((maxBindingsSize = _bindingCountHigh.get()) < bindingCountSize)
{
_bindingCountHigh.compareAndSet(maxBindingsSize, bindingCountSize);
}
for(BindingListener listener : _listeners)
{
listener.bindingAdded(this, binding);
}
onBind(binding);
}
public long getBindingCountHigh()
{
return _bindingCountHigh.get();
}
public final void removeBinding(final Binding binding)
{
onUnbind(binding);
for(BindingListener listener : _listeners)
{
listener.bindingRemoved(this, binding);
}
_bindings.remove(binding);
}
public final Collection<Binding> getBindings()
{
return Collections.unmodifiableList(_bindings);
}
protected abstract void onBind(final Binding binding);
protected abstract void onUnbind(final Binding binding);
public String getName()
{
return _name.toString();
}
public ExchangeType getType()
{
return _type;
}
public Map<String, Object> getArguments()
{
// TODO - Fix
return Collections.EMPTY_MAP;
}
public UUID getId()
{
return _id;
}
public ExchangeConfigType getConfigType()
{
return ExchangeConfigType.getInstance();
}
public ConfiguredObject getParent()
{
return _virtualHost;
}
public long getBindingCount()
{
return getBindings().size();
}
public final ArrayList<? extends BaseQueue> route(final InboundMessage message)
{
_receivedMessageCount.incrementAndGet();
_receivedMessageSize.addAndGet(message.getSize());
final ArrayList<? extends BaseQueue> queues = doRoute(message);
if(queues != null && !queues.isEmpty())
{
_routedMessageCount.incrementAndGet();
_routedMessageSize.addAndGet(message.getSize());
}
return queues;
}
protected abstract ArrayList<? extends BaseQueue> doRoute(final InboundMessage message);
public long getMsgReceives()
{
return _receivedMessageCount.get();
}
public long getMsgRoutes()
{
return _routedMessageCount.get();
}
public long getByteReceives()
{
return _receivedMessageSize.get();
}
public long getByteRoutes()
{
return _routedMessageSize.get();
}
public long getCreateTime()
{
return _createTime;
}
public void addBindingListener(final BindingListener listener)
{
_listeners.add(listener);
}
public void removeBindingListener(final BindingListener listener)
{
_listeners.remove(listener);
}
}
| akalankapagoda/andes | modules/andes-core/broker/src/main/java/org/wso2/andes/server/exchange/AbstractExchange.java | Java | apache-2.0 | 10,726 |
/**
* Copyright (c) 2010 Abbcc Corp.
* No 225,Wen Yi RD, Hang Zhou, Zhe Jiang, China.
* All rights reserved.
*
* "AttachAction.java is the copyrighted,
* proprietary property of Abbcc Company and its
* subsidiaries and affiliates which retain all right, title and interest
* therein."
*
* Revision History
*
* Date Programmer Notes
* --------- --------------------- --------------------------------------------
* 2010-3-22 baowp initial
*/
package com.abbcc.module.usersite;
import java.util.Date;
import com.abbcc.action.FileUploadAction;
import com.abbcc.models.AbcAttachment;
import com.abbcc.util.ObjectUtil;
import com.abbcc.util.constant.ModelType;
@SuppressWarnings("serial")
public class AttachAction extends FileUploadAction<AbcAttachment> {
public String callback;
private String uploaded() {
uploadImage();
return "back";
}
protected void prepareAttach(AbcAttachment attach){
entity.setBelongType(ModelType.AE);
ObjectUtil.extend(attach, entity);
}
public String topic() {
return uploaded();
}
public String sign(){
return uploaded();
}
public String nav(){
return uploaded();
}
public String title(){
return uploaded();
}
public String inBg(){
return uploaded();
}
public String outBg(){
return uploaded();
}
public String log(){
return uploaded();
}
public String flash(){
doUpload();
if(uploadFilePath!=null){
entity.setBelongType(ModelType.AE);
entity.setServerPath(uploadFilePath);
entity.setFilename(newFilename);
entity.setUserId(getCurrentUser().getUserId());
entity.setUploadTime(new Date());
attachmentService.save(entity);
}
return "back";
}
}
| baowp/platform | biz/src/main/java/com/abbcc/module/usersite/AttachAction.java | Java | apache-2.0 | 1,740 |
package org.jboss.resteasy.reactive.server.providers.serialisers.jsonp;
import java.io.ByteArrayOutputStream;
import java.lang.reflect.Type;
import javax.json.JsonObject;
import javax.json.JsonStructure;
import javax.json.JsonWriter;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import org.jboss.resteasy.reactive.common.providers.serialisers.jsonp.JsonStructureHandler;
import org.jboss.resteasy.reactive.common.providers.serialisers.jsonp.JsonpUtil;
import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo;
import org.jboss.resteasy.reactive.server.spi.ServerMessageBodyWriter;
import org.jboss.resteasy.reactive.server.spi.ServerRequestContext;
public class ServerJsonStructureHandler extends JsonStructureHandler
implements ServerMessageBodyWriter<JsonStructure> {
@Override
public boolean isWriteable(Class<?> type, Type genericType, ResteasyReactiveResourceInfo target, MediaType mediaType) {
return JsonStructure.class.isAssignableFrom(type) && !JsonObject.class.isAssignableFrom(type);
}
@Override
public void writeResponse(JsonStructure o, Type genericType, ServerRequestContext context) throws WebApplicationException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (JsonWriter writer = JsonpUtil.writer(out, context.getResponseMediaType())) {
writer.write(o);
}
context.serverResponse().end(out.toByteArray());
}
}
| quarkusio/quarkus | independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/providers/serialisers/jsonp/ServerJsonStructureHandler.java | Java | apache-2.0 | 1,483 |
/*jshint browser: true */
/*jshint unused: false */
/*global arangoHelper, _, $, window, arangoHelper, templateEngine, Joi, btoa */
(function() {
"use strict";
window.DocumentsView = window.PaginationView.extend({
filters : { "0" : true },
filterId : 0,
paginationDiv : "#documentsToolbarF",
idPrefix : "documents",
addDocumentSwitch: true,
activeFilter: false,
lastCollectionName: undefined,
restoredFilters: [],
editMode: false,
allowUpload: false,
el: '#content',
table: '#documentsTableID',
template: templateEngine.createTemplate("documentsView.ejs"),
collectionContext : {
prev: null,
next: null
},
editButtons: ["#deleteSelected", "#moveSelected"],
initialize : function () {
this.documentStore = this.options.documentStore;
this.collectionsStore = this.options.collectionsStore;
this.tableView = new window.TableView({
el: this.table,
collection: this.collection
});
this.tableView.setRowClick(this.clicked.bind(this));
this.tableView.setRemoveClick(this.remove.bind(this));
},
setCollectionId : function (colid, pageid) {
this.collection.setCollection(colid);
var type = arangoHelper.collectionApiType(colid);
this.pageid = pageid;
this.type = type;
this.checkCollectionState();
this.collection.getDocuments(this.getDocsCallback.bind(this));
this.collectionModel = this.collectionsStore.get(colid);
},
getDocsCallback: function() {
//Hide first/last pagination
$('#documents_last').css("visibility", "hidden");
$('#documents_first').css("visibility", "hidden");
this.drawTable();
this.renderPaginationElements();
},
events: {
"click #collectionPrev" : "prevCollection",
"click #collectionNext" : "nextCollection",
"click #filterCollection" : "filterCollection",
"click #markDocuments" : "editDocuments",
"click #indexCollection" : "indexCollection",
"click #importCollection" : "importCollection",
"click #exportCollection" : "exportCollection",
"click #filterSend" : "sendFilter",
"click #addFilterItem" : "addFilterItem",
"click .removeFilterItem" : "removeFilterItem",
"click #deleteSelected" : "deleteSelectedDocs",
"click #moveSelected" : "moveSelectedDocs",
"click #addDocumentButton" : "addDocumentModal",
"click #documents_first" : "firstDocuments",
"click #documents_last" : "lastDocuments",
"click #documents_prev" : "prevDocuments",
"click #documents_next" : "nextDocuments",
"click #confirmDeleteBtn" : "confirmDelete",
"click .key" : "nop",
"keyup" : "returnPressedHandler",
"keydown .queryline input" : "filterValueKeydown",
"click #importModal" : "showImportModal",
"click #resetView" : "resetView",
"click #confirmDocImport" : "startUpload",
"click #exportDocuments" : "startDownload",
"change #newIndexType" : "selectIndexType",
"click #createIndex" : "createIndex",
"click .deleteIndex" : "prepDeleteIndex",
"click #confirmDeleteIndexBtn" : "deleteIndex",
"click #documentsToolbar ul" : "resetIndexForms",
"click #indexHeader #addIndex" : "toggleNewIndexView",
"click #indexHeader #cancelIndex" : "toggleNewIndexView",
"change #documentSize" : "setPagesize",
"change #docsSort" : "setSorting"
},
showSpinner: function() {
$('#uploadIndicator').show();
},
hideSpinner: function() {
$('#uploadIndicator').hide();
},
showImportModal: function() {
$("#docImportModal").modal('show');
},
hideImportModal: function() {
$("#docImportModal").modal('hide');
},
setPagesize: function() {
var size = $('#documentSize').find(":selected").val();
this.collection.setPagesize(size);
this.collection.getDocuments(this.getDocsCallback.bind(this));
},
setSorting: function() {
var sortAttribute = $('#docsSort').val();
if (sortAttribute === '' || sortAttribute === undefined || sortAttribute === null) {
sortAttribute = '_key';
}
this.collection.setSort(sortAttribute);
},
returnPressedHandler: function(event) {
if (event.keyCode === 13 && $(event.target).is($('#docsSort'))) {
this.collection.getDocuments(this.getDocsCallback.bind(this));
}
if (event.keyCode === 13) {
if ($("#confirmDeleteBtn").attr("disabled") === false) {
this.confirmDelete();
}
}
},
toggleNewIndexView: function () {
$('#indexEditView').toggle("fast");
$('#newIndexView').toggle("fast");
this.resetIndexForms();
},
nop: function(event) {
event.stopPropagation();
},
resetView: function () {
//clear all input/select - fields
$('input').val('');
$('select').val('==');
this.removeAllFilterItems();
$('#documentSize').val(this.collection.getPageSize());
$('#documents_last').css("visibility", "visible");
$('#documents_first').css("visibility", "visible");
this.addDocumentSwitch = true;
this.collection.resetFilter();
this.collection.loadTotal();
this.restoredFilters = [];
//for resetting json upload
this.allowUpload = false;
this.files = undefined;
this.file = undefined;
$('#confirmDocImport').attr("disabled", true);
this.markFilterToggle();
this.collection.getDocuments(this.getDocsCallback.bind(this));
},
startDownload: function() {
var query = this.collection.buildDownloadDocumentQuery();
if (query !== '' || query !== undefined || query !== null) {
window.open(encodeURI("query/result/download/" + btoa(JSON.stringify(query))));
}
else {
arangoHelper.arangoError("Document error", "could not download documents");
}
},
startUpload: function () {
var result;
if (this.allowUpload === true) {
this.showSpinner();
result = this.collection.uploadDocuments(this.file);
if (result !== true) {
this.hideSpinner();
this.hideImportModal();
this.resetView();
arangoHelper.arangoError(result);
return;
}
this.hideSpinner();
this.hideImportModal();
this.resetView();
return;
}
},
uploadSetup: function () {
var self = this;
$('#importDocuments').change(function(e) {
self.files = e.target.files || e.dataTransfer.files;
self.file = self.files[0];
$('#confirmDocImport').attr("disabled", false);
self.allowUpload = true;
});
},
buildCollectionLink : function (collection) {
return "collection/" + encodeURIComponent(collection.get('name')) + '/documents/1';
},
/*
prevCollection : function () {
if (this.collectionContext.prev !== null) {
$('#collectionPrev').parent().removeClass('disabledPag');
window.App.navigate(
this.buildCollectionLink(
this.collectionContext.prev
),
{
trigger: true
}
);
}
else {
$('#collectionPrev').parent().addClass('disabledPag');
}
},
nextCollection : function () {
if (this.collectionContext.next !== null) {
$('#collectionNext').parent().removeClass('disabledPag');
window.App.navigate(
this.buildCollectionLink(
this.collectionContext.next
),
{
trigger: true
}
);
}
else {
$('#collectionNext').parent().addClass('disabledPag');
}
},*/
markFilterToggle: function () {
if (this.restoredFilters.length > 0) {
$('#filterCollection').addClass('activated');
}
else {
$('#filterCollection').removeClass('activated');
}
},
//need to make following functions automatically!
editDocuments: function () {
$('#indexCollection').removeClass('activated');
$('#importCollection').removeClass('activated');
$('#exportCollection').removeClass('activated');
this.markFilterToggle();
$('#markDocuments').toggleClass('activated');
this.changeEditMode();
$('#filterHeader').hide();
$('#importHeader').hide();
$('#indexHeader').hide();
$('#editHeader').slideToggle(200);
$('#exportHeader').hide();
},
filterCollection : function () {
$('#indexCollection').removeClass('activated');
$('#importCollection').removeClass('activated');
$('#exportCollection').removeClass('activated');
$('#markDocuments').removeClass('activated');
this.changeEditMode(false);
this.markFilterToggle();
this.activeFilter = true;
$('#importHeader').hide();
$('#indexHeader').hide();
$('#editHeader').hide();
$('#exportHeader').hide();
$('#filterHeader').slideToggle(200);
var i;
for (i in this.filters) {
if (this.filters.hasOwnProperty(i)) {
$('#attribute_name' + i).focus();
return;
}
}
},
exportCollection: function () {
$('#indexCollection').removeClass('activated');
$('#importCollection').removeClass('activated');
$('#filterHeader').removeClass('activated');
$('#markDocuments').removeClass('activated');
this.changeEditMode(false);
$('#exportCollection').toggleClass('activated');
this.markFilterToggle();
$('#exportHeader').slideToggle(200);
$('#importHeader').hide();
$('#indexHeader').hide();
$('#filterHeader').hide();
$('#editHeader').hide();
},
importCollection: function () {
this.markFilterToggle();
$('#indexCollection').removeClass('activated');
$('#markDocuments').removeClass('activated');
this.changeEditMode(false);
$('#importCollection').toggleClass('activated');
$('#exportCollection').removeClass('activated');
$('#importHeader').slideToggle(200);
$('#filterHeader').hide();
$('#indexHeader').hide();
$('#editHeader').hide();
$('#exportHeader').hide();
},
indexCollection: function () {
this.markFilterToggle();
$('#importCollection').removeClass('activated');
$('#exportCollection').removeClass('activated');
$('#markDocuments').removeClass('activated');
this.changeEditMode(false);
$('#indexCollection').toggleClass('activated');
$('#newIndexView').hide();
$('#indexEditView').show();
$('#indexHeader').slideToggle(200);
$('#importHeader').hide();
$('#editHeader').hide();
$('#filterHeader').hide();
$('#exportHeader').hide();
},
changeEditMode: function (enable) {
if (enable === false || this.editMode === true) {
$('#documentsTableID tbody tr').css('cursor', 'default');
$('.deleteButton').fadeIn();
$('.addButton').fadeIn();
$('.selected-row').removeClass('selected-row');
this.editMode = false;
this.tableView.setRowClick(this.clicked.bind(this));
}
else {
$('#documentsTableID tbody tr').css('cursor', 'copy');
$('.deleteButton').fadeOut();
$('.addButton').fadeOut();
$('.selectedCount').text(0);
this.editMode = true;
this.tableView.setRowClick(this.editModeClick.bind(this));
}
},
getFilterContent: function () {
var filters = [ ];
var i;
for (i in this.filters) {
if (this.filters.hasOwnProperty(i)) {
var value = $('#attribute_value' + i).val();
try {
value = JSON.parse(value);
}
catch (err) {
value = String(value);
}
if ($('#attribute_name' + i).val() !== ''){
filters.push({
attribute : $('#attribute_name'+i).val(),
operator : $('#operator'+i).val(),
value : value
});
}
}
}
return filters;
},
sendFilter : function () {
this.restoredFilters = this.getFilterContent();
var self = this;
this.collection.resetFilter();
this.addDocumentSwitch = false;
_.each(this.restoredFilters, function (f) {
if (f.operator !== undefined) {
self.collection.addFilter(f.attribute, f.operator, f.value);
}
});
this.collection.setToFirst();
this.collection.getDocuments(this.getDocsCallback.bind(this));
this.markFilterToggle();
},
restoreFilter: function () {
var self = this, counter = 0;
this.filterId = 0;
$('#docsSort').val(this.collection.getSort());
_.each(this.restoredFilters, function (f) {
//change html here and restore filters
if (counter !== 0) {
self.addFilterItem();
}
if (f.operator !== undefined) {
$('#attribute_name' + counter).val(f.attribute);
$('#operator' + counter).val(f.operator);
$('#attribute_value' + counter).val(f.value);
}
counter++;
//add those filters also to the collection
self.collection.addFilter(f.attribute, f.operator, f.value);
});
},
addFilterItem : function () {
// adds a line to the filter widget
var num = ++this.filterId;
$('#filterHeader').append(' <div class="queryline querylineAdd">'+
'<input id="attribute_name' + num +
'" type="text" placeholder="Attribute name">'+
'<select name="operator" id="operator' +
num + '" class="filterSelect">'+
' <option value="==">==</option>'+
' <option value="!=">!=</option>'+
' <option value="<"><</option>'+
' <option value="<="><=</option>'+
' <option value=">=">>=</option>'+
' <option value=">">></option>'+
'</select>'+
'<input id="attribute_value' + num +
'" type="text" placeholder="Attribute value" ' +
'class="filterValue">'+
' <a class="removeFilterItem" id="removeFilter' + num + '">' +
'<i class="icon icon-minus arangoicon"></i></a></div>');
this.filters[num] = true;
},
filterValueKeydown : function (e) {
if (e.keyCode === 13) {
this.sendFilter();
}
},
removeFilterItem : function (e) {
// removes line from the filter widget
var button = e.currentTarget;
var filterId = button.id.replace(/^removeFilter/, '');
// remove the filter from the list
delete this.filters[filterId];
delete this.restoredFilters[filterId];
// remove the line from the DOM
$(button.parentElement).remove();
},
removeAllFilterItems : function () {
var childrenLength = $('#filterHeader').children().length;
var i;
for (i = 1; i <= childrenLength; i++) {
$('#removeFilter'+i).parent().remove();
}
this.filters = { "0" : true };
this.filterId = 0;
},
addDocumentModal: function () {
var collid = window.location.hash.split("/")[1],
buttons = [], tableContent = [],
// second parameter is "true" to disable caching of collection type
doctype = arangoHelper.collectionApiType(collid, true);
if (doctype === 'edge') {
tableContent.push(
window.modalView.createTextEntry(
'new-edge-from-attr',
'_from',
'',
"document _id: document handle of the linked vertex (incoming relation)",
undefined,
false,
[
{
rule: Joi.string().required(),
msg: "No _from attribute given."
}
]
)
);
tableContent.push(
window.modalView.createTextEntry(
'new-edge-to',
'_to',
'',
"document _id: document handle of the linked vertex (outgoing relation)",
undefined,
false,
[
{
rule: Joi.string().required(),
msg: "No _to attribute given."
}
]
)
);
tableContent.push(
window.modalView.createTextEntry(
'new-edge-key-attr',
'_key',
undefined,
"the edges unique key(optional attribute, leave empty for autogenerated key",
'is optional: leave empty for autogenerated key',
false,
[
{/*optional validation rules for joi*/}
]
)
);
buttons.push(
window.modalView.createSuccessButton('Create', this.addEdge.bind(this))
);
window.modalView.show(
'modalTable.ejs',
'Create edge',
buttons,
tableContent
);
return;
}
else {
tableContent.push(
window.modalView.createTextEntry(
'new-document-key-attr',
'_key',
undefined,
"the documents unique key(optional attribute, leave empty for autogenerated key",
'is optional: leave empty for autogenerated key',
false,
[
{/*optional validation rules for joi*/}
]
)
);
buttons.push(
window.modalView.createSuccessButton('Create', this.addDocument.bind(this))
);
window.modalView.show(
'modalTable.ejs',
'Create document',
buttons,
tableContent
);
}
},
addEdge: function () {
var collid = window.location.hash.split("/")[1];
var from = $('.modal-body #new-edge-from-attr').last().val();
var to = $('.modal-body #new-edge-to').last().val();
var key = $('.modal-body #new-edge-key-attr').last().val();
var result;
if (key !== '' || key !== undefined) {
result = this.documentStore.createTypeEdge(collid, from, to, key);
}
else {
result = this.documentStore.createTypeEdge(collid, from, to);
}
if (result !== false) {
//$('#edgeCreateModal').modal('hide');
window.modalView.hide();
window.location.hash = "collection/"+result;
}
//Error
else {
arangoHelper.arangoError('Creating edge failed');
}
},
addDocument: function() {
var collid = window.location.hash.split("/")[1];
var key = $('.modal-body #new-document-key-attr').last().val();
var result;
if (key !== '' || key !== undefined) {
result = this.documentStore.createTypeDocument(collid, key);
}
else {
result = this.documentStore.createTypeDocument(collid);
}
//Success
if (result !== false) {
window.modalView.hide();
window.location.hash = "collection/" + result;
}
else {
arangoHelper.arangoError('Creating document failed');
}
},
moveSelectedDocs: function() {
var buttons = [], tableContent = [],
toDelete = this.getSelectedDocs();
if (toDelete.length === 0) {
return;
}
tableContent.push(
window.modalView.createTextEntry(
'move-documents-to',
'Move to',
'',
false,
'collection-name',
true,
[
{
rule: Joi.string().regex(/^[a-zA-Z]/),
msg: "Collection name must always start with a letter."
},
{
rule: Joi.string().regex(/^[a-zA-Z0-9\-_]*$/),
msg: 'Only Symbols "_" and "-" are allowed.'
},
{
rule: Joi.string().required(),
msg: "No collection name given."
}
]
)
);
buttons.push(
window.modalView.createSuccessButton('Move', this.confirmMoveSelectedDocs.bind(this))
);
window.modalView.show(
'modalTable.ejs',
'Move documents',
buttons,
tableContent
);
},
confirmMoveSelectedDocs: function() {
var toMove = this.getSelectedDocs(),
self = this,
toCollection = $('.modal-body').last().find('#move-documents-to').val();
var callback = function() {
this.collection.getDocuments(this.getDocsCallback.bind(this));
$('#markDocuments').click();
window.modalView.hide();
}.bind(this);
_.each(toMove, function(key) {
self.collection.moveDocument(key, self.collection.collectionID, toCollection, callback);
});
},
deleteSelectedDocs: function() {
var buttons = [], tableContent = [];
var toDelete = this.getSelectedDocs();
if (toDelete.length === 0) {
return;
}
tableContent.push(
window.modalView.createReadOnlyEntry(
undefined,
toDelete.length + ' documents selected',
'Do you want to delete all selected documents?',
undefined,
undefined,
false,
undefined
)
);
buttons.push(
window.modalView.createDeleteButton('Delete', this.confirmDeleteSelectedDocs.bind(this))
);
window.modalView.show(
'modalTable.ejs',
'Delete documents',
buttons,
tableContent
);
},
confirmDeleteSelectedDocs: function() {
var toDelete = this.getSelectedDocs();
var deleted = [], self = this;
_.each(toDelete, function(key) {
var result = false;
if (self.type === 'document') {
result = self.documentStore.deleteDocument(
self.collection.collectionID, key
);
if (result) {
//on success
deleted.push(true);
self.collection.setTotalMinusOne();
}
else {
deleted.push(false);
arangoHelper.arangoError('Document error', 'Could not delete document.');
}
}
else if (self.type === 'edge') {
result = self.documentStore.deleteEdge(self.collection.collectionID, key);
if (result === true) {
//on success
self.collection.setTotalMinusOne();
deleted.push(true);
}
else {
deleted.push(false);
arangoHelper.arangoError('Edge error', 'Could not delete edge');
}
}
});
this.collection.getDocuments(this.getDocsCallback.bind(this));
$('#markDocuments').click();
window.modalView.hide();
},
getSelectedDocs: function() {
var toDelete = [];
_.each($('#documentsTableID tbody tr'), function(element) {
if ($(element).hasClass('selected-row')) {
toDelete.push($($(element).children()[1]).find('.key').text());
}
});
return toDelete;
},
remove: function (a) {
this.docid = $(a.currentTarget).closest("tr").attr("id").substr(4);
$("#confirmDeleteBtn").attr("disabled", false);
$('#docDeleteModal').modal('show');
},
confirmDelete: function () {
$("#confirmDeleteBtn").attr("disabled", true);
var hash = window.location.hash.split("/");
var check = hash[3];
//to_do - find wrong event handler
if (check !== 'source') {
this.reallyDelete();
}
},
reallyDelete: function () {
var self = this;
var row = $(self.target).closest("tr").get(0);
var deleted = false;
var result;
if (this.type === 'document') {
result = this.documentStore.deleteDocument(
this.collection.collectionID, this.docid
);
if (result) {
//on success
this.collection.setTotalMinusOne();
deleted = true;
}
else {
arangoHelper.arangoError('Doc error');
}
}
else if (this.type === 'edge') {
result = this.documentStore.deleteEdge(this.collection.collectionID, this.docid);
if (result === true) {
//on success
this.collection.setTotalMinusOne();
deleted = true;
}
else {
arangoHelper.arangoError('Edge error');
}
}
if (deleted === true) {
this.collection.getDocuments(this.getDocsCallback.bind(this));
$('#docDeleteModal').modal('hide');
}
},
editModeClick: function(event) {
var target = $(event.currentTarget);
if(target.hasClass('selected-row')) {
target.removeClass('selected-row');
} else {
target.addClass('selected-row');
}
var selected = this.getSelectedDocs();
$('.selectedCount').text(selected.length);
_.each(this.editButtons, function(button) {
if (selected.length > 0) {
$(button).prop('disabled', false);
$(button).removeClass('button-neutral');
$(button).removeClass('disabled');
if (button === "#moveSelected") {
$(button).addClass('button-success');
}
else {
$(button).addClass('button-danger');
}
}
else {
$(button).prop('disabled', true);
$(button).addClass('disabled');
$(button).addClass('button-neutral');
if (button === "#moveSelected") {
$(button).removeClass('button-success');
}
else {
$(button).removeClass('button-danger');
}
}
});
},
clicked: function (event) {
var self = event.currentTarget;
window.App.navigate("collection/" + this.collection.collectionID + "/" + $(self).attr("id").substr(4), true);
},
drawTable: function() {
this.tableView.setElement($(this.table)).render();
// we added some icons, so we need to fix their tooltips
arangoHelper.fixTooltips(".icon_arangodb, .arangoicon", "top");
$(".prettify").snippet("javascript", {
style: "nedit",
menu: false,
startText: false,
transparent: true,
showNum: false
});
},
checkCollectionState: function() {
if (this.lastCollectionName === this.collectionName) {
if (this.activeFilter) {
this.filterCollection();
this.restoreFilter();
}
}
else {
if (this.lastCollectionName !== undefined) {
this.collection.resetFilter();
this.collection.setSort('_key');
this.restoredFilters = [];
this.activeFilter = false;
}
}
},
render: function() {
$(this.el).html(this.template.render({}));
this.tableView.setElement($(this.table)).drawLoading();
this.collectionContext = this.collectionsStore.getPosition(
this.collection.collectionID
);
this.getIndex();
this.breadcrumb();
this.checkCollectionState();
//set last active collection name
this.lastCollectionName = this.collectionName;
/*
if (this.collectionContext.prev === null) {
$('#collectionPrev').parent().addClass('disabledPag');
}
if (this.collectionContext.next === null) {
$('#collectionNext').parent().addClass('disabledPag');
}
*/
this.uploadSetup();
$("[data-toggle=tooltip]").tooltip();
$('.upload-info').tooltip();
arangoHelper.fixTooltips(".icon_arangodb, .arangoicon", "top");
this.renderPaginationElements();
this.selectActivePagesize();
this.markFilterToggle();
return this;
},
rerender : function () {
this.collection.getDocuments(this.getDocsCallback.bind(this));
},
selectActivePagesize: function() {
$('#documentSize').val(this.collection.getPageSize());
},
renderPaginationElements: function () {
this.renderPagination();
var total = $('#totalDocuments');
if (total.length === 0) {
$('#documentsToolbarFL').append(
'<a id="totalDocuments" class="totalDocuments"></a>'
);
total = $('#totalDocuments');
}
total.html(this.collection.getTotal() + " document(s)");
},
breadcrumb: function () {
this.collectionName = window.location.hash.split("/")[1];
$('#transparentHeader').append(
'<div class="breadcrumb">'+
'<a class="activeBread" href="#collections">Collections</a>'+
'<span class="disabledBread">></span>'+
'<a class="disabledBread">'+this.collectionName+'</a>'+
'</div>'
);
},
resetIndexForms: function () {
$('#indexHeader input').val('').prop("checked", false);
$('#newIndexType').val('Cap').prop('selected',true);
this.selectIndexType();
},
stringToArray: function (fieldString) {
var fields = [];
fieldString.split(',').forEach(function(field){
field = field.replace(/(^\s+|\s+$)/g,'');
if (field !== '') {
fields.push(field);
}
});
return fields;
},
createIndex: function () {
//e.preventDefault();
var self = this;
var indexType = $('#newIndexType').val();
var result;
var postParameter = {};
var fields;
var unique;
var sparse;
switch (indexType) {
case 'Cap':
var size = parseInt($('#newCapSize').val(), 10) || 0;
var byteSize = parseInt($('#newCapByteSize').val(), 10) || 0;
postParameter = {
type: 'cap',
size: size,
byteSize: byteSize
};
break;
case 'Geo':
//HANDLE ARRAY building
fields = $('#newGeoFields').val();
var geoJson = self.checkboxToValue('#newGeoJson');
var constraint = self.checkboxToValue('#newGeoConstraint');
var ignoreNull = self.checkboxToValue('#newGeoIgnoreNull');
postParameter = {
type: 'geo',
fields: self.stringToArray(fields),
geoJson: geoJson,
constraint: constraint,
ignoreNull: ignoreNull
};
break;
case 'Hash':
fields = $('#newHashFields').val();
unique = self.checkboxToValue('#newHashUnique');
sparse = self.checkboxToValue('#newHashSparse');
postParameter = {
type: 'hash',
fields: self.stringToArray(fields),
unique: unique,
sparse: sparse
};
break;
case 'Fulltext':
fields = ($('#newFulltextFields').val());
var minLength = parseInt($('#newFulltextMinLength').val(), 10) || 0;
postParameter = {
type: 'fulltext',
fields: self.stringToArray(fields),
minLength: minLength
};
break;
case 'Skiplist':
fields = $('#newSkiplistFields').val();
unique = self.checkboxToValue('#newSkiplistUnique');
sparse = self.checkboxToValue('#newSkiplistSparse');
postParameter = {
type: 'skiplist',
fields: self.stringToArray(fields),
unique: unique,
sparse: sparse
};
break;
}
result = self.collectionModel.createIndex(postParameter);
if (result === true) {
$('#collectionEditIndexTable tbody tr').remove();
self.getIndex();
self.toggleNewIndexView();
self.resetIndexForms();
}
else {
if (result.responseText) {
var message = JSON.parse(result.responseText);
arangoHelper.arangoNotification("Document error", message.errorMessage);
}
else {
arangoHelper.arangoNotification("Document error", "Could not create index.");
}
}
},
prepDeleteIndex: function (e) {
this.lastTarget = e;
this.lastId = $(this.lastTarget.currentTarget).
parent().
parent().
first().
children().
first().
text();
$("#indexDeleteModal").modal('show');
},
deleteIndex: function () {
var result = this.collectionModel.deleteIndex(this.lastId);
if (result === true) {
$(this.lastTarget.currentTarget).parent().parent().remove();
}
else {
arangoHelper.arangoError("Could not delete index");
}
$("#indexDeleteModal").modal('hide');
},
selectIndexType: function () {
$('.newIndexClass').hide();
var type = $('#newIndexType').val();
$('#newIndexType'+type).show();
},
checkboxToValue: function (id) {
return $(id).prop('checked');
},
getIndex: function () {
this.index = this.collectionModel.getIndex();
var cssClass = 'collectionInfoTh modal-text';
if (this.index) {
var fieldString = '';
var actionString = '';
$.each(this.index.indexes, function(k, v) {
if (v.type === 'primary' || v.type === 'edge') {
actionString = '<span class="icon_arangodb_locked" ' +
'data-original-title="No action"></span>';
}
else {
actionString = '<span class="deleteIndex icon_arangodb_roundminus" ' +
'data-original-title="Delete index" title="Delete index"></span>';
}
if (v.fields !== undefined) {
fieldString = v.fields.join(", ");
}
//cut index id
var position = v.id.indexOf('/');
var indexId = v.id.substr(position + 1, v.id.length);
var selectivity = (
v.hasOwnProperty("selectivityEstimate") ?
(v.selectivityEstimate * 100).toFixed(2) + "%" :
"n/a"
);
var sparse = (v.hasOwnProperty("sparse") ? v.sparse : "n/a");
$('#collectionEditIndexTable').append(
'<tr>' +
'<th class=' + JSON.stringify(cssClass) + '>' + indexId + '</th>' +
'<th class=' + JSON.stringify(cssClass) + '>' + v.type + '</th>' +
'<th class=' + JSON.stringify(cssClass) + '>' + v.unique + '</th>' +
'<th class=' + JSON.stringify(cssClass) + '>' + sparse + '</th>' +
'<th class=' + JSON.stringify(cssClass) + '>' + selectivity + '</th>' +
'<th class=' + JSON.stringify(cssClass) + '>' + fieldString + '</th>' +
'<th class=' + JSON.stringify(cssClass) + '>' + actionString + '</th>' +
'</tr>'
);
});
arangoHelper.fixTooltips("deleteIndex", "left");
}
}
});
}());
| abaditsegay/arangodb | js/apps/system/_admin/aardvark/APP/frontend/js/views/documentsView.js | JavaScript | apache-2.0 | 35,454 |
/*
* Copyright 2010-2013 Ning, Inc.
* Copyright 2014-2015 Groupon, Inc
* Copyright 2014-2015 The Billing Project, LLC
*
* The Billing Project 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.subscription.engine.dao;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.UUID;
import org.joda.time.DateTime;
import org.killbill.billing.callcontext.InternalCallContext;
import org.killbill.billing.callcontext.InternalTenantContext;
import org.killbill.billing.catalog.api.CatalogApiException;
import org.killbill.billing.catalog.api.CatalogService;
import org.killbill.billing.catalog.api.ProductCategory;
import org.killbill.billing.catalog.api.TimeUnit;
import org.killbill.billing.dao.MockNonEntityDao;
import org.killbill.billing.entitlement.api.SubscriptionApiException;
import org.killbill.billing.subscription.api.SubscriptionBase;
import org.killbill.billing.subscription.api.migration.AccountMigrationData;
import org.killbill.billing.subscription.api.migration.AccountMigrationData.BundleMigrationData;
import org.killbill.billing.subscription.api.migration.AccountMigrationData.SubscriptionMigrationData;
import org.killbill.billing.subscription.api.transfer.TransferCancelData;
import org.killbill.billing.subscription.api.user.DefaultSubscriptionBase;
import org.killbill.billing.subscription.api.user.DefaultSubscriptionBaseBundle;
import org.killbill.billing.subscription.api.user.SubscriptionBaseBundle;
import org.killbill.billing.subscription.api.user.SubscriptionBuilder;
import org.killbill.billing.subscription.engine.core.DefaultSubscriptionBaseService;
import org.killbill.billing.subscription.engine.core.SubscriptionNotificationKey;
import org.killbill.billing.subscription.engine.dao.model.SubscriptionBundleModelDao;
import org.killbill.billing.subscription.events.SubscriptionBaseEvent;
import org.killbill.billing.subscription.events.SubscriptionBaseEvent.EventType;
import org.killbill.billing.subscription.events.user.ApiEvent;
import org.killbill.billing.subscription.events.user.ApiEventType;
import org.killbill.billing.util.entity.DefaultPagination;
import org.killbill.billing.util.entity.Pagination;
import org.killbill.billing.util.entity.dao.EntitySqlDaoWrapperFactory;
import org.killbill.billing.util.entity.dao.MockEntityDaoBase;
import org.killbill.clock.Clock;
import org.killbill.notificationq.api.NotificationEvent;
import org.killbill.notificationq.api.NotificationQueue;
import org.killbill.notificationq.api.NotificationQueueService;
import org.killbill.notificationq.api.NotificationQueueService.NoSuchNotificationQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Inject;
public class MockSubscriptionDaoMemory extends MockEntityDaoBase<SubscriptionBundleModelDao, SubscriptionBaseBundle, SubscriptionApiException> implements SubscriptionDao {
protected static final Logger log = LoggerFactory.getLogger(SubscriptionDao.class);
private final List<SubscriptionBaseBundle> bundles;
private final List<SubscriptionBase> subscriptions;
private final TreeSet<SubscriptionBaseEvent> events;
private final MockNonEntityDao mockNonEntityDao;
private final Clock clock;
private final NotificationQueueService notificationQueueService;
private final CatalogService catalogService;
@Inject
public MockSubscriptionDaoMemory(final MockNonEntityDao mockNonEntityDao,
final Clock clock,
final NotificationQueueService notificationQueueService,
final CatalogService catalogService) {
super();
this.mockNonEntityDao = mockNonEntityDao;
this.clock = clock;
this.catalogService = catalogService;
this.notificationQueueService = notificationQueueService;
this.bundles = new ArrayList<SubscriptionBaseBundle>();
this.subscriptions = new ArrayList<SubscriptionBase>();
this.events = new TreeSet<SubscriptionBaseEvent>();
}
public void reset() {
bundles.clear();
subscriptions.clear();
events.clear();
}
@Override
public List<SubscriptionBaseBundle> getSubscriptionBundleForAccount(final UUID accountId, final InternalTenantContext context) {
final List<SubscriptionBaseBundle> results = new ArrayList<SubscriptionBaseBundle>();
for (final SubscriptionBaseBundle cur : bundles) {
if (cur.getAccountId().equals(accountId)) {
results.add(cur);
}
}
return results;
}
@Override
public List<SubscriptionBaseBundle> getSubscriptionBundlesForKey(final String bundleKey, final InternalTenantContext context) {
final List<SubscriptionBaseBundle> results = new ArrayList<SubscriptionBaseBundle>();
for (final SubscriptionBaseBundle cur : bundles) {
if (cur.getExternalKey().equals(bundleKey)) {
results.add(cur);
}
}
return results;
}
@Override
public Pagination<SubscriptionBundleModelDao> searchSubscriptionBundles(final String searchKey, final Long offset, final Long limit, final InternalTenantContext context) {
final List<SubscriptionBundleModelDao> results = new LinkedList<SubscriptionBundleModelDao>();
for (final SubscriptionBundleModelDao bundleModelDao : getAll(context)) {
if (bundleModelDao.getId().toString().equals(searchKey) ||
bundleModelDao.getExternalKey().equals(searchKey) ||
bundleModelDao.getAccountId().toString().equals(searchKey)) {
results.add(bundleModelDao);
}
}
return DefaultPagination.<SubscriptionBundleModelDao>build(offset, limit, results);
}
@Override
public List<UUID> getNonAOSubscriptionIdsForKey(final String bundleKey, final InternalTenantContext context) {
throw new UnsupportedOperationException();
}
@Override
public SubscriptionBaseBundle getSubscriptionBundleFromId(final UUID bundleId, final InternalTenantContext context) {
for (final SubscriptionBaseBundle cur : bundles) {
if (cur.getId().equals(bundleId)) {
return cur;
}
}
return null;
}
@Override
public List<SubscriptionBaseBundle> getSubscriptionBundlesForAccountAndKey(final UUID accountId, final String bundleKey, final InternalTenantContext context) {
final List<SubscriptionBaseBundle> results = new ArrayList<SubscriptionBaseBundle>();
for (final SubscriptionBaseBundle cur : bundles) {
if (cur.getExternalKey().equals(bundleKey) && cur.getAccountId().equals(accountId)) {
results.add(cur);
}
}
return results;
}
@Override
public SubscriptionBaseBundle createSubscriptionBundle(final DefaultSubscriptionBaseBundle bundle, final InternalCallContext context) {
bundles.add(bundle);
mockNonEntityDao.addTenantRecordIdMapping(bundle.getId(), context);
return getSubscriptionBundleFromId(bundle.getId(), context);
}
@Override
public SubscriptionBase getSubscriptionFromId(final UUID subscriptionId, final InternalTenantContext context) {
for (final SubscriptionBase cur : subscriptions) {
if (cur.getId().equals(subscriptionId)) {
return buildSubscription((DefaultSubscriptionBase) cur, context);
}
}
return null;
}
@Override
public UUID getAccountIdFromSubscriptionId(final UUID subscriptionId, final InternalTenantContext context) {
throw new UnsupportedOperationException();
}
/*
@Override
public List<SubscriptionBase> getSubscriptionsForAccountAndKey(final UUID accountId, final String bundleKey, final InternalTenantContext callcontext) {
for (final SubscriptionBaseBundle cur : bundles) {
if (cur.getExternalKey().equals(bundleKey) && cur.getAccountId().equals(bundleKey)) {
return getSubscriptions(cur.getId(), callcontext);
}
}
return Collections.emptyList();
}
*/
@Override
public void createSubscription(final DefaultSubscriptionBase subscription, final List<SubscriptionBaseEvent> initialEvents,
final InternalCallContext context) {
synchronized (events) {
events.addAll(initialEvents);
for (final SubscriptionBaseEvent cur : initialEvents) {
recordFutureNotificationFromTransaction(null, cur.getEffectiveDate(), new SubscriptionNotificationKey(cur.getId()), context);
}
}
final SubscriptionBase updatedSubscription = buildSubscription(subscription, context);
subscriptions.add(updatedSubscription);
mockNonEntityDao.addTenantRecordIdMapping(updatedSubscription.getId(), context);
}
@Override
public void createSubscriptionWithAddOns(final List<DefaultSubscriptionBase> subscriptions,
final Map<UUID, List<SubscriptionBaseEvent>> initialEventsMap,
final InternalCallContext context) {
synchronized (events) {
for (DefaultSubscriptionBase subscription : subscriptions) {
final List<SubscriptionBaseEvent> initialEvents = initialEventsMap.get(subscription.getId());
events.addAll(initialEvents);
for (final SubscriptionBaseEvent cur : initialEvents) {
recordFutureNotificationFromTransaction(null, cur.getEffectiveDate(), new SubscriptionNotificationKey(cur.getId()), context);
}
final SubscriptionBase updatedSubscription = buildSubscription(subscription, context);
this.subscriptions.add(updatedSubscription);
mockNonEntityDao.addTenantRecordIdMapping(updatedSubscription.getId(), context);
}
}
}
@Override
public void recreateSubscription(final DefaultSubscriptionBase subscription, final List<SubscriptionBaseEvent> recreateEvents, final InternalCallContext context) {
synchronized (events) {
events.addAll(recreateEvents);
for (final SubscriptionBaseEvent cur : recreateEvents) {
recordFutureNotificationFromTransaction(null, cur.getEffectiveDate(), new SubscriptionNotificationKey(cur.getId()), context);
}
}
}
@Override
public List<SubscriptionBase> getSubscriptions(final UUID bundleId, final List<SubscriptionBaseEvent> dryRunEvents, final InternalTenantContext context) {
final List<SubscriptionBase> results = new ArrayList<SubscriptionBase>();
for (final SubscriptionBase cur : subscriptions) {
if (cur.getBundleId().equals(bundleId)) {
results.add(buildSubscription((DefaultSubscriptionBase) cur, context));
}
}
return results;
}
@Override
public Map<UUID, List<SubscriptionBase>> getSubscriptionsForAccount(final InternalTenantContext context) {
final Map<UUID, List<SubscriptionBase>> results = new HashMap<UUID, List<SubscriptionBase>>();
for (final SubscriptionBase cur : subscriptions) {
if (results.get(cur.getBundleId()) == null) {
results.put(cur.getBundleId(), new LinkedList<SubscriptionBase>());
}
results.get(cur.getBundleId()).add(buildSubscription((DefaultSubscriptionBase) cur, context));
}
return results;
}
@Override
public List<SubscriptionBaseEvent> getEventsForSubscription(final UUID subscriptionId, final InternalTenantContext context) {
synchronized (events) {
final List<SubscriptionBaseEvent> results = new LinkedList<SubscriptionBaseEvent>();
for (final SubscriptionBaseEvent cur : events) {
if (cur.getSubscriptionId().equals(subscriptionId)) {
results.add(cur);
}
}
return results;
}
}
@Override
public List<SubscriptionBaseEvent> getPendingEventsForSubscription(final UUID subscriptionId, final InternalTenantContext context) {
synchronized (events) {
final List<SubscriptionBaseEvent> results = new LinkedList<SubscriptionBaseEvent>();
for (final SubscriptionBaseEvent cur : events) {
if (cur.isActive() &&
cur.getEffectiveDate().isAfter(clock.getUTCNow()) &&
cur.getSubscriptionId().equals(subscriptionId)) {
results.add(cur);
}
}
return results;
}
}
@Override
public SubscriptionBase getBaseSubscription(final UUID bundleId, final InternalTenantContext context) {
for (final SubscriptionBase cur : subscriptions) {
if (cur.getBundleId().equals(bundleId) &&
cur.getCurrentPlan().getProduct().getCategory() == ProductCategory.BASE) {
return buildSubscription((DefaultSubscriptionBase) cur, context);
}
}
return null;
}
@Override
public void createNextPhaseEvent(final DefaultSubscriptionBase subscription, final SubscriptionBaseEvent nextPhase, final InternalCallContext context) {
cancelNextPhaseEvent(subscription.getId(), context);
insertEvent(nextPhase, context);
}
private SubscriptionBase buildSubscription(final DefaultSubscriptionBase in, final InternalTenantContext context) {
final DefaultSubscriptionBase subscription = new DefaultSubscriptionBase(new SubscriptionBuilder(in), null, clock);
if (events.size() > 0) {
try {
subscription.rebuildTransitions(getEventsForSubscription(in.getId(), context), catalogService.getFullCatalog(context));
} catch (final CatalogApiException e) {
log.warn("Failed to rebuild subscription", e);
}
}
return subscription;
}
@Override
public void updateChargedThroughDate(final DefaultSubscriptionBase subscription, final InternalCallContext context) {
boolean found = false;
final Iterator<SubscriptionBase> it = subscriptions.iterator();
while (it.hasNext()) {
final SubscriptionBase cur = it.next();
if (cur.getId().equals(subscription.getId())) {
found = true;
it.remove();
break;
}
}
if (found) {
subscriptions.add(subscription);
}
}
@Override
public void cancelSubscription(final DefaultSubscriptionBase subscription, final SubscriptionBaseEvent cancelEvent,
final InternalCallContext context, final int seqId) {
synchronized (events) {
cancelNextPhaseEvent(subscription.getId(), context);
insertEvent(cancelEvent, context);
}
}
@Override
public void cancelSubscriptions(final List<DefaultSubscriptionBase> subscriptions, final List<SubscriptionBaseEvent> cancelEvents, final InternalCallContext context) {
synchronized (events) {
for (int i = 0; i < subscriptions.size(); i++) {
cancelSubscription(subscriptions.get(i), cancelEvents.get(i), context, 0);
}
}
}
@Override
public void changePlan(final DefaultSubscriptionBase subscription, final List<SubscriptionBaseEvent> changeEvents, final InternalCallContext context) {
synchronized (events) {
cancelNextChangeEvent(subscription.getId());
cancelNextPhaseEvent(subscription.getId(), context);
events.addAll(changeEvents);
for (final SubscriptionBaseEvent cur : changeEvents) {
recordFutureNotificationFromTransaction(null, cur.getEffectiveDate(), new SubscriptionNotificationKey(cur.getId()), context);
}
}
}
private void insertEvent(final SubscriptionBaseEvent event, final InternalCallContext context) {
synchronized (events) {
events.add(event);
mockNonEntityDao.addTenantRecordIdMapping(event.getId(), context);
recordFutureNotificationFromTransaction(null, event.getEffectiveDate(), new SubscriptionNotificationKey(event.getId()), context);
}
}
private void cancelNextPhaseEvent(final UUID subscriptionId, final InternalTenantContext context) {
final SubscriptionBase curSubscription = getSubscriptionFromId(subscriptionId, context);
if (curSubscription.getCurrentPhase() == null ||
curSubscription.getCurrentPhase().getDuration().getUnit() == TimeUnit.UNLIMITED) {
return;
}
synchronized (events) {
final Iterator<SubscriptionBaseEvent> it = events.descendingIterator();
while (it.hasNext()) {
final SubscriptionBaseEvent cur = it.next();
if (cur.getSubscriptionId() != subscriptionId) {
continue;
}
if (cur.getType() == EventType.PHASE &&
cur.getEffectiveDate().isAfter(clock.getUTCNow())) {
it.remove();
break;
}
}
}
}
private void cancelNextChangeEvent(final UUID subscriptionId) {
synchronized (events) {
final Iterator<SubscriptionBaseEvent> it = events.descendingIterator();
while (it.hasNext()) {
final SubscriptionBaseEvent cur = it.next();
if (cur.getSubscriptionId() != subscriptionId) {
continue;
}
if (cur.getType() == EventType.API_USER &&
ApiEventType.CHANGE == ((ApiEvent) cur).getApiEventType() &&
cur.getEffectiveDate().isAfter(clock.getUTCNow())) {
it.remove();
break;
}
}
}
}
@Override
public void uncancelSubscription(final DefaultSubscriptionBase subscription, final List<SubscriptionBaseEvent> uncancelEvents,
final InternalCallContext context) {
synchronized (events) {
boolean foundCancel = false;
final Iterator<SubscriptionBaseEvent> it = events.descendingIterator();
while (it.hasNext()) {
final SubscriptionBaseEvent cur = it.next();
if (cur.getSubscriptionId() != subscription.getId()) {
continue;
}
if (cur.getType() == EventType.API_USER &&
((ApiEvent) cur).getApiEventType() == ApiEventType.CANCEL) {
it.remove();
foundCancel = true;
break;
}
}
if (foundCancel) {
for (final SubscriptionBaseEvent cur : uncancelEvents) {
insertEvent(cur, context);
}
}
}
}
@Override
public void migrate(final UUID accountId, final AccountMigrationData accountData, final InternalCallContext context) {
synchronized (events) {
for (final BundleMigrationData curBundle : accountData.getData()) {
final DefaultSubscriptionBaseBundle bundleData = curBundle.getData();
for (final SubscriptionMigrationData curSubscription : curBundle.getSubscriptions()) {
final DefaultSubscriptionBase subData = curSubscription.getData();
for (final SubscriptionBaseEvent curEvent : curSubscription.getInitialEvents()) {
events.add(curEvent);
mockNonEntityDao.addTenantRecordIdMapping(curEvent.getId(), context);
recordFutureNotificationFromTransaction(null, curEvent.getEffectiveDate(),
new SubscriptionNotificationKey(curEvent.getId()), context);
}
subscriptions.add(subData);
mockNonEntityDao.addTenantRecordIdMapping(subData.getId(), context);
}
bundles.add(bundleData);
mockNonEntityDao.addTenantRecordIdMapping(bundleData.getId(), context);
}
}
}
@Override
public SubscriptionBaseEvent getEventById(final UUID eventId, final InternalTenantContext context) {
synchronized (events) {
for (final SubscriptionBaseEvent cur : events) {
if (cur.getId().equals(eventId)) {
return cur;
}
}
}
return null;
}
private void recordFutureNotificationFromTransaction(final EntitySqlDaoWrapperFactory transactionalDao, final DateTime effectiveDate,
final NotificationEvent notificationKey, final InternalCallContext context) {
try {
final NotificationQueue subscriptionEventQueue = notificationQueueService.getNotificationQueue(DefaultSubscriptionBaseService.SUBSCRIPTION_SERVICE_NAME,
DefaultSubscriptionBaseService.NOTIFICATION_QUEUE_NAME);
subscriptionEventQueue.recordFutureNotificationFromTransaction(null, effectiveDate, notificationKey, context.getUserToken(), context.getAccountRecordId(), context.getTenantRecordId());
} catch (final NoSuchNotificationQueue e) {
throw new RuntimeException(e);
} catch (final IOException e) {
throw new RuntimeException(e);
}
}
@Override
public Iterable<SubscriptionBaseEvent> getFutureEventsForAccount(final InternalTenantContext context) {
return null;
}
@Override
public void transfer(final UUID srcAccountId, final UUID destAccountId, final BundleMigrationData data,
final List<TransferCancelData> transferCancelData, final InternalCallContext fromContext,
final InternalCallContext toContext) {
}
@Override
public void updateBundleExternalKey(final UUID bundleId, final String externalKey, final InternalCallContext context) {
}
}
| maguero/killbill | subscription/src/test/java/org/killbill/billing/subscription/engine/dao/MockSubscriptionDaoMemory.java | Java | apache-2.0 | 23,275 |
package org.anderes.edu.gui.pm.gui;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
/**
* View für das Presentation-Model-Pattern
*
* @author René Anderes
*/
public class View {
private final JFrame f;
private final JTextField textField;
private final JTextArea textArea;
private final PresentationModel presentationModel;
/**
* Konstruktor
*/
public View(final PresentationModel presentationModel) {
this.presentationModel = presentationModel;
f = new JFrame( "Taschenrechner" );
f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
f.setSize(300, 200);
JPanel panel = new JPanel(new GridBagLayout());
textField = new JTextField(20);
textField.setBackground(Color.WHITE);
textField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String text = textField.getText();
textField.setText("");
if (text.matches("\\d+")) {
presentationModel.input(text);
updateStack();
} else if (presentationModel.isCommandEnabled()) {
presentationModel.command(text);
updateStack();
} else {
textField.setText("Ung�ltige Funktion");
textField.selectAll();
}
}
});
textArea = new JTextArea(5, 20);
textArea.setEditable(false);
textArea.setBackground(Color.LIGHT_GRAY);
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.HORIZONTAL;
panel.add(textField, c);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
panel.add(textArea, c);
f.add(panel);
f.setVisible(true);
}
/**
* Die Anzeige des Stacks wird aktualisiert.
*/
private void updateStack() {
textArea.setText("");
for (Double d : presentationModel.getStack()) {
textArea.append(String.format("%1$f", d));
textArea.append("\n");
}
}
}
| rene-anderes/edu | oo.basics/src/main/java/org/anderes/edu/gui/pm/gui/View.java | Java | apache-2.0 | 2,276 |
package com.epam.rft.atsy.web.configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebConfiguration.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
}
| epam-debrecen-rft-2015/atsy | web/src/main/java/com/epam/rft/atsy/web/configuration/WebAppInitializer.java | Java | apache-2.0 | 532 |
/*
Copyright 2014 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package serviceaccount_test
import (
"crypto/rsa"
"io/ioutil"
"os"
"reflect"
"testing"
"github.com/dgrijalva/jwt-go"
"k8s.io/kubernetes/pkg/api"
clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_1"
"k8s.io/kubernetes/pkg/client/testing/fake"
serviceaccountcontroller "k8s.io/kubernetes/pkg/controller/serviceaccount"
"k8s.io/kubernetes/pkg/serviceaccount"
)
const otherPublicKey = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArXz0QkIG1B5Bj2/W69GH
rsm5e+RC3kE+VTgocge0atqlLBek35tRqLgUi3AcIrBZ/0YctMSWDVcRt5fkhWwe
Lqjj6qvAyNyOkrkBi1NFDpJBjYJtuKHgRhNxXbOzTSNpdSKXTfOkzqv56MwHOP25
yP/NNAODUtr92D5ySI5QX8RbXW+uDn+ixul286PBW/BCrE4tuS88dA0tYJPf8LCu
sqQOwlXYH/rNUg4Pyl9xxhR5DIJR0OzNNfChjw60zieRIt2LfM83fXhwk8IxRGkc
gPZm7ZsipmfbZK2Tkhnpsa4QxDg7zHJPMsB5kxRXW0cQipXcC3baDyN9KBApNXa0
PwIDAQAB
-----END PUBLIC KEY-----`
const publicKey = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA249XwEo9k4tM8fMxV7zx
OhcrP+WvXn917koM5Qr2ZXs4vo26e4ytdlrV0bQ9SlcLpQVSYjIxNfhTZdDt+ecI
zshKuv1gKIxbbLQMOuK1eA/4HALyEkFgmS/tleLJrhc65tKPMGD+pKQ/xhmzRuCG
51RoiMgbQxaCyYxGfNLpLAZK9L0Tctv9a0mJmGIYnIOQM4kC1A1I1n3EsXMWmeJU
j7OTh/AjjCnMnkgvKT2tpKxYQ59PgDgU8Ssc7RDSmSkLxnrv+OrN80j6xrw0OjEi
B4Ycr0PqfzZcvy8efTtFQ/Jnc4Bp1zUtFXt7+QeevePtQ2EcyELXE0i63T1CujRM
WwIDAQAB
-----END PUBLIC KEY-----
`
const privateKey = `-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEA249XwEo9k4tM8fMxV7zxOhcrP+WvXn917koM5Qr2ZXs4vo26
e4ytdlrV0bQ9SlcLpQVSYjIxNfhTZdDt+ecIzshKuv1gKIxbbLQMOuK1eA/4HALy
EkFgmS/tleLJrhc65tKPMGD+pKQ/xhmzRuCG51RoiMgbQxaCyYxGfNLpLAZK9L0T
ctv9a0mJmGIYnIOQM4kC1A1I1n3EsXMWmeJUj7OTh/AjjCnMnkgvKT2tpKxYQ59P
gDgU8Ssc7RDSmSkLxnrv+OrN80j6xrw0OjEiB4Ycr0PqfzZcvy8efTtFQ/Jnc4Bp
1zUtFXt7+QeevePtQ2EcyELXE0i63T1CujRMWwIDAQABAoIBAHJx8GqyCBDNbqk7
e7/hI9iE1S10Wwol5GH2RWxqX28cYMKq+8aE2LI1vPiXO89xOgelk4DN6urX6xjK
ZBF8RRIMQy/e/O2F4+3wl+Nl4vOXV1u6iVXMsD6JRg137mqJf1Fr9elg1bsaRofL
Q7CxPoB8dhS+Qb+hj0DhlqhgA9zG345CQCAds0ZYAZe8fP7bkwrLqZpMn7Dz9WVm
++YgYYKjuE95kPuup/LtWfA9rJyE/Fws8/jGvRSpVn1XglMLSMKhLd27sE8ZUSV0
2KUzbfRGE0+AnRULRrjpYaPu0XQ2JjdNvtkjBnv27RB89W9Gklxq821eH1Y8got8
FZodjxECgYEA93pz7AQZ2xDs67d1XLCzpX84GxKzttirmyj3OIlxgzVHjEMsvw8v
sjFiBU5xEEQDosrBdSknnlJqyiq1YwWG/WDckr13d8G2RQWoySN7JVmTQfXcLoTu
YGRiiTuoEi3ab3ZqrgGrFgX7T/cHuasbYvzCvhM2b4VIR3aSxU2DTUMCgYEA4x7J
T/ErP6GkU5nKstu/mIXwNzayEO1BJvPYsy7i7EsxTm3xe/b8/6cYOz5fvJLGH5mT
Q8YvuLqBcMwZardrYcwokD55UvNLOyfADDFZ6l3WntIqbA640Ok2g1X4U8J09xIq
ZLIWK1yWbbvi4QCeN5hvWq47e8sIj5QHjIIjRwkCgYEAyNqjltxFN9zmzPDa2d24
EAvOt3pYTYBQ1t9KtqImdL0bUqV6fZ6PsWoPCgt+DBuHb+prVPGP7Bkr/uTmznU/
+AlTO+12NsYLbr2HHagkXE31DEXE7CSLa8RNjN/UKtz4Ohq7vnowJvG35FCz/mb3
FUHbtHTXa2+bGBUOTf/5Hw0CgYBxw0r9EwUhw1qnUYJ5op7OzFAtp+T7m4ul8kCa
SCL8TxGsgl+SQ34opE775dtYfoBk9a0RJqVit3D8yg71KFjOTNAIqHJm/Vyyjc+h
i9rJDSXiuczsAVfLtPVMRfS0J9QkqeG4PIfkQmVLI/CZ2ZBmsqEcX+eFs4ZfPLun
Qsxe2QKBgGuPilIbLeIBDIaPiUI0FwU8v2j8CEQBYvoQn34c95hVQsig/o5z7zlo
UsO0wlTngXKlWdOcCs1kqEhTLrstf48djDxAYAxkw40nzeJOt7q52ib/fvf4/UBy
X024wzbiw1q07jFCyfQmODzURAx1VNT7QVUMdz/N8vy47/H40AZJ
-----END RSA PRIVATE KEY-----
`
func getPrivateKey(data string) *rsa.PrivateKey {
key, _ := jwt.ParseRSAPrivateKeyFromPEM([]byte(data))
return key
}
func getPublicKey(data string) *rsa.PublicKey {
key, _ := jwt.ParseRSAPublicKeyFromPEM([]byte(data))
return key
}
func TestReadPrivateKey(t *testing.T) {
f, err := ioutil.TempFile("", "")
if err != nil {
t.Fatalf("error creating tmpfile: %v", err)
}
defer os.Remove(f.Name())
if err := ioutil.WriteFile(f.Name(), []byte(privateKey), os.FileMode(0600)); err != nil {
t.Fatalf("error creating tmpfile: %v", err)
}
if _, err := serviceaccount.ReadPrivateKey(f.Name()); err != nil {
t.Fatalf("error reading key: %v", err)
}
}
func TestReadPublicKey(t *testing.T) {
f, err := ioutil.TempFile("", "")
if err != nil {
t.Fatalf("error creating tmpfile: %v", err)
}
defer os.Remove(f.Name())
if err := ioutil.WriteFile(f.Name(), []byte(publicKey), os.FileMode(0600)); err != nil {
t.Fatalf("error creating tmpfile: %v", err)
}
if _, err := serviceaccount.ReadPublicKey(f.Name()); err != nil {
t.Fatalf("error reading key: %v", err)
}
}
func TestTokenGenerateAndValidate(t *testing.T) {
expectedUserName := "system:serviceaccount:test:my-service-account"
expectedUserUID := "12345"
// Related API objects
serviceAccount := &api.ServiceAccount{
ObjectMeta: api.ObjectMeta{
Name: "my-service-account",
UID: "12345",
Namespace: "test",
},
}
secret := &api.Secret{
ObjectMeta: api.ObjectMeta{
Name: "my-secret",
Namespace: "test",
},
}
// Generate the token
generator := serviceaccount.JWTTokenGenerator(getPrivateKey(privateKey))
token, err := generator.GenerateToken(*serviceAccount, *secret)
if err != nil {
t.Fatalf("error generating token: %v", err)
}
if len(token) == 0 {
t.Fatalf("no token generated")
}
// "Save" the token
secret.Data = map[string][]byte{
"token": []byte(token),
}
testCases := map[string]struct {
Client clientset.Interface
Keys []*rsa.PublicKey
ExpectedErr bool
ExpectedOK bool
ExpectedUserName string
ExpectedUserUID string
ExpectedGroups []string
}{
"no keys": {
Client: nil,
Keys: []*rsa.PublicKey{},
ExpectedErr: false,
ExpectedOK: false,
},
"invalid keys": {
Client: nil,
Keys: []*rsa.PublicKey{getPublicKey(otherPublicKey)},
ExpectedErr: true,
ExpectedOK: false,
},
"valid key": {
Client: nil,
Keys: []*rsa.PublicKey{getPublicKey(publicKey)},
ExpectedErr: false,
ExpectedOK: true,
ExpectedUserName: expectedUserName,
ExpectedUserUID: expectedUserUID,
ExpectedGroups: []string{"system:serviceaccounts", "system:serviceaccounts:test"},
},
"rotated keys": {
Client: nil,
Keys: []*rsa.PublicKey{getPublicKey(otherPublicKey), getPublicKey(publicKey)},
ExpectedErr: false,
ExpectedOK: true,
ExpectedUserName: expectedUserName,
ExpectedUserUID: expectedUserUID,
ExpectedGroups: []string{"system:serviceaccounts", "system:serviceaccounts:test"},
},
"valid lookup": {
Client: fake.NewSimpleClientset(serviceAccount, secret),
Keys: []*rsa.PublicKey{getPublicKey(publicKey)},
ExpectedErr: false,
ExpectedOK: true,
ExpectedUserName: expectedUserName,
ExpectedUserUID: expectedUserUID,
ExpectedGroups: []string{"system:serviceaccounts", "system:serviceaccounts:test"},
},
"invalid secret lookup": {
Client: fake.NewSimpleClientset(serviceAccount),
Keys: []*rsa.PublicKey{getPublicKey(publicKey)},
ExpectedErr: true,
ExpectedOK: false,
},
"invalid serviceaccount lookup": {
Client: fake.NewSimpleClientset(secret),
Keys: []*rsa.PublicKey{getPublicKey(publicKey)},
ExpectedErr: true,
ExpectedOK: false,
},
}
for k, tc := range testCases {
getter := serviceaccountcontroller.NewGetterFromClient(tc.Client)
authenticator := serviceaccount.JWTTokenAuthenticator(tc.Keys, tc.Client != nil, getter)
user, ok, err := authenticator.AuthenticateToken(token)
if (err != nil) != tc.ExpectedErr {
t.Errorf("%s: Expected error=%v, got %v", k, tc.ExpectedErr, err)
continue
}
if ok != tc.ExpectedOK {
t.Errorf("%s: Expected ok=%v, got %v", k, tc.ExpectedOK, ok)
continue
}
if err != nil || !ok {
continue
}
if user.GetName() != tc.ExpectedUserName {
t.Errorf("%s: Expected username=%v, got %v", k, tc.ExpectedUserName, user.GetName())
continue
}
if user.GetUID() != tc.ExpectedUserUID {
t.Errorf("%s: Expected userUID=%v, got %v", k, tc.ExpectedUserUID, user.GetUID())
continue
}
if !reflect.DeepEqual(user.GetGroups(), tc.ExpectedGroups) {
t.Errorf("%s: Expected groups=%v, got %v", k, tc.ExpectedGroups, user.GetGroups())
continue
}
}
}
func TestMakeSplitUsername(t *testing.T) {
username := serviceaccount.MakeUsername("ns", "name")
ns, name, err := serviceaccount.SplitUsername(username)
if err != nil {
t.Errorf("Unexpected error %v", err)
}
if ns != "ns" || name != "name" {
t.Errorf("Expected ns/name, got %s/%s", ns, name)
}
invalid := []string{"test", "system:serviceaccount", "system:serviceaccount:", "system:serviceaccount:ns", "system:serviceaccount:ns:name:extra"}
for _, n := range invalid {
_, _, err := serviceaccount.SplitUsername("test")
if err == nil {
t.Errorf("Expected error for %s", n)
}
}
}
| XiaoningDing/UbernetesPOC | pkg/serviceaccount/jwt_test.go | GO | apache-2.0 | 9,089 |
/*
* Minio Client (C) 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/dustin/go-humanize"
"github.com/minio/mc/pkg/client"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio-xl/pkg/probe"
)
/// ls - related internal functions
const (
printDate = "2006-01-02 15:04:05 MST"
)
// ContentMessage container for content message structure.
type ContentMessage struct {
Filetype string `json:"type"`
Time time.Time `json:"lastModified"`
Size int64 `json:"size"`
Name string `json:"name"`
}
// String colorized string message
func (c ContentMessage) String() string {
message := console.Colorize("Time", fmt.Sprintf("[%s] ", c.Time.Format(printDate)))
message = message + console.Colorize("Size", fmt.Sprintf("%6s ", humanize.IBytes(uint64(c.Size))))
message = func() string {
if c.Filetype == "folder" {
return message + console.Colorize("Dir", fmt.Sprintf("%s", c.Name))
}
return message + console.Colorize("File", fmt.Sprintf("%s", c.Name))
}()
return message
}
// JSON jsonified content message
func (c ContentMessage) JSON() string {
jsonMessageBytes, e := json.Marshal(c)
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
}
// parseContent parse client Content container into printer struct.
func parseContent(c *client.Content) ContentMessage {
content := ContentMessage{}
content.Time = c.Time.Local()
// guess file type
content.Filetype = func() string {
if c.Type.IsDir() {
return "folder"
}
return "file"
}()
content.Size = c.Size
// Convert OS Type to match console file printing style.
content.Name = func() string {
switch {
case runtime.GOOS == "windows":
c.Name = strings.Replace(c.Name, "/", "\\", -1)
c.Name = strings.TrimSuffix(c.Name, "\\")
default:
c.Name = strings.TrimSuffix(c.Name, "/")
}
if c.Type.IsDir() {
switch {
case runtime.GOOS == "windows":
return fmt.Sprintf("%s\\", c.Name)
default:
return fmt.Sprintf("%s/", c.Name)
}
}
return c.Name
}()
return content
}
// doList - list all entities inside a folder.
func doList(clnt client.Client, recursive, multipleArgs bool) *probe.Error {
var err *probe.Error
var parentContent *client.Content
urlStr := clnt.URL().String()
parentDir := url2Dir(urlStr)
parentClnt, err := url2Client(parentDir)
if err != nil {
return err.Trace(clnt.URL().String())
}
parentContent, err = parentClnt.Stat()
if err != nil {
return err.Trace(clnt.URL().String())
}
for contentCh := range clnt.List(recursive, false) {
if contentCh.Err != nil {
switch contentCh.Err.ToGoError().(type) {
// handle this specifically for filesystem
case client.BrokenSymlink:
errorIf(contentCh.Err.Trace(), "Unable to list broken link.")
continue
case client.TooManyLevelsSymlink:
errorIf(contentCh.Err.Trace(), "Unable to list too many levels link.")
continue
}
if os.IsNotExist(contentCh.Err.ToGoError()) || os.IsPermission(contentCh.Err.ToGoError()) {
if contentCh.Content != nil {
if contentCh.Content.Type.IsDir() {
if contentCh.Content.Type&os.ModeSymlink == os.ModeSymlink {
errorIf(contentCh.Err.Trace(), "Unable to list broken folder link.")
continue
}
errorIf(contentCh.Err.Trace(), "Unable to list folder.")
}
} else {
errorIf(contentCh.Err.Trace(), "Unable to list.")
continue
}
}
err = contentCh.Err.Trace()
break
}
if multipleArgs && parentContent.Type.IsDir() {
contentCh.Content.Name = filepath.Join(parentContent.Name, strings.TrimPrefix(contentCh.Content.Name, parentContent.Name))
}
Prints("%s\n", parseContent(contentCh.Content))
}
if err != nil {
return err.Trace()
}
return nil
}
// doListIncomplete - list all incomplete uploads entities inside a folder.
func doListIncomplete(clnt client.Client, recursive, multipleArgs bool) *probe.Error {
var err *probe.Error
var parentContent *client.Content
parentContent, err = clnt.Stat()
if err != nil {
return err.Trace(clnt.URL().String())
}
for contentCh := range clnt.List(recursive, true) {
if contentCh.Err != nil {
switch contentCh.Err.ToGoError().(type) {
// handle this specifically for filesystem
case client.BrokenSymlink:
errorIf(contentCh.Err.Trace(), "Unable to list broken link.")
continue
case client.TooManyLevelsSymlink:
errorIf(contentCh.Err.Trace(), "Unable to list too many levels link.")
continue
}
if os.IsNotExist(contentCh.Err.ToGoError()) || os.IsPermission(contentCh.Err.ToGoError()) {
if contentCh.Content != nil {
if contentCh.Content.Type.IsDir() && (contentCh.Content.Type&os.ModeSymlink == os.ModeSymlink) {
errorIf(contentCh.Err.Trace(), "Unable to list broken folder link.")
continue
}
}
errorIf(contentCh.Err.Trace(), "Unable to list.")
continue
}
err = contentCh.Err.Trace()
break
}
if multipleArgs && parentContent.Type.IsDir() {
contentCh.Content.Name = filepath.Join(parentContent.Name, strings.TrimPrefix(contentCh.Content.Name, parentContent.Name))
}
Prints("%s\n", parseContent(contentCh.Content))
}
if err != nil {
return err.Trace()
}
return nil
}
| winchram/mc | ls.go | GO | apache-2.0 | 5,848 |
import angular from 'angular';
import uiRouter from 'angular-ui-router';
import uiModal from 'angular-ui-bootstrap/src/modal';
import forcegraphComponent from './forcegraph.component';
let forcegraphModule = angular.module('forcegraph', [
uiRouter,
uiModal
])
.config(($stateProvider) => {
"ngInject";
$stateProvider
.state('forcegraph', {
url: '/forcegraph',
component: 'forcegraph'
});
})
.component('forcegraph', forcegraphComponent)
.name;
export default forcegraphModule;
| garrettwong/GDashboard | client/app/components/d3visualizations/forcegraph/forcegraph.js | JavaScript | apache-2.0 | 510 |
// 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 by the Codegen C++ plugin.
// If you make any local changes, they will be lost.
// source: google/cloud/iap/v1/service.proto
#include "google/cloud/iap/identity_aware_proxy_o_auth_connection_idempotency_policy.h"
#include "absl/memory/memory.h"
#include <memory>
namespace google {
namespace cloud {
namespace iap {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
using ::google::cloud::Idempotency;
IdentityAwareProxyOAuthServiceConnectionIdempotencyPolicy::
~IdentityAwareProxyOAuthServiceConnectionIdempotencyPolicy() = default;
namespace {
class DefaultIdentityAwareProxyOAuthServiceConnectionIdempotencyPolicy
: public IdentityAwareProxyOAuthServiceConnectionIdempotencyPolicy {
public:
~DefaultIdentityAwareProxyOAuthServiceConnectionIdempotencyPolicy() override =
default;
/// Create a new copy of this object.
std::unique_ptr<IdentityAwareProxyOAuthServiceConnectionIdempotencyPolicy>
clone() const override {
return absl::make_unique<
DefaultIdentityAwareProxyOAuthServiceConnectionIdempotencyPolicy>(
*this);
}
Idempotency ListBrands(
google::cloud::iap::v1::ListBrandsRequest const&) override {
return Idempotency::kIdempotent;
}
Idempotency CreateBrand(
google::cloud::iap::v1::CreateBrandRequest const&) override {
return Idempotency::kNonIdempotent;
}
Idempotency GetBrand(
google::cloud::iap::v1::GetBrandRequest const&) override {
return Idempotency::kIdempotent;
}
Idempotency CreateIdentityAwareProxyClient(
google::cloud::iap::v1::CreateIdentityAwareProxyClientRequest const&)
override {
return Idempotency::kNonIdempotent;
}
Idempotency ListIdentityAwareProxyClients(
google::cloud::iap::v1::ListIdentityAwareProxyClientsRequest) override {
return Idempotency::kIdempotent;
}
Idempotency GetIdentityAwareProxyClient(
google::cloud::iap::v1::GetIdentityAwareProxyClientRequest const&)
override {
return Idempotency::kIdempotent;
}
Idempotency ResetIdentityAwareProxyClientSecret(
google::cloud::iap::v1::ResetIdentityAwareProxyClientSecretRequest const&)
override {
return Idempotency::kNonIdempotent;
}
Idempotency DeleteIdentityAwareProxyClient(
google::cloud::iap::v1::DeleteIdentityAwareProxyClientRequest const&)
override {
return Idempotency::kNonIdempotent;
}
};
} // namespace
std::unique_ptr<IdentityAwareProxyOAuthServiceConnectionIdempotencyPolicy>
MakeDefaultIdentityAwareProxyOAuthServiceConnectionIdempotencyPolicy() {
return absl::make_unique<
DefaultIdentityAwareProxyOAuthServiceConnectionIdempotencyPolicy>();
}
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace iap
} // namespace cloud
} // namespace google
| googleapis/google-cloud-cpp | google/cloud/iap/identity_aware_proxy_o_auth_connection_idempotency_policy.cc | C++ | apache-2.0 | 3,353 |
/*
* 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.referencing.operation;
import java.util.Collections;
import javax.xml.bind.JAXBException;
import org.opengis.util.FactoryException;
import org.opengis.referencing.crs.GeodeticCRS;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.CoordinateOperation;
import org.opengis.referencing.operation.MathTransformFactory;
import org.opengis.referencing.operation.NoninvertibleTransformException;
import org.apache.sis.referencing.operation.transform.EllipsoidToCentricTransform;
import org.apache.sis.referencing.datum.HardCodedDatum;
import org.apache.sis.referencing.crs.HardCodedCRS;
import org.apache.sis.internal.system.DefaultFactories;
import org.apache.sis.io.wkt.Convention;
import org.opengis.test.Validators;
import org.apache.sis.test.DependsOn;
import org.apache.sis.test.XMLTestCase;
import org.junit.Test;
import static org.apache.sis.test.MetadataAssert.*;
import static org.apache.sis.test.TestUtilities.getSingleton;
/**
* Tests the {@link DefaultConcatenatedOperation} class.
*
* @author Martin Desruisseaux (Geomatys)
* @since 0.7
* @version 0.7
* @module
*/
@DependsOn({
DefaultTransformationTest.class,
SingleOperationMarshallingTest.class
})
public final strictfp class DefaultConcatenatedOperationTest extends XMLTestCase {
/**
* An XML file in this package containing a projected CRS definition.
*/
private static final String XML_FILE = "ConcatenatedOperation.xml";
/**
* Creates a “Tokyo to JGD2000” transformation.
*
* @see DefaultTransformationTest#createGeocentricTranslation()
*/
private static DefaultConcatenatedOperation createGeocentricTranslation() throws FactoryException, NoninvertibleTransformException {
final MathTransformFactory mtFactory = DefaultFactories.forBuildin(MathTransformFactory.class);
final DefaultTransformation op = DefaultTransformationTest.createGeocentricTranslation();
final DefaultConversion before = new DefaultConversion(
Collections.singletonMap(DefaultConversion.NAME_KEY, "Geographic to geocentric"),
HardCodedCRS.TOKYO, // SourceCRS
op.getSourceCRS(), // TargetCRS
null, // InterpolationCRS
DefaultOperationMethodTest.create("Geographic/geocentric conversions", "9602", "EPSG guidance note #7-2", 3),
EllipsoidToCentricTransform.createGeodeticConversion(mtFactory, HardCodedDatum.TOKYO.getEllipsoid(), true));
final DefaultConversion after = new DefaultConversion(
Collections.singletonMap(DefaultConversion.NAME_KEY, "Geocentric to geographic"),
op.getTargetCRS(), // SourceCRS
HardCodedCRS.JGD2000, // TargetCRS
null, // InterpolationCRS
DefaultOperationMethodTest.create("Geographic/geocentric conversions", "9602", "EPSG guidance note #7-2", 3),
EllipsoidToCentricTransform.createGeodeticConversion(mtFactory, HardCodedDatum.JGD2000.getEllipsoid(), true).inverse());
return new DefaultConcatenatedOperation(
Collections.singletonMap(DefaultConversion.NAME_KEY, "Tokyo to JGD2000"),
new AbstractSingleOperation[] {before, op, after}, mtFactory);
}
/**
* Tests WKT formatting. The WKT format used here is not defined in OGC/ISO standards;
* this is a SIS-specific extension.
*
* @throws FactoryException if an error occurred while creating the test operation.
* @throws NoninvertibleTransformException if an error occurred while creating the test operation.
*/
@Test
public void testWKT() throws FactoryException, NoninvertibleTransformException {
final DefaultConcatenatedOperation op = createGeocentricTranslation();
assertWktEquals(Convention.WKT2_SIMPLIFIED, // Pseudo-WKT actually.
"ConcatenatedOperation[“Tokyo to JGD2000”,\n" +
" SourceCRS[GeodeticCRS[“Tokyo”,\n" +
" Datum[“Tokyo 1918”,\n" +
" Ellipsoid[“Bessel 1841”, 6377397.155, 299.1528128]],\n" +
" CS[ellipsoidal, 3],\n" +
" Axis[“Longitude (L)”, east, Unit[“degree”, 0.017453292519943295]],\n" +
" Axis[“Latitude (B)”, north, Unit[“degree”, 0.017453292519943295]],\n" +
" Axis[“Ellipsoidal height (h)”, up, Unit[“metre”, 1]]]],\n" +
" TargetCRS[GeodeticCRS[“JGD2000”,\n" +
" Datum[“Japanese Geodetic Datum 2000”,\n" +
" Ellipsoid[“GRS 1980”, 6378137.0, 298.257222101]],\n" +
" CS[ellipsoidal, 3],\n" +
" Axis[“Longitude (L)”, east, Unit[“degree”, 0.017453292519943295]],\n" +
" Axis[“Latitude (B)”, north, Unit[“degree”, 0.017453292519943295]],\n" +
" Axis[“Ellipsoidal height (h)”, up, Unit[“metre”, 1]]]],\n" +
" CoordinateOperationStep[“Geographic to geocentric”,\n" +
" Method[“Geographic/geocentric conversions”],\n" +
" Parameter[“semi_major”, 6377397.155, Unit[“metre”, 1]],\n" +
" Parameter[“semi_minor”, 6356078.962818189, Unit[“metre”, 1]]],\n" +
" CoordinateOperationStep[“Tokyo to JGD2000 (GSI)”,\n" +
" Method[“Geocentric translations”],\n" +
" Parameter[“X-axis translation”, -146.414],\n" +
" Parameter[“Y-axis translation”, 507.337],\n" +
" Parameter[“Z-axis translation”, 680.507]],\n" +
" CoordinateOperationStep[“Geocentric to geographic”,\n" +
" Method[“Geographic/geocentric conversions”],\n" +
" Parameter[“semi_major”, 6378137.0, Unit[“metre”, 1]],\n" +
" Parameter[“semi_minor”, 6356752.314140356, Unit[“metre”, 1]]]]", op);
}
/**
* Tests (un)marshalling of a concatenated operation.
*
* @throws JAXBException if an error occurred during (un)marshalling.
*/
@Test
public void testXML() throws JAXBException {
final DefaultConcatenatedOperation op = unmarshalFile(DefaultConcatenatedOperation.class, XML_FILE);
Validators.validate(op);
assertEquals("operations.size()", 2, op.getOperations().size());
final CoordinateOperation step1 = op.getOperations().get(0);
final CoordinateOperation step2 = op.getOperations().get(1);
final CoordinateReferenceSystem sourceCRS = op.getSourceCRS();
final CoordinateReferenceSystem targetCRS = op.getTargetCRS();
assertIdentifierEquals( "identifier", "test", "test", null, "concatenated", getSingleton(op .getIdentifiers()));
assertIdentifierEquals("sourceCRS.identifier", "test", "test", null, "source", getSingleton(sourceCRS.getIdentifiers()));
assertIdentifierEquals("targetCRS.identifier", "test", "test", null, "target", getSingleton(targetCRS.getIdentifiers()));
assertIdentifierEquals( "step1.identifier", "test", "test", null, "step-1", getSingleton(step1 .getIdentifiers()));
assertIdentifierEquals( "step2.identifier", "test", "test", null, "step-2", getSingleton(step2 .getIdentifiers()));
assertInstanceOf("sourceCRS", GeodeticCRS.class, sourceCRS);
assertInstanceOf("targetCRS", GeodeticCRS.class, targetCRS);
assertSame("sourceCRS", step1.getSourceCRS(), sourceCRS);
assertSame("targetCRS", step2.getTargetCRS(), targetCRS);
assertSame("tmp CRS", step1.getTargetCRS(), step2.getSourceCRS());
/*
* Test marshalling and compare with the original file.
*/
assertMarshalEqualsFile(XML_FILE, op, "xmlns:*", "xsi:schemaLocation");
}
}
| desruisseaux/sis | core/sis-referencing/src/test/java/org/apache/sis/referencing/operation/DefaultConcatenatedOperationTest.java | Java | apache-2.0 | 8,998 |
/*
*
* Copyright 2013 OpenStack 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 hudson.plugins.gearman;
import hudson.model.Hudson;
import hudson.model.Queue;
import hudson.model.Computer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NodeAvailabilityMonitor implements AvailabilityMonitor {
private final Queue queue;
private final Hudson hudson;
private final Computer computer;
private MyGearmanWorkerImpl workerHoldingLock = null;
private String expectedUUID = null;
private static final Logger logger = LoggerFactory
.getLogger(Constants.PLUGIN_LOGGER_NAME);
NodeAvailabilityMonitor(Computer computer)
{
this.computer = computer;
queue = Queue.getInstance();
hudson = Hudson.getInstance();
}
public Computer getComputer() {
return computer;
}
public void lock(MyGearmanWorkerImpl worker)
throws InterruptedException
{
logger.debug("AvailabilityMonitor lock request: " + worker);
while (true) {
boolean busy = false;
// Synchronize on the Jenkins queue so that Jenkins is
// unable to schedule builds while we try to acquire the
// lock.
synchronized(queue) {
if (workerHoldingLock == null) {
if (computer.countIdle() == 0) {
// If there are no idle executors, we can not
// schedule a build.
busy = true;
} else if (hudson.isQuietingDown()) {
busy = true;
} else {
logger.debug("AvailabilityMonitor got lock: " + worker);
workerHoldingLock = worker;
return;
}
} else {
busy = true;
}
}
if (busy) {
synchronized(this) {
// We get synchronous notification when a
// build finishes, but there are lots of other
// reasons circumstances could change (adding
// an executor, canceling shutdown, etc), so
// we slowly busy wait to cover all those
// reasons.
this.wait(5000);
}
}
}
}
public void unlock(MyGearmanWorkerImpl worker) {
logger.debug("AvailabilityMonitor unlock request: " + worker);
synchronized(queue) {
if (workerHoldingLock == worker) {
workerHoldingLock = null;
expectedUUID = null;
logger.debug("AvailabilityMonitor unlocked: " + worker);
} else {
logger.debug("Worker does not own AvailabilityMonitor lock: " +
worker);
}
}
wake();
}
public void wake() {
// Called when we know circumstances may have changed in a way
// that may allow someone to get the lock.
logger.debug("AvailabilityMonitor wake request");
synchronized(this) {
logger.debug("AvailabilityMonitor woken");
notifyAll();
}
}
public void expectUUID(String UUID) {
// The Gearman worker which holds the lock is about to
// schedule this build, so when Jenkins asks to run it, say
// "yes".
if (expectedUUID != null) {
logger.error("AvailabilityMonitor told to expect UUID " +
UUID + "while already expecting " + expectedUUID);
}
expectedUUID = UUID;
}
public boolean canTake(Queue.BuildableItem item)
{
// Jenkins calls this from within the scheduler maintenance
// function (while owning the queue monitor). If we are
// locked, only allow the build we are expecting to run.
logger.debug("AvailabilityMonitor canTake request for " +
workerHoldingLock);
NodeParametersAction param = item.getAction(NodeParametersAction.class);
if (param != null) {
logger.debug("AvailabilityMonitor canTake request for UUID " +
param.getUuid() + " expecting " + expectedUUID);
if (expectedUUID == param.getUuid()) {
return true;
}
}
return (workerHoldingLock == null);
}
} | hudson3-plugins/gearman-plugin | src/main/java/hudson/plugins/gearman/NodeAvailabilityMonitor.java | Java | apache-2.0 | 5,039 |
import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import org.apache.log4j.Logger;
import org.yeastrc.ms.parser.DataProviderException;
import org.yeastrc.ms.parser.ms2File.Ms2FileReader;
import org.yeastrc.ms.util.Sha1SumCalculator;
/**
*
*/
public class MS2FileValidator {
private static final Logger log = Logger.getLogger(MS2FileValidator.class);
public static final int VALIDATION_ERR_SHA1SUM = 1;
public static final int VALIDATION_ERR_READ = 2;
public static final int VALIDATION_ERR_HEADER = 3;
public static final int VALIDATION_ERR_SCAN = 4;
public static final int VALID = 0;
public int validateFile(String filePath) {
log.info("VALIDATING file: "+filePath);
Ms2FileReader dataProvider = new Ms2FileReader();
String sha1sum = getSha1Sum(filePath);
if (sha1sum == null) {
log.error("ERROR calculating sha1sum for file: "+filePath+". EXITING...");
return VALIDATION_ERR_SHA1SUM;
}
// open the file
try {
dataProvider.open(filePath, sha1sum);
}
catch (DataProviderException e) {
log.error("ERROR reading file: "+filePath+". EXITING...", e);
dataProvider.close();
return VALIDATION_ERR_READ;
}
// read the header
try {
dataProvider.getRunHeader();
}
catch (DataProviderException e) {
log.error("ERROR reading file: "+filePath+". EXITING...", e);
dataProvider.close();
return VALIDATION_ERR_HEADER;
}
// read the scans
while (true) {
try {
if(dataProvider.getNextScan() == null)
break;
}
catch (DataProviderException e) {
log.error("ERROR reading file: "+filePath+". EXITING...", e);
dataProvider.close();
return VALIDATION_ERR_SCAN;
}
}
dataProvider.close();
return VALID;
}
private String getSha1Sum(String filePath) {
try {
return Sha1SumCalculator.instance().sha1SumFor(new File(filePath));
}
catch (IOException e) {
log.error(e.getMessage(), e);
return null;
}
catch (NoSuchAlgorithmException e) {
log.error(e.getMessage(), e);
return null;
}
}
}
| yeastrc/msdapl | MS_LIBRARY/src/MS2FileValidator.java | Java | apache-2.0 | 2,486 |
/*
* 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.activemq.artemis.core.config;
import java.io.File;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.apache.activemq.artemis.api.core.BroadcastGroupConfiguration;
import org.apache.activemq.artemis.api.core.DiscoveryGroupConfiguration;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.api.core.TransportConfiguration;
import org.apache.activemq.artemis.core.config.impl.ConfigurationImpl;
import org.apache.activemq.artemis.core.security.Role;
import org.apache.activemq.artemis.core.server.JournalType;
import org.apache.activemq.artemis.core.server.SecuritySettingPlugin;
import org.apache.activemq.artemis.core.server.group.impl.GroupingHandlerConfiguration;
import org.apache.activemq.artemis.core.server.plugin.ActiveMQServerPlugin;
import org.apache.activemq.artemis.core.settings.impl.AddressSettings;
import org.apache.activemq.artemis.core.settings.impl.ResourceLimitSettings;
/**
* A Configuration is used to configure ActiveMQ Artemis servers.
*/
public interface Configuration {
/**
* To be used on dependency management on the application server
*/
String getName();
/**
* To be used on dependency management on the application server
*/
Configuration setName(String name);
/**
* We use Bean-utils to pass in System.properties that start with {@link #setSystemPropertyPrefix(String)}.
* The default should be 'brokerconfig.' (Including the ".").
* For example if you want to set clustered through a system property you must do:
*
* -Dbrokerconfig.clustered=true
*
* The prefix is configured here.
* @param systemPropertyPrefix
* @return
*/
Configuration setSystemPropertyPrefix(String systemPropertyPrefix);
/**
* See doc at {@link #setSystemPropertyPrefix(String)}.
* @return
*/
String getSystemPropertyPrefix();
Configuration parseSystemProperties() throws Exception;
Configuration parseSystemProperties(Properties properties) throws Exception;
/**
* Returns whether this server is clustered. <br>
* {@code true} if {@link #getClusterConfigurations()} is not empty.
*/
boolean isClustered();
/**
* Returns whether delivery count is persisted before messages are delivered to the consumers. <br>
* Default value is
* {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_PERSIST_DELIVERY_COUNT_BEFORE_DELIVERY}
*/
boolean isPersistDeliveryCountBeforeDelivery();
/**
* Sets whether delivery count is persisted before messages are delivered to consumers.
*/
Configuration setPersistDeliveryCountBeforeDelivery(boolean persistDeliveryCountBeforeDelivery);
/**
* Returns whether this server is using persistence and store data. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_PERSISTENCE_ENABLED}.
*/
boolean isPersistenceEnabled();
/**
* Sets whether this server is using persistence and store data.
*/
Configuration setPersistenceEnabled(boolean enable);
/**
* Should use fdatasync on journal files.
*
* @see <a href="http://man7.org/linux/man-pages/man2/fdatasync.2.html">fdatasync</a>
*
* @return a boolean
*/
boolean isJournalDatasync();
/**
* documented at {@link #isJournalDatasync()} ()}
*
* @param enable
* @return this
*/
Configuration setJournalDatasync(boolean enable);
/**
* @return usernames mapped to ResourceLimitSettings
*/
Map<String, ResourceLimitSettings> getResourceLimitSettings();
/**
* @param resourceLimitSettings usernames mapped to ResourceLimitSettings
*/
Configuration setResourceLimitSettings(Map<String, ResourceLimitSettings> resourceLimitSettings);
/**
* @param resourceLimitSettings usernames mapped to ResourceLimitSettings
*/
Configuration addResourceLimitSettings(ResourceLimitSettings resourceLimitSettings);
/**
* Returns the period (in milliseconds) to scan configuration files used by deployment. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_FILE_DEPLOYER_SCAN_PERIOD}.
*/
long getFileDeployerScanPeriod();
/**
* Sets the period to scan configuration files used by deployment.
*/
Configuration setFileDeployerScanPeriod(long period);
/**
* Returns the maximum number of threads in the thread pool of this server. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_THREAD_POOL_MAX_SIZE}.
*/
int getThreadPoolMaxSize();
/**
* Sets the maximum number of threads in the thread pool of this server.
*/
Configuration setThreadPoolMaxSize(int maxSize);
/**
* Returns the maximum number of threads in the <em>scheduled</em> thread pool of this server. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_SCHEDULED_THREAD_POOL_MAX_SIZE}.
*/
int getScheduledThreadPoolMaxSize();
/**
* Sets the maximum number of threads in the <em>scheduled</em> thread pool of this server.
*/
Configuration setScheduledThreadPoolMaxSize(int maxSize);
/**
* Returns the interval time (in milliseconds) to invalidate security credentials. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_SECURITY_INVALIDATION_INTERVAL}.
*/
long getSecurityInvalidationInterval();
/**
* Sets the interval time (in milliseconds) to invalidate security credentials.
*/
Configuration setSecurityInvalidationInterval(long interval);
/**
* Returns whether security is enabled for this server. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_SECURITY_ENABLED}.
*/
boolean isSecurityEnabled();
/**
* Sets whether security is enabled for this server.
*/
Configuration setSecurityEnabled(boolean enabled);
/**
* Returns whether graceful shutdown is enabled for this server. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_SECURITY_ENABLED}.
*/
boolean isGracefulShutdownEnabled();
/**
* Sets whether security is enabled for this server.
*/
Configuration setGracefulShutdownEnabled(boolean enabled);
/**
* Returns the graceful shutdown timeout for this server. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT}.
*/
long getGracefulShutdownTimeout();
/**
* Sets the graceful shutdown timeout
*/
Configuration setGracefulShutdownTimeout(long timeout);
/**
* Returns whether this server is manageable using JMX or not. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_JMX_MANAGEMENT_ENABLED}.
*/
boolean isJMXManagementEnabled();
/**
* Sets whether this server is manageable using JMX or not. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_JMX_MANAGEMENT_ENABLED}.
*/
Configuration setJMXManagementEnabled(boolean enabled);
/**
* Returns the domain used by JMX MBeans (provided JMX management is enabled). <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_JMX_DOMAIN}.
*/
String getJMXDomain();
/**
* Sets the domain used by JMX MBeans (provided JMX management is enabled).
* <p>
* Changing this JMX domain is required if multiple ActiveMQ Artemis servers are run inside
* the same JVM and all servers are using the same MBeanServer.
*/
Configuration setJMXDomain(String domain);
/**
* whether or not to use the broker name in the JMX tree
*/
boolean isJMXUseBrokerName();
/**
* whether or not to use the broker name in the JMX tree
*/
ConfigurationImpl setJMXUseBrokerName(boolean jmxUseBrokerName);
/**
* Returns the list of interceptors classes used by this server for incoming messages (i.e. those being delivered to
* the server from clients).
*/
List<String> getIncomingInterceptorClassNames();
/**
* Returns the list of interceptors classes used by this server for outgoing messages (i.e. those being delivered to
* clients from the server).
*/
List<String> getOutgoingInterceptorClassNames();
/**
* Sets the list of interceptors classes used by this server for incoming messages (i.e. those being delivered to
* the server from clients).
* <br>
* Classes must implement {@link org.apache.activemq.artemis.api.core.Interceptor}.
*/
Configuration setIncomingInterceptorClassNames(List<String> interceptors);
/**
* Sets the list of interceptors classes used by this server for outgoing messages (i.e. those being delivered to
* clients from the server).
* <br>
* Classes must implement {@link org.apache.activemq.artemis.api.core.Interceptor}.
*/
Configuration setOutgoingInterceptorClassNames(List<String> interceptors);
/**
* Returns the connection time to live. <br>
* This value overrides the connection time to live <em>sent by the client</em>. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_CONNECTION_TTL_OVERRIDE}.
*/
long getConnectionTTLOverride();
/**
* Sets the connection time to live.
*/
Configuration setConnectionTTLOverride(long ttl);
/**
* Returns whether code coming from connection is executed asynchronously or not. <br>
* Default value is
* {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_ASYNC_CONNECTION_EXECUTION_ENABLED}.
*/
boolean isAsyncConnectionExecutionEnabled();
/**
* Sets whether code coming from connection is executed asynchronously or not.
*/
Configuration setEnabledAsyncConnectionExecution(boolean enabled);
/**
* Returns the acceptors configured for this server.
*/
Set<TransportConfiguration> getAcceptorConfigurations();
/**
* Sets the acceptors configured for this server.
*/
Configuration setAcceptorConfigurations(Set<TransportConfiguration> infos);
Configuration addAcceptorConfiguration(TransportConfiguration infos);
/**
* Add an acceptor to the config
*
* @param name the name of the acceptor
* @param uri the URI of the acceptor
* @return this
* @throws Exception in case of Parsing errors on the URI
*/
Configuration addAcceptorConfiguration(String name, String uri) throws Exception;
Configuration clearAcceptorConfigurations();
/**
* Returns the connectors configured for this server.
*/
Map<String, TransportConfiguration> getConnectorConfigurations();
/**
* Sets the connectors configured for this server.
*/
Configuration setConnectorConfigurations(Map<String, TransportConfiguration> infos);
Configuration addConnectorConfiguration(String key, TransportConfiguration info);
Configuration addConnectorConfiguration(String name, String uri) throws Exception;
Configuration clearConnectorConfigurations();
/**
* Returns the broadcast groups configured for this server.
*/
List<BroadcastGroupConfiguration> getBroadcastGroupConfigurations();
/**
* Sets the broadcast groups configured for this server.
*/
Configuration setBroadcastGroupConfigurations(List<BroadcastGroupConfiguration> configs);
Configuration addBroadcastGroupConfiguration(BroadcastGroupConfiguration config);
/**
* Returns the discovery groups configured for this server.
*/
Map<String, DiscoveryGroupConfiguration> getDiscoveryGroupConfigurations();
/**
* Sets the discovery groups configured for this server.
*/
Configuration setDiscoveryGroupConfigurations(Map<String, DiscoveryGroupConfiguration> configs);
Configuration addDiscoveryGroupConfiguration(String key,
DiscoveryGroupConfiguration discoveryGroupConfiguration);
/**
* Returns the grouping handler configured for this server.
*/
GroupingHandlerConfiguration getGroupingHandlerConfiguration();
/**
* Sets the grouping handler configured for this server.
*/
Configuration setGroupingHandlerConfiguration(GroupingHandlerConfiguration groupingHandlerConfiguration);
/**
* Returns the bridges configured for this server.
*/
List<BridgeConfiguration> getBridgeConfigurations();
/**
* Sets the bridges configured for this server.
*/
Configuration setBridgeConfigurations(List<BridgeConfiguration> configs);
/**
* Returns the diverts configured for this server.
*/
List<DivertConfiguration> getDivertConfigurations();
/**
* Sets the diverts configured for this server.
*/
Configuration setDivertConfigurations(List<DivertConfiguration> configs);
Configuration addDivertConfiguration(DivertConfiguration config);
/**
* Returns the cluster connections configured for this server.
* <p>
* Modifying the returned list will modify the list of {@link ClusterConnectionConfiguration}
* used by this configuration.
*/
List<ClusterConnectionConfiguration> getClusterConfigurations();
/**
* Sets the cluster connections configured for this server.
*/
Configuration setClusterConfigurations(List<ClusterConnectionConfiguration> configs);
Configuration addClusterConfiguration(ClusterConnectionConfiguration config);
ClusterConnectionConfiguration addClusterConfiguration(String name, String uri) throws Exception;
Configuration clearClusterConfigurations();
/**
* Returns the queues configured for this server.
*/
List<CoreQueueConfiguration> getQueueConfigurations();
/**
* Sets the queues configured for this server.
*/
Configuration setQueueConfigurations(List<CoreQueueConfiguration> configs);
Configuration addQueueConfiguration(CoreQueueConfiguration config);
/**
* Returns the addresses configured for this server.
*/
List<CoreAddressConfiguration> getAddressConfigurations();
/**
* Sets the addresses configured for this server.
*/
Configuration setAddressConfigurations(List<CoreAddressConfiguration> configs);
/**
* Adds an addresses configuration
*/
Configuration addAddressConfiguration(CoreAddressConfiguration config);
/**
* Returns the management address of this server. <br>
* Clients can send management messages to this address to manage this server. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_MANAGEMENT_ADDRESS}.
*/
SimpleString getManagementAddress();
/**
* Sets the management address of this server.
*/
Configuration setManagementAddress(SimpleString address);
/**
* Returns the management notification address of this server. <br>
* Clients can bind queues to this address to receive management notifications emitted by this
* server. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_MANAGEMENT_NOTIFICATION_ADDRESS}.
*/
SimpleString getManagementNotificationAddress();
/**
* Sets the management notification address of this server.
*/
Configuration setManagementNotificationAddress(SimpleString address);
/**
* Returns the cluster user for this server. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_CLUSTER_USER}.
*/
String getClusterUser();
/**
* Sets the cluster user for this server.
*/
Configuration setClusterUser(String user);
/**
* Returns the cluster password for this server. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_CLUSTER_PASSWORD}.
*/
String getClusterPassword();
/**
* Sets the cluster password for this server.
*/
Configuration setClusterPassword(String password);
/**
* Returns the size of the cache for pre-creating message IDs. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_ID_CACHE_SIZE}.
*/
int getIDCacheSize();
/**
* Sets the size of the cache for pre-creating message IDs.
*/
Configuration setIDCacheSize(int idCacheSize);
/**
* Returns whether message ID cache is persisted. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_PERSIST_ID_CACHE}.
*/
boolean isPersistIDCache();
/**
* Sets whether message ID cache is persisted.
*/
Configuration setPersistIDCache(boolean persist);
// Journal related attributes ------------------------------------------------------------
/**
* Returns the file system directory used to store bindings. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_BINDINGS_DIRECTORY}.
*/
String getBindingsDirectory();
/**
* The binding location related to artemis.instance.
*/
File getBindingsLocation();
/**
* Sets the file system directory used to store bindings.
*/
Configuration setBindingsDirectory(String dir);
/**
* The max number of concurrent reads allowed on paging.
* <p>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_MAX_CONCURRENT_PAGE_IO}.
*/
int getPageMaxConcurrentIO();
/**
* The max number of concurrent reads allowed on paging.
* <p>
* Default = 5
*/
Configuration setPageMaxConcurrentIO(int maxIO);
/**
* Returns the file system directory used to store journal log. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_JOURNAL_DIR}.
*/
String getJournalDirectory();
/**
* The location of the journal related to artemis.instance.
*
* @return
*/
File getJournalLocation();
/**
* Sets the file system directory used to store journal log.
*/
Configuration setJournalDirectory(String dir);
/**
* Returns the type of journal used by this server ({@code NIO}, {@code ASYNCIO} or {@code MAPPED}).
* <br>
* Default value is ASYNCIO.
*/
JournalType getJournalType();
/**
* Sets the type of journal used by this server (either {@code NIO} or {@code ASYNCIO}).
*/
Configuration setJournalType(JournalType type);
/**
* Returns whether the journal is synchronized when receiving transactional data. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_JOURNAL_SYNC_TRANSACTIONAL}.
*/
boolean isJournalSyncTransactional();
/**
* Sets whether the journal is synchronized when receiving transactional data.
*/
Configuration setJournalSyncTransactional(boolean sync);
/**
* Returns whether the journal is synchronized when receiving non-transactional data. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_JOURNAL_SYNC_NON_TRANSACTIONAL}.
*/
boolean isJournalSyncNonTransactional();
/**
* Sets whether the journal is synchronized when receiving non-transactional data.
*/
Configuration setJournalSyncNonTransactional(boolean sync);
/**
* Returns the size (in bytes) of each journal files. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_JOURNAL_FILE_SIZE}.
*/
int getJournalFileSize();
/**
* Sets the size (in bytes) of each journal files.
*/
Configuration setJournalFileSize(int size);
/**
* Returns the minimal number of journal files before compacting. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_JOURNAL_COMPACT_MIN_FILES}.
*/
int getJournalCompactMinFiles();
/**
* Sets the minimal number of journal files before compacting.
*/
Configuration setJournalCompactMinFiles(int minFiles);
/**
* Number of files that would be acceptable to keep on a pool. Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_JOURNAL_POOL_FILES}.
*/
int getJournalPoolFiles();
/**
* Number of files that would be acceptable to keep on a pool. Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_JOURNAL_POOL_FILES}.
*/
Configuration setJournalPoolFiles(int poolSize);
/**
* Returns the percentage of live data before compacting the journal. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_JOURNAL_COMPACT_PERCENTAGE}.
*/
int getJournalCompactPercentage();
/**
* Sets the percentage of live data before compacting the journal.
*/
Configuration setJournalCompactPercentage(int percentage);
/**
* Returns the number of journal files to pre-create. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_JOURNAL_MIN_FILES}.
*/
int getJournalMinFiles();
/**
* Sets the number of journal files to pre-create.
*/
Configuration setJournalMinFiles(int files);
// AIO and NIO need different values for these params
/**
* Returns the maximum number of write requests that can be in the AIO queue at any given time. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_JOURNAL_MAX_IO_AIO}.
*/
int getJournalMaxIO_AIO();
/**
* Sets the maximum number of write requests that can be in the AIO queue at any given time.
*/
Configuration setJournalMaxIO_AIO(int journalMaxIO);
/**
* Returns the timeout (in nanoseconds) used to flush buffers in the AIO queue.
* <br>
* Default value is {@link org.apache.activemq.artemis.ArtemisConstants#DEFAULT_JOURNAL_BUFFER_TIMEOUT_AIO}.
*/
int getJournalBufferTimeout_AIO();
/**
* Sets the timeout (in nanoseconds) used to flush buffers in the AIO queue.
*/
Configuration setJournalBufferTimeout_AIO(int journalBufferTimeout);
/**
* Returns the buffer size (in bytes) for AIO.
* <br>
* Default value is {@link org.apache.activemq.artemis.ArtemisConstants#DEFAULT_JOURNAL_BUFFER_SIZE_AIO}.
*/
int getJournalBufferSize_AIO();
/**
* Sets the buffer size (in bytes) for AIO.
*/
Configuration setJournalBufferSize_AIO(int journalBufferSize);
/**
* Returns the maximum number of write requests for NIO journal. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_JOURNAL_MAX_IO_NIO}.
*/
int getJournalMaxIO_NIO();
/**
* Sets the maximum number of write requests for NIO journal.
*/
Configuration setJournalMaxIO_NIO(int journalMaxIO);
/**
* Returns the timeout (in nanoseconds) used to flush buffers in the NIO.
* <br>
* Default value is {@link org.apache.activemq.artemis.ArtemisConstants#DEFAULT_JOURNAL_BUFFER_TIMEOUT_NIO}.
*/
int getJournalBufferTimeout_NIO();
/**
* Sets the timeout (in nanoseconds) used to flush buffers in the NIO.
*/
Configuration setJournalBufferTimeout_NIO(int journalBufferTimeout);
/**
* Returns the buffer size (in bytes) for NIO.
* <br>
* Default value is {@link org.apache.activemq.artemis.ArtemisConstants#DEFAULT_JOURNAL_BUFFER_SIZE_NIO}.
*/
int getJournalBufferSize_NIO();
/**
* Sets the buffer size (in bytes) for NIO.
*/
Configuration setJournalBufferSize_NIO(int journalBufferSize);
/**
* Returns whether the bindings directory is created on this server startup. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_CREATE_BINDINGS_DIR}.
*/
boolean isCreateBindingsDir();
/**
* Sets whether the bindings directory is created on this server startup.
*/
Configuration setCreateBindingsDir(boolean create);
/**
* Returns whether the journal directory is created on this server startup. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_CREATE_JOURNAL_DIR}.
*/
boolean isCreateJournalDir();
/**
* Sets whether the journal directory is created on this server startup.
*/
Configuration setCreateJournalDir(boolean create);
// Undocumented attributes
boolean isLogJournalWriteRate();
Configuration setLogJournalWriteRate(boolean rate);
long getServerDumpInterval();
Configuration setServerDumpInterval(long interval);
int getMemoryWarningThreshold();
Configuration setMemoryWarningThreshold(int memoryWarningThreshold);
long getMemoryMeasureInterval();
Configuration setMemoryMeasureInterval(long memoryMeasureInterval);
// Paging Properties --------------------------------------------------------------------
/**
* Returns the file system directory used to store paging files. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_PAGING_DIR}.
*/
String getPagingDirectory();
/**
* Sets the file system directory used to store paging files.
*/
Configuration setPagingDirectory(String dir);
/**
* The paging location related to artemis.instance
*/
File getPagingLocation();
// Large Messages Properties ------------------------------------------------------------
/**
* Returns the file system directory used to store large messages. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_LARGE_MESSAGES_DIR}.
*/
String getLargeMessagesDirectory();
/**
* The large message location related to artemis.instance
*/
File getLargeMessagesLocation();
/**
* Sets the file system directory used to store large messages.
*/
Configuration setLargeMessagesDirectory(String directory);
// Other Properties ---------------------------------------------------------------------
/**
* Returns whether wildcard routing is supported by this server. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_WILDCARD_ROUTING_ENABLED}.
*/
boolean isWildcardRoutingEnabled();
/**
* Sets whether wildcard routing is supported by this server.
*/
Configuration setWildcardRoutingEnabled(boolean enabled);
WildcardConfiguration getWildcardConfiguration();
Configuration setWildCardConfiguration(WildcardConfiguration wildcardConfiguration);
/**
* Returns the timeout (in milliseconds) after which transactions is removed from the resource
* manager after it was created. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_TRANSACTION_TIMEOUT}.
*/
long getTransactionTimeout();
/**
* Sets the timeout (in milliseconds) after which transactions is removed
* from the resource manager after it was created.
*/
Configuration setTransactionTimeout(long timeout);
/**
* Returns whether message counter is enabled for this server. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_MESSAGE_COUNTER_ENABLED}.
*/
boolean isMessageCounterEnabled();
/**
* Sets whether message counter is enabled for this server.
*/
Configuration setMessageCounterEnabled(boolean enabled);
/**
* Returns the sample period (in milliseconds) to take message counter snapshot. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_MESSAGE_COUNTER_SAMPLE_PERIOD}.
*/
long getMessageCounterSamplePeriod();
/**
* Sets the sample period to take message counter snapshot.
*
* @param period value must be greater than 1000ms
*/
Configuration setMessageCounterSamplePeriod(long period);
/**
* Returns the maximum number of days kept in memory for message counter. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_MESSAGE_COUNTER_MAX_DAY_HISTORY}.
*/
int getMessageCounterMaxDayHistory();
/**
* Sets the maximum number of days kept in memory for message counter.
*
* @param maxDayHistory value must be greater than 0
*/
Configuration setMessageCounterMaxDayHistory(int maxDayHistory);
/**
* Returns the frequency (in milliseconds) to scan transactions to detect which transactions have
* timed out. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_TRANSACTION_TIMEOUT_SCAN_PERIOD}.
*/
long getTransactionTimeoutScanPeriod();
/**
* Sets the frequency (in milliseconds) to scan transactions to detect which transactions
* have timed out.
*/
Configuration setTransactionTimeoutScanPeriod(long period);
/**
* Returns the frequency (in milliseconds) to scan messages to detect which messages have
* expired. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_MESSAGE_EXPIRY_SCAN_PERIOD}.
*/
long getMessageExpiryScanPeriod();
/**
* Sets the frequency (in milliseconds) to scan messages to detect which messages
* have expired.
*/
Configuration setMessageExpiryScanPeriod(long messageExpiryScanPeriod);
/**
* Returns the priority of the thread used to scan message expiration. <br>
* Default value is {@link org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_MESSAGE_EXPIRY_THREAD_PRIORITY}.
*/
int getMessageExpiryThreadPriority();
/**
* Sets the priority of the thread used to scan message expiration.
*/
Configuration setMessageExpiryThreadPriority(int messageExpiryThreadPriority);
/**
* @return A list of AddressSettings per matching to be deployed to the address settings repository
*/
Map<String, AddressSettings> getAddressesSettings();
/**
* @param addressesSettings list of AddressSettings per matching to be deployed to the address
* settings repository
*/
Configuration setAddressesSettings(Map<String, AddressSettings> addressesSettings);
Configuration addAddressesSetting(String key, AddressSettings addressesSetting);
Configuration clearAddressesSettings();
/**
* @param roles a list of roles per matching
*/
Configuration setSecurityRoles(Map<String, Set<Role>> roles);
/**
* @return a list of roles per matching
*/
Map<String, Set<Role>> getSecurityRoles();
Configuration addSecurityRoleNameMapping(String internalRole, Set<String> externalRoles);
Map<String, Set<String>> getSecurityRoleNameMappings();
Configuration putSecurityRoles(String match, Set<Role> roles);
Configuration setConnectorServiceConfigurations(List<ConnectorServiceConfiguration> configs);
Configuration addConnectorServiceConfiguration(ConnectorServiceConfiguration config);
Configuration setSecuritySettingPlugins(List<SecuritySettingPlugin> plugins);
Configuration addSecuritySettingPlugin(SecuritySettingPlugin plugin);
/**
* @return list of {@link ConnectorServiceConfiguration}
*/
List<ConnectorServiceConfiguration> getConnectorServiceConfigurations();
List<SecuritySettingPlugin> getSecuritySettingPlugins();
/**
* The default password decoder
*/
Configuration setPasswordCodec(String codec);
/**
* Gets the default password decoder
*/
String getPasswordCodec();
/**
* Sets if passwords should be masked or not. True means the passwords should be masked.
*/
Configuration setMaskPassword(boolean maskPassword);
/**
* If passwords are masked. True means the passwords are masked.
*/
boolean isMaskPassword();
/*
* Whether or not that ActiveMQ Artemis should use all protocols available on the classpath. If false only the core protocol will
* be set, any other protocols will need to be set directly on the ActiveMQServer
* */
Configuration setResolveProtocols(boolean resolveProtocols);
TransportConfiguration[] getTransportConfigurations(String... connectorNames);
TransportConfiguration[] getTransportConfigurations(List<String> connectorNames);
/*
* @see #setResolveProtocols()
* @return whether ActiveMQ Artemis should resolve and use any Protocols available on the classpath
* Default value is {@link org.apache.activemq.artemis.api.config.org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration#DEFAULT_RESOLVE_PROTOCOLS}.
* */
boolean isResolveProtocols();
Configuration copy() throws Exception;
Configuration setJournalLockAcquisitionTimeout(long journalLockAcquisitionTimeout);
long getJournalLockAcquisitionTimeout();
HAPolicyConfiguration getHAPolicyConfiguration();
Configuration setHAPolicyConfiguration(HAPolicyConfiguration haPolicyConfiguration);
/**
* Set the Artemis instance relative folder for data and stuff.
*/
void setBrokerInstance(File directory);
/**
* Set the Artemis instance relative folder for data and stuff.
*/
File getBrokerInstance();
StoreConfiguration getStoreConfiguration();
Configuration setStoreConfiguration(StoreConfiguration storeConfiguration);
boolean isPopulateValidatedUser();
Configuration setPopulateValidatedUser(boolean populateValidatedUser);
/**
* It will return all the connectors in a toString manner for debug purposes.
*/
String debugConnectors();
Configuration setConnectionTtlCheckInterval(long connectionTtlCheckInterval);
long getConnectionTtlCheckInterval();
URL getConfigurationUrl();
Configuration setConfigurationUrl(URL configurationUrl);
long getConfigurationFileRefreshPeriod();
Configuration setConfigurationFileRefreshPeriod(long configurationFileRefreshPeriod);
long getGlobalMaxSize();
Configuration setGlobalMaxSize(long globalMaxSize);
int getMaxDiskUsage();
Configuration setMaxDiskUsage(int maxDiskUsage);
ConfigurationImpl setInternalNamingPrefix(String internalNamingPrefix);
Configuration setDiskScanPeriod(int diskScanPeriod);
int getDiskScanPeriod();
/** A comma separated list of IPs we could use to validate if the network is UP.
* In case of none of these Ips are reached (if configured) the server will be shutdown. */
Configuration setNetworkCheckList(String list);
String getNetworkCheckList();
/** A comma separated list of URIs we could use to validate if the network is UP.
* In case of none of these Ips are reached (if configured) the server will be shutdown.
* The difference from networkCheckList is that we will use HTTP to make this validation. */
Configuration setNetworkCheckURLList(String uris);
String getNetworkCheckURLList();
/** The interval on which we will perform network checks. */
Configuration setNetworkCheckPeriod(long period);
long getNetworkCheckPeriod();
/** Time in ms for how long we should wait for a ping to finish. */
Configuration setNetworkCheckTimeout(int timeout);
int getNetworkCheckTimeout();
/** The NIC name to be used on network checks */
Configuration setNetworCheckNIC(String nic);
String getNetworkCheckNIC();
String getNetworkCheckPingCommand();
Configuration setNetworkCheckPingCommand(String command);
String getNetworkCheckPing6Command();
Configuration setNetworkCheckPing6Command(String command);
String getInternalNamingPrefix();
/**
* @param plugins
*/
void registerBrokerPlugins(List<ActiveMQServerPlugin> plugins);
/**
* @param plugin
*/
void registerBrokerPlugin(ActiveMQServerPlugin plugin);
/**
* @param plugin
*/
void unRegisterBrokerPlugin(ActiveMQServerPlugin plugin);
/**
* @return
*/
List<ActiveMQServerPlugin> getBrokerPlugins();
}
| bennetelli/activemq-artemis | artemis-server/src/main/java/org/apache/activemq/artemis/core/config/Configuration.java | Java | apache-2.0 | 37,644 |
package loadBalance;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.zip.Inflater;
/**
* Created by Administrator on 2017/1/17.
*/
public class IpMap {
public static Map<String, Integer> serverMap = new HashMap<String, Integer>();
static {
serverMap.put("192.168.1.1", 1);
serverMap.put("192.168.1.2", 2);
serverMap.put("192.168.1.3", 3);
}
public static Map<String, Integer> copy() {
return new HashMap<String, Integer>(serverMap);
}
}
| yekevin/JavaPractise | src/loadBalance/IpMap.java | Java | apache-2.0 | 563 |
<?php
// Contact
$to = 'jasonekstromdev@gmail.com';
$subject = 'Job Opportunity';
if(isset($_POST['c_name']) && isset($_POST['c_email']) && isset($_POST['c_message'])){
$name = $_POST['c_name'];
$from = $_POST['c_email'];
$message = $_POST['c_message'];
if (mail($to, $subject, $message, $from)) {
$result = array(
'message' => 'Thanks for contacting me!',
'sendstatus' => 1
);
echo json_encode($result);
} else {
$result = array(
'message' => 'Sorry, something is wrong',
'sendstatus' => 1
);
echo json_encode($result);
}
}
?> | jmekstrom/Portfolio | assets/php/contactForm.php | PHP | apache-2.0 | 628 |
#
# Author:: Shawn Neal <sneal@daptiv.com>
# Cookbook Name:: visualstudio
# Recipe:: install
#
# Copyright 2013, Daptiv Solutions, LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
::Chef::Recipe.send(:include, Visualstudio::Helper)
vs_is_installed = is_vs_installed?()
# Ensure the installation ISO url has been set by the user
if !node['visualstudio']['source']
raise 'visualstudio source attribute must be set before running this cookbook'
end
version = 'vs' + node['visualstudio']['version']
edition = node['visualstudio']['edition']
install_url = File.join(node['visualstudio']['source'], node['visualstudio'][edition]['filename'])
install_log_file = win_friendly_path(
File.join(node['visualstudio']['install_dir'], 'vsinstall.log'))
iso_extraction_dir = win_friendly_path(File.join(Chef::Config[:file_cache_path], version))
setup_exe_path = File.join(iso_extraction_dir, node['visualstudio'][edition]['installer_file'])
admin_deployment_xml_file = win_friendly_path(File.join(iso_extraction_dir, 'AdminDeployment.xml'))
# Extract the ISO image to the tmp dir
seven_zip_archive 'extract_vs_iso' do
path iso_extraction_dir
source install_url
overwrite true
checksum node['visualstudio'][edition]['checksum']
not_if { vs_is_installed }
end
# Create installation config file
cookbook_file admin_deployment_xml_file do
source version + '/AdminDeployment-' + edition + '.xml'
action :create
not_if { vs_is_installed }
end
# Install Visual Studio
windows_package node['visualstudio'][edition]['package_name'] do
source setup_exe_path
installer_type :custom
options "/Q /norestart /Log \"#{install_log_file}\" /AdminFile \"#{admin_deployment_xml_file}\""
notifies :delete, "directory[#{iso_extraction_dir}]"
timeout 3600 # 1hour
not_if { vs_is_installed }
end
# Cleanup extracted ISO files from tmp dir
directory iso_extraction_dir do
action :nothing
recursive true
not_if { node['visualstudio']['preserve_extracted_files'] }
end
| dthagard/opschef-cookbook-visualstudio | recipes/install.rb | Ruby | apache-2.0 | 2,479 |
/**
* class for student
*/
'use strict'
const util = require('util')
const Person = require('./person');
function Student() {
Person.call(this);
}
// student继承自person
util.inherits(Student, Person);
Student.prototype.study = function() {
console.log('i am learning...');
};
module.exports = Student; | EvanDylan/node | base/mods/inhertis/student.js | JavaScript | apache-2.0 | 318 |
package module
import (
"net"
"sync"
)
type TCP_server struct {
Port uint16
NewAgent func(*TCPConn) Agent
ln net.Listener
mutexConns sync.Mutex
}
func (server *TCP_server) Start() {
}
| swordhell/go_server | src/td.com/module/module.go | GO | apache-2.0 | 210 |
import * as Preact from '#preact';
import {boolean, number, select, withKnobs} from '@storybook/addon-knobs';
import {withAmp} from '@ampproject/storybook-addon';
export default {
title: 'amp-twitter-1_0',
decorators: [withKnobs, withAmp],
parameters: {
extensions: [
{
name: 'amp-twitter',
version: '1.0',
},
{
name: 'amp-bind',
version: '0.1',
},
],
experiments: ['bento'],
},
};
export const Default = () => {
const tweetId = select(
'tweet id',
['1356304203044499462', '495719809695621121', '463440424141459456'],
'1356304203044499462'
);
const cards = boolean('show cards', true) ? undefined : 'hidden';
const conversation = boolean('show conversation', false) ? undefined : 'none';
return (
<amp-twitter
width="300"
height="200"
data-tweetid={tweetId}
data-cards={cards}
data-conversation={conversation}
/>
);
};
export const Moments = () => {
const limit = number('limit to', 2);
return (
<amp-twitter
data-limit={limit}
data-momentid="1009149991452135424"
width="300"
height="200"
/>
);
};
export const Timelines = () => {
const tweetLimit = number('limit to', 5);
const timelineSourceType = select(
'source type',
['profile', 'likes', 'list', 'source', 'collection', 'url', 'widget'],
'profile'
);
const timelineScreenName = 'amphtml';
const timelineUserId = '3450662892';
return (
<amp-twitter
data-tweet-limit={tweetLimit}
data-timeline-source-type={timelineSourceType}
data-timeline-scree-name={timelineScreenName}
data-timeline-user-id={timelineUserId}
width="300"
height="200"
/>
);
};
export const DeletedTweet = () => {
const withFallback = boolean('include fallback?', true);
return (
<amp-twitter
width="390"
height="330"
layout="fixed"
data-tweetid="882818033403789316"
data-cards="hidden"
>
<blockquote placeholder>
<p lang="en" dir="ltr">
In case you missed it last week, check out our recap of AMP in 2020
⚡🙌
</p>
<p>
Watch here ➡️
<br />
<a href="https://t.co/eaxT3MuSAK">https://t.co/eaxT3MuSAK</a>
</p>
</blockquote>
{withFallback && (
<div fallback>
An error occurred while retrieving the tweet. It might have been
deleted.
</div>
)}
</amp-twitter>
);
};
export const InvalidTweet = () => {
return (
<amp-twitter
width="390"
height="330"
layout="fixed"
data-tweetid="1111111111111641653602164060160"
data-cards="hidden"
>
<blockquote placeholder class="twitter-tweet" data-lang="en">
<p>
This placeholder should never change because given tweet-id is
invalid.
</p>
</blockquote>
</amp-twitter>
);
};
export const MutatedTweetId = () => {
return (
<>
<button on="tap:AMP.setState({tweetid: '495719809695621121'})">
Change tweet
</button>
<amp-state id="tweetid">
<script type="application/json">1356304203044499462</script>
</amp-state>
<amp-twitter
width="375"
height="472"
layout="responsive"
data-tweetid="1356304203044499462"
data-amp-bind-data-tweetid="tweetid"
></amp-twitter>
</>
);
};
| jpettitt/amphtml | extensions/amp-twitter/1.0/storybook/Basic.amp.js | JavaScript | apache-2.0 | 3,469 |
// This is a generated file. Not intended for manual editing.
package com.github.joshholl.intellij.csharp.lang.psi.impl;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import static com.github.joshholl.intellij.csharp.lang.lexer.CSharpTokenTypes.*;
import com.intellij.extapi.psi.ASTWrapperPsiElement;
import com.github.joshholl.intellij.csharp.lang.psi.*;
public class CSharpImplicitAnonymousFunctionParameterListImpl extends ASTWrapperPsiElement implements CSharpImplicitAnonymousFunctionParameterList {
public CSharpImplicitAnonymousFunctionParameterListImpl(ASTNode node) {
super(node);
}
public void accept(@NotNull PsiElementVisitor visitor) {
if (visitor instanceof CSharpVisitor) ((CSharpVisitor)visitor).visitImplicitAnonymousFunctionParameterList(this);
else super.accept(visitor);
}
@Override
@NotNull
public List<CSharpImplicitAnonymousFunctionParameter> getImplicitAnonymousFunctionParameterList() {
return PsiTreeUtil.getChildrenOfTypeAsList(this, CSharpImplicitAnonymousFunctionParameter.class);
}
}
| joshholl/intellij-csharp | gen/com/github/joshholl/intellij/csharp/lang/psi/impl/CSharpImplicitAnonymousFunctionParameterListImpl.java | Java | apache-2.0 | 1,220 |
using System;
using ruibarbo.core.Search;
using ruibarbo.core.Wpf.Base;
namespace ruibarbo.core.Wpf.Helpers
{
public static class ComboBoxExtensions
{
public static void OpenAndClickFirst<TItem>(this IComboBox me)
where TItem : class, IComboBoxItem
{
OpenAndClickFirst<TItem>(me, By.Empty);
}
public static void OpenAndClickFirst<TItem>(this IComboBox me, params Func<IByBuilder<TItem>, By>[] byBuilders)
where TItem : class, IComboBoxItem
{
OpenAndClickFirst<TItem>(me, byBuilders.Build());
}
public static void OpenAndClickFirst<TItem>(this IComboBox me, params By[] bys)
where TItem : class, IComboBoxItem
{
var item = me.FindFirstItem<TItem>(bys);
item.OpenAndClick();
}
}
} | toroso/ruibarbo | ruibarbo.core/Wpf/Helpers/ComboBoxExtensions.cs | C# | apache-2.0 | 879 |
/*
* Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.am.integration.tests.api.lifecycle;
import org.json.JSONException;
import org.json.JSONObject;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.am.integration.clients.publisher.api.ApiException;
import org.wso2.am.integration.clients.publisher.api.v1.dto.APIDTO;
import org.wso2.am.integration.clients.publisher.api.v1.dto.APIOperationsDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.APIKeyDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationKeyDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationKeyGenerateRequestDTO;
import org.wso2.am.integration.test.utils.APIManagerIntegrationTestException;
import org.wso2.am.integration.test.utils.base.APIMIntegrationConstants;
import org.wso2.am.integration.test.utils.bean.APILifeCycleAction;
import org.wso2.am.integration.test.utils.bean.APIRequest;
import org.wso2.carbon.automation.engine.annotations.ExecutionEnvironment;
import org.wso2.carbon.automation.engine.annotations.SetEnvironment;
import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil;
import org.wso2.carbon.automation.test.utils.http.client.HttpResponse;
import org.wso2.carbon.integration.common.utils.exceptions.AutomationUtilException;
import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager;
import javax.xml.xpath.XPathExpressionException;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
/**
* This class tests the behaviour of API when there is choice of selection between oauth2 and mutual ssl in API Manager.
*/
@SetEnvironment(executionEnvironments = {ExecutionEnvironment.STANDALONE})
public class APISecurityTestCase extends APIManagerLifecycleBaseTest {
private final String API_NAME = "mutualsslAPI";
private final String API_NAME_2 = "mutualsslAPI2";
private final String API_CONTEXT = "mutualsslAPI";
private final String API_CONTEXT_2 = "mutualsslAPI2";
private final String API_END_POINT_METHOD = "/customers/123";
private final String API_VERSION_1_0_0 = "1.0.0";
private final String APPLICATION_NAME = "AccessibilityOfDeprecatedOldAPIAndPublishedCopyAPITestCase";
private String accessToken;
private final String API_END_POINT_POSTFIX_URL = "jaxrs_basic/services/customers/customerservice/";
private String apiEndPointUrl;
private String applicationId;
private String apiId1, apiId2;
@BeforeClass(alwaysRun = true)
public void initialize()
throws APIManagerIntegrationTestException, IOException, ApiException, org.wso2.am.integration.clients.store.api.ApiException, XPathExpressionException, AutomationUtilException {
super.init();
apiEndPointUrl = backEndServerUrl.getWebAppURLHttp() + API_END_POINT_POSTFIX_URL;
APIRequest apiRequest1 = new APIRequest(API_NAME, API_CONTEXT, new URL(apiEndPointUrl));
apiRequest1.setVersion(API_VERSION_1_0_0);
apiRequest1.setTiersCollection(APIMIntegrationConstants.API_TIER.UNLIMITED);
apiRequest1.setTier(APIMIntegrationConstants.API_TIER.UNLIMITED);
apiRequest1.setTags(API_TAGS);
apiRequest1.setVisibility(APIDTO.VisibilityEnum.PUBLIC.getValue());
APIOperationsDTO apiOperationsDTO1 = new APIOperationsDTO();
apiOperationsDTO1.setVerb("GET");
apiOperationsDTO1.setTarget("/customers/{id}");
apiOperationsDTO1.setAuthType("Application & Application User");
apiOperationsDTO1.setThrottlingPolicy("Unlimited");
List<APIOperationsDTO> operationsDTOS = new ArrayList<>();
operationsDTOS.add(apiOperationsDTO1);
apiRequest1.setOperationsDTOS(operationsDTOS);
List<String> securitySchemes = new ArrayList<>();
securitySchemes.add("mutualssl");
apiRequest1.setSecurityScheme(securitySchemes);
HttpResponse response1 = restAPIPublisher.addAPI(apiRequest1);
apiId1 = response1.getData();
String certOne = getAMResourceLocation() + File.separator + "lifecycletest" + File.separator + "mutualssl"
+ File.separator + "example.crt";
restAPIPublisher.uploadCertificate(new File(certOne), "example", apiId1, APIMIntegrationConstants.API_TIER.UNLIMITED);
APIRequest apiRequest2 = new APIRequest(API_NAME_2, API_CONTEXT_2, new URL(apiEndPointUrl));
apiRequest2.setVersion(API_VERSION_1_0_0);
apiRequest2.setTiersCollection(APIMIntegrationConstants.API_TIER.UNLIMITED);
apiRequest2.setTier(APIMIntegrationConstants.API_TIER.UNLIMITED);
apiRequest2.setTags(API_TAGS);
apiRequest2.setVisibility(APIDTO.VisibilityEnum.PUBLIC.getValue());
apiRequest2.setOperationsDTOS(operationsDTOS);
List<String> securitySchemes2 = new ArrayList<>();
securitySchemes2.add("mutualssl");
securitySchemes2.add("oauth2");
securitySchemes2.add("api_key");
apiRequest2.setSecurityScheme(securitySchemes2);
HttpResponse response2 = restAPIPublisher.addAPI(apiRequest2);
apiId2 = response2.getData();
String certTwo = getAMResourceLocation() + File.separator + "lifecycletest" + File.separator + "mutualssl"
+ File.separator + "abcde.crt";
restAPIPublisher.uploadCertificate(new File(certTwo), "abcde", apiId2, APIMIntegrationConstants.API_TIER.UNLIMITED);
restAPIPublisher.changeAPILifeCycleStatus(apiId1, APILifeCycleAction.PUBLISH.getAction());
restAPIPublisher.changeAPILifeCycleStatus(apiId2, APILifeCycleAction.PUBLISH.getAction());
HttpResponse applicationResponse = restAPIStore.createApplication(APPLICATION_NAME,
"Test Application", APIMIntegrationConstants.APPLICATION_TIER.UNLIMITED,
ApplicationDTO.TokenTypeEnum.JWT);
applicationId = applicationResponse.getData();
restAPIStore.subscribeToAPI(apiId2, applicationId, APIMIntegrationConstants.APPLICATION_TIER.UNLIMITED);
ArrayList grantTypes = new ArrayList();
grantTypes.add(APIMIntegrationConstants.GRANT_TYPE.PASSWORD);
grantTypes.add(APIMIntegrationConstants.GRANT_TYPE.CLIENT_CREDENTIAL);
ApplicationKeyDTO applicationKeyDTO = restAPIStore.generateKeys(applicationId, "36000", "",
ApplicationKeyGenerateRequestDTO.KeyTypeEnum.PRODUCTION, null, grantTypes);
//get access token
accessToken = applicationKeyDTO.getToken().getAccessToken();
}
@Test(description = "This test case tests the behaviour of APIs that are protected with mutual SSL and OAuth2 "
+ "when the client certificate is not presented but OAuth2 token is presented.")
public void testCreateAndPublishAPIWithOAuth2() throws XPathExpressionException, IOException, JSONException {
// Create requestHeaders
Map<String, String> requestHeaders = new HashMap<>();
requestHeaders.put("accept", "application/json");
requestHeaders.put("Authorization", "Bearer " + accessToken);
HttpResponse apiResponse = HttpRequestUtil
.doGet(getAPIInvocationURLHttp(API_CONTEXT, API_VERSION_1_0_0) + API_END_POINT_METHOD, requestHeaders);
JSONObject response = new JSONObject(apiResponse.getData());
//fix test failure due to error code changes introduced in product-apim pull #7106
assertEquals(response.getJSONObject("fault").getInt("code"), 900901,
"API invocation succeeded with the access token without need for mutual ssl");
apiResponse = HttpRequestUtil
.doGet(getAPIInvocationURLHttp(API_CONTEXT_2, API_VERSION_1_0_0) + API_END_POINT_METHOD,
requestHeaders);
assertEquals(apiResponse.getResponseCode(), HTTP_RESPONSE_CODE_OK,
"API invocation failed for a test case with valid access token when the API is protected with "
+ "both mutual sso and oauth2");
}
@Test(description = "Testing the invocation with API Keys", dependsOnMethods = {"testCreateAndPublishAPIWithOAuth2"})
public void testInvocationWithApiKeys() throws Exception {
APIKeyDTO apiKeyDTO = restAPIStore
.generateAPIKeys(applicationId, ApplicationKeyGenerateRequestDTO.KeyTypeEnum.PRODUCTION.toString(), -1);
assertNotNull(apiKeyDTO, "API Key generation failed");
Map<String, String> requestHeaders = new HashMap<>();
requestHeaders.put("accept", "application/json");
requestHeaders.put("apikey", apiKeyDTO.getApikey());
HttpResponse apiResponse = HttpRequestUtil
.doGet(getAPIInvocationURLHttp(API_CONTEXT_2, API_VERSION_1_0_0) + API_END_POINT_METHOD,
requestHeaders);
assertEquals(apiResponse.getResponseCode(), HTTP_RESPONSE_CODE_OK,
"API invocation failed for a test case with valid api key when the API is protected with "
+ "API Keys");
}
// @Test(description = "This method tests the behaviour of APIs that are protected with mutual SSL and when the "
// + "authentication is done using mutual SSL", dependsOnMethods = "testCreateAndPublishAPIWithOAuth2")
// public void testAPIInvocationWithMutualSSL()
// throws IOException, XPathExpressionException, InterruptedException,
// NoSuchAlgorithmException, KeyStoreException, KeyManagementException, UnrecoverableKeyException {
// String expectedResponseData = "<id>123</id><name>John</name></Customer>";
// // We need to wait till the relevant listener reloads.
// Thread.sleep(60000);
// Map<String, String> requestHeaders = new HashMap<>();
// requestHeaders.put("accept", "text/xml");
// // Check with the correct client certificate for an API that is only protected with mutual ssl.
// HttpResponse response = HTTPSClientUtils.doMutulSSLGet(
// getAMResourceLocation() + File.separator + "lifecycletest" + File.separator + "mutualssl"
// + File.separator + "new-keystore.jks",
// getAPIInvocationURLHttps(API_CONTEXT, API_VERSION_1_0_0) + API_END_POINT_METHOD, requestHeaders);
// Assert.assertEquals(response.getResponseCode(), HttpStatus.SC_OK,
// "Mutual SSL Authentication has not succeeded");
// Assert.assertTrue(response.getData().contains(expectedResponseData), "Expected payload did not match");
// /* Check with the wrong client certificate for an API that is protected with mutual ssl and oauth2, without
// an access token.*/
// response = HTTPSClientUtils.doMutulSSLGet(
// getAMResourceLocation() + File.separator + "lifecycletest" + File.separator + "mutualssl"
// + File.separator + "new-keystore.jks",
// getAPIInvocationURLHttps(API_CONTEXT_2, API_VERSION_1_0_0) + API_END_POINT_METHOD, requestHeaders);
// Assert.assertEquals(response.getResponseCode(), HttpStatus.SC_UNAUTHORIZED,
// "Mutual SSL Authentication has succeeded for a different certificate");
// /* Check with the correct client certificate for an API that is protected with mutual ssl and oauth2, without
// an access token.*/
// response = HTTPSClientUtils.doMutulSSLGet(
// getAMResourceLocation() + File.separator + "lifecycletest" + File.separator + "mutualssl"
// + File.separator + "test.jks",
// getAPIInvocationURLHttps(API_CONTEXT_2, API_VERSION_1_0_0) + API_END_POINT_METHOD, requestHeaders);
// Assert.assertEquals(response.getResponseCode(), HttpStatus.SC_OK,
// "Mutual SSL Authentication has not succeeded");
// Assert.assertTrue(response.getData().contains(expectedResponseData), "Expected payload did not match");
//
// /* Check with the wrong client certificate for an API that is protected with mutual ssl and oauth2, with a
// correct access token.*/
// requestHeaders.put("Authorization", "Bearer " + accessToken);
// response = HTTPSClientUtils.doMutulSSLGet(
// getAMResourceLocation() + File.separator + "lifecycletest" + File.separator + "mutualssl"
// + File.separator + "new-keystore.jks",
// getAPIInvocationURLHttps(API_CONTEXT_2, API_VERSION_1_0_0) + API_END_POINT_METHOD, requestHeaders);
// Assert.assertEquals(response.getResponseCode(), HttpStatus.SC_OK,
// "OAuth2 authentication was not checked in the event of mutual SSL failure");
// Assert.assertTrue(response.getData().contains(expectedResponseData), "Expected payload did not match");
// }
@AfterClass(alwaysRun = true)
public void cleanUpArtifacts() throws IOException, AutomationUtilException, ApiException {
restAPIStore.deleteApplication(applicationId);
restAPIPublisher.deleteAPI(apiId1);
restAPIPublisher.deleteAPI(apiId2);
}
}
| jaadds/product-apim | modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/api/lifecycle/APISecurityTestCase.java | Java | apache-2.0 | 14,024 |
using System;
using System.Net;
namespace Exceptionless.Api.Controllers {
public class PermissionResult {
public bool Allowed { get; set; }
public string Id { get; set; }
public string Message { get; set; }
public HttpStatusCode StatusCode { get; set; }
public static PermissionResult Allow = new PermissionResult { Allowed = true, StatusCode = HttpStatusCode.OK };
public static PermissionResult Deny = new PermissionResult { Allowed = false, StatusCode = HttpStatusCode.BadRequest };
public static PermissionResult DenyWithNotFound(string id = null) {
return new PermissionResult {
Allowed = false,
Id = id,
StatusCode = HttpStatusCode.NotFound
};
}
public static PermissionResult DenyWithMessage(string message, string id = null) {
return new PermissionResult {
Allowed = false,
Id = id,
Message = message,
StatusCode = HttpStatusCode.BadRequest
};
}
public static PermissionResult DenyWithStatus(HttpStatusCode statusCode, string message = null, string id = null) {
return new PermissionResult {
Allowed = false,
Id = id,
Message = message,
StatusCode = statusCode
};
}
public static PermissionResult DenyWithPlanLimitReached(string message, string id = null) {
return new PermissionResult {
Allowed = false,
Id = id,
Message = message,
StatusCode = HttpStatusCode.UpgradeRequired
};
}
}
} | adamzolotarev/Exceptionless | Source/Api/Controllers/Base/PermissionResult.cs | C# | apache-2.0 | 1,762 |
package org.apache.luke.client;
/**
* 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.
*/
import java.io.File;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.apache.lucene.analysis.core.WhitespaceAnalyzer;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexCommit;
import org.apache.lucene.index.IndexDeletionPolicy;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.MultiReader;
import org.apache.lucene.index.SegmentInfos;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockFactory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;
import org.apache.luke.client.data.FieldsDummyData;
import org.getopt.luke.KeepAllIndexDeletionPolicy;
import org.getopt.luke.KeepLastIndexDeletionPolicy;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.GWT.UncaughtExceptionHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.ColumnSortEvent.AsyncHandler;
import com.google.gwt.user.cellview.client.ColumnSortList;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CaptionPanel;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.SplitLayoutPanel;
import com.google.gwt.user.client.ui.StackPanel;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.view.client.AsyncDataProvider;
import com.google.gwt.view.client.HasData;
import com.google.gwt.view.client.Range;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class LukeInspector implements EntryPoint {
public static Version LV = Version.LUCENE_46;
private final static String solrIndexDir = "D:\\Projects\\information_retrieval\\solr\\solr-4.6.0\\solr-4.6.0\\example\\solr\\collection1\\data\\index";
private String pName = null;
private Directory dir = null;
private IndexReader ir = null;
private IndexSearcher is = null;
public void onModuleLoad() {
final RootPanel rootPanel = RootPanel.get();
CaptionPanel cptnpnlNewPanel = new CaptionPanel("New panel");
cptnpnlNewPanel.setCaptionHTML("Luke version 5.0");
rootPanel.add(cptnpnlNewPanel, 10, 10);
cptnpnlNewPanel.setSize("959px", "652px");
TabPanel tabPanel = new TabPanel();
cptnpnlNewPanel.setContentWidget(tabPanel);
tabPanel.setSize("5cm", "636px");
//LuceneIndexLoader.loadIndex(pName, this);
SplitLayoutPanel splitLayoutPanel = new SplitLayoutPanel();
tabPanel.add(splitLayoutPanel, "Index overview", false);
tabPanel.setVisible(true);
splitLayoutPanel.setSize("652px", "590px");
SplitLayoutPanel splitLayoutPanel_1 = new SplitLayoutPanel();
splitLayoutPanel.addNorth(splitLayoutPanel_1, 288.0);
Label lblIndexStatistics = new Label("Index statistics");
lblIndexStatistics.setDirectionEstimator(true);
lblIndexStatistics.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
splitLayoutPanel_1.addNorth(lblIndexStatistics, 26.0);
VerticalPanel verticalPanel = new VerticalPanel();
splitLayoutPanel_1.addWest(verticalPanel, 125.0);
Label lblTest = new Label("Index name:");
verticalPanel.add(lblTest);
lblTest.setWidth("109px");
Label lblTest_1 = new Label("# fields:");
verticalPanel.add(lblTest_1);
Label lblNumber = new Label("# documents:");
verticalPanel.add(lblNumber);
lblNumber.setWidth("101px");
Label lblTerms = new Label("# terms:");
verticalPanel.add(lblTerms);
Label lblHasDeletions = new Label("Has deletions?");
verticalPanel.add(lblHasDeletions);
Label lblNewLabel = new Label("Optimised?");
verticalPanel.add(lblNewLabel);
Label lblIndexVersion = new Label("Index version:");
verticalPanel.add(lblIndexVersion);
SplitLayoutPanel splitLayoutPanel_2 = new SplitLayoutPanel();
splitLayoutPanel.addWest(splitLayoutPanel_2, 240.0);
// Create name column.
TextColumn<Field> nameColumn = new TextColumn<Field>() {
@Override
public String getValue(Field field) {
return field.getName();
}
};
// Make the name column sortable.
nameColumn.setSortable(true);
// Create termCount column.
TextColumn<Field> termCountColumn = new TextColumn<Field>() {
@Override
public String getValue(Field contact) {
return contact.getTermCount();
}
};
// Create decoder column.
TextColumn<Field> decoderColumn = new TextColumn<Field>() {
@Override
public String getValue(Field contact) {
return contact.getDecoder();
}
};
final CellTable<Field> cellTable = new CellTable<Field>();
cellTable.addColumn(nameColumn, "Name");
cellTable.addColumn(termCountColumn, "Term count");
cellTable.addColumn(decoderColumn, "Decoder");
cellTable.setRowCount(FieldsDummyData.Fields.size(), true);
// Set the range to display. In this case, our visible range is smaller than
// the data set.
cellTable.setVisibleRange(0, 3);
// Create a data provider.
AsyncDataProvider<Field> dataProvider = new AsyncDataProvider<Field>() {
@Override
protected void onRangeChanged(HasData<Field> display) {
final Range range = display.getVisibleRange();
// Get the ColumnSortInfo from the table.
final ColumnSortList sortList = cellTable.getColumnSortList();
// This timer is here to illustrate the asynchronous nature of this data
// provider. In practice, you would use an asynchronous RPC call to
// request data in the specified range.
new Timer() {
@Override
public void run() {
int start = range.getStart();
int end = start + range.getLength();
// This sorting code is here so the example works. In practice, you
// would sort on the server.
Collections.sort(FieldsDummyData.Fields, new Comparator<Field>() {
public int compare(Field o1, Field o2) {
if (o1 == o2) {
return 0;
}
// Compare the name columns.
int diff = -1;
if (o1 != null) {
diff = (o2 != null) ? o1.getName().compareTo(o2.getName()) : 1;
}
return sortList.get(0).isAscending() ? diff : -diff;
}
});
List<Field> dataInRange = FieldsDummyData.Fields.subList(start, end);
// Push the data back into the list.
cellTable.setRowData(start, dataInRange);
}
}.schedule(2000);
}
};
// Connect the list to the data provider.
dataProvider.addDataDisplay(cellTable);
// Add a ColumnSortEvent.AsyncHandler to connect sorting to the
// AsyncDataPRrovider.
AsyncHandler columnSortHandler = new AsyncHandler(cellTable);
cellTable.addColumnSortHandler(columnSortHandler);
// We know that the data is sorted alphabetically by default.
cellTable.getColumnSortList().push(nameColumn);
splitLayoutPanel_2.add(cellTable);
SplitLayoutPanel splitLayoutPanel_3 = new SplitLayoutPanel();
splitLayoutPanel.addEast(splitLayoutPanel_3, 215.0);
StackPanel stackPanel = new StackPanel();
rootPanel.add(stackPanel, 714, 184);
stackPanel.setSize("259px", "239px");
FlowPanel flowPanel = new FlowPanel();
stackPanel.add(flowPanel, "Open index", false);
flowPanel.setSize("100%", "100%");
TextBox textBox = new TextBox();
flowPanel.add(textBox);
Button btnNewButton = new Button("...");
btnNewButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
DirectoryLister directoryLister = new DirectoryLister();
directoryLister.setPopupPosition(rootPanel.getAbsoluteLeft() + rootPanel.getOffsetWidth() / 2,
rootPanel.getAbsoluteTop() + rootPanel.getOffsetHeight() / 2);
directoryLister.show();
}
});
flowPanel.add(btnNewButton);
// exception handling
// credits: http://code.google.com/p/mgwt/source/browse/src/main/java/com/googlecode/mgwt/examples/showcase/client/ShowCaseEntryPoint.java?repo=showcase
GWT.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void onUncaughtException(Throwable e) {
Window.alert("uncaught: " + e.getMessage());
String s = buildStackTrace(e, "RuntimeExceotion:\n");
Window.alert(s);
e.printStackTrace();
}
});
}
// showing the stacktrace
// credits: http://code.google.com/p/mgwt/source/browse/src/main/java/com/googlecode/mgwt/examples/showcase/client/ShowCaseEntryPoint.java?repo=showcase
final String buildStackTrace(Throwable t, String log) {
// return "disabled";
if (t != null) {
log += t.getClass().toString();
log += t.getMessage();
//
StackTraceElement[] stackTrace = t.getStackTrace();
if (stackTrace != null) {
StringBuffer trace = new StringBuffer();
for (int i = 0; i < stackTrace.length; i++) {
trace.append(stackTrace[i].getClassName() + "." + stackTrace[i].getMethodName() + "("
+ stackTrace[i].getFileName() + ":" + stackTrace[i].getLineNumber());
}
log += trace.toString();
}
//
Throwable cause = t.getCause();
if (cause != null && cause != t) {
log += buildStackTrace(cause, "CausedBy:\n");
}
}
return log;
}
public Directory openDirectory(String dirImpl, String file, boolean create) throws Exception {
File f = new File(file);
if (!f.exists()) {
throw new Exception("Index directory doesn't exist.");
}
Directory res = null;
if (dirImpl == null || dirImpl.equals(Directory.class.getName()) || dirImpl.equals(FSDirectory.class.getName())) {
return FSDirectory.open(f);
}
try {
Class implClass = Class.forName(dirImpl);
Constructor<Directory> constr = implClass.getConstructor(File.class);
if (constr != null) {
res = constr.newInstance(f);
} else {
constr = implClass.getConstructor(File.class, LockFactory.class);
res = constr.newInstance(f, (LockFactory)null);
}
} catch (Throwable e) {
//errorMsg("Invalid directory implementation class: " + dirImpl + " " + e);
return null;
}
if (res != null) return res;
// fall-back to FSDirectory.
if (res == null) return FSDirectory.open(f);
return null;
}
/**
* open Lucene index and re-init all the sub-widgets
* @param name
* @param force
* @param dirImpl
* @param ro
* @param ramdir
* @param keepCommits
* @param point
* @param tiiDivisor
*/
public void openIndex(String name, boolean force, String dirImpl, boolean ro,
boolean ramdir, boolean keepCommits, IndexCommit point, int tiiDivisor) {
pName = name;
File baseFileDir = new File(name);
ArrayList<Directory> dirs = new ArrayList<Directory>();
Throwable lastException = null;
try {
Directory d = openDirectory(dirImpl, pName, false);
if (IndexWriter.isLocked(d)) {
if (!ro) {
if (force) {
IndexWriter.unlock(d);
} else {
//errorMsg("Index is locked. Try 'Force unlock' when opening.");
d.close();
d = null;
return;
}
}
}
boolean existsSingle = false;
// IR.indexExists doesn't report the cause of error
try {
new SegmentInfos().read(d);
existsSingle = true;
} catch (Throwable e) {
e.printStackTrace();
lastException = e;
//
}
if (!existsSingle) { // try multi
File[] files = baseFileDir.listFiles();
for (File f : files) {
if (f.isFile()) {
continue;
}
Directory d1 = openDirectory(dirImpl, f.toString(), false);
if (IndexWriter.isLocked(d1)) {
if (!ro) {
if (force) {
IndexWriter.unlock(d1);
} else {
//errorMsg("Index is locked. Try 'Force unlock' when opening.");
d1.close();
d1 = null;
return;
}
}
}
existsSingle = false;
try {
new SegmentInfos().read(d1);
existsSingle = true;
} catch (Throwable e) {
lastException = e;
e.printStackTrace();
}
if (!existsSingle) {
d1.close();
continue;
}
dirs.add(d1);
}
} else {
dirs.add(d);
}
if (dirs.size() == 0) {
if (lastException != null) {
//errorMsg("Invalid directory at the location, check console for more information. Last exception:\n" + lastException.toString());
} else {
//errorMsg("No valid directory at the location, try another location.\nCheck console for other possible causes.");
}
return;
}
if (ramdir) {
//showStatus("Loading index into RAMDirectory ...");
Directory dir1 = new RAMDirectory();
IndexWriterConfig cfg = new IndexWriterConfig(LV, new WhitespaceAnalyzer(LV));
IndexWriter iw1 = new IndexWriter(dir1, cfg);
iw1.addIndexes((Directory[])dirs.toArray(new Directory[dirs.size()]));
iw1.close();
//showStatus("RAMDirectory loading done!");
if (dir != null) dir.close();
dirs.clear();
dirs.add(dir1);
}
IndexDeletionPolicy policy;
if (keepCommits) {
policy = new KeepAllIndexDeletionPolicy();
} else {
policy = new KeepLastIndexDeletionPolicy();
}
ArrayList<DirectoryReader> readers = new ArrayList<DirectoryReader>();
for (Directory dd : dirs) {
DirectoryReader reader;
if (tiiDivisor > 1) {
reader = DirectoryReader.open(dd, tiiDivisor);
} else {
reader = DirectoryReader.open(dd);
}
readers.add(reader);
}
if (readers.size() == 1) {
ir = readers.get(0);
dir = ((DirectoryReader)ir).directory();
} else {
ir = new MultiReader((IndexReader[])readers.toArray(new IndexReader[readers.size()]));
}
is = new IndexSearcher(ir);
// XXX
//slowAccess = false;
//initOverview();
//initPlugins();
//showStatus("Index successfully open.");
} catch (Exception e) {
e.printStackTrace();
//errorMsg(e.getMessage());
return;
}
}
}
| DmitryKey/luke-gwt | src/main/java/org/apache/luke/client/LukeInspector.java | Java | apache-2.0 | 17,271 |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.buck.util.network;
import static org.hamcrest.MatcherAssert.assertThat;
import com.facebook.buck.util.types.Unit;
import com.google.common.collect.ImmutableCollection;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.ArrayList;
import java.util.List;
import org.hamcrest.Matchers;
import org.junit.Test;
public class AbstractBatchingLoggerTest {
private static class TestBatchingLogger extends AbstractBatchingLogger {
private final List<ImmutableCollection<BatchEntry>> uploadedBatches = new ArrayList<>();
public TestBatchingLogger(int minBatchSize) {
super(minBatchSize);
}
public List<ImmutableCollection<AbstractBatchingLogger.BatchEntry>> getUploadedBatches() {
return uploadedBatches;
}
@Override
protected ListenableFuture<Unit> logMultiple(
ImmutableCollection<AbstractBatchingLogger.BatchEntry> data) {
uploadedBatches.add(data);
return Futures.immediateFuture(Unit.UNIT);
}
}
@Test
public void testBatchingLogger() {
String shortData = "data";
String longData = "datdatdatdatdatdatdataaaaaaadata";
AbstractBatchingLogger.BatchEntry shortDataBatch =
new AbstractBatchingLogger.BatchEntry(shortData);
AbstractBatchingLogger.BatchEntry longDataBatch =
new AbstractBatchingLogger.BatchEntry(longData);
TestBatchingLogger testBatchingLogger = new TestBatchingLogger(longData.length() + 1);
testBatchingLogger.log(longData);
// Data should still be buffered at this point.
assertThat(testBatchingLogger.getUploadedBatches(), Matchers.hasSize(0));
// This one should tip it over.
testBatchingLogger.log(shortData);
assertThat(testBatchingLogger.getUploadedBatches(), Matchers.hasSize(1));
testBatchingLogger.log(shortData);
testBatchingLogger.log(shortData);
assertThat(testBatchingLogger.getUploadedBatches(), Matchers.hasSize(1));
testBatchingLogger.forceFlush();
assertThat(testBatchingLogger.getUploadedBatches(), Matchers.hasSize(2));
assertThat(
testBatchingLogger.getUploadedBatches(),
Matchers.contains(
Matchers.contains(longDataBatch, shortDataBatch),
Matchers.contains(shortDataBatch, shortDataBatch)));
}
}
| JoelMarcey/buck | test/com/facebook/buck/util/network/AbstractBatchingLoggerTest.java | Java | apache-2.0 | 2,949 |
angular.module('app').factory('Entity', function ($resource) {
var __apiBase__ = 'http://localhost:8080/GenericBackend/';
return {
Model : $resource(__apiBase__ + 'api/models/fqns'),
User : $resource(__apiBase__ + 'api/users/:id', {id: '@id', profileId :'@profileId'},{
getPermissions : {method : 'GET', url : __apiBase__ + 'api/userProfileRules/:profileId/allowedPermissions', isArray : true},
changePassword : {method : 'POST', url : __apiBase__ + 'api/users/:id/changePassword', isArray : false},
resetPassword : {method : 'POST', url : __apiBase__ + 'api/users/:id/resetPassword', isArray : false},
activate : {method : 'POST', url : __apiBase__ + 'api/users/:id/activate', isArray : false},
deactivate : {method : 'POST', url : __apiBase__ + 'api/users/:id/deactivate', isArray : false}
}),
Authentication : $resource(__apiBase__ + 'api/authentication/:id', {id: '@id', newStatus:'@newStatus'},{
login : {method : 'POST', url : __apiBase__ + 'api/authentication/login'},
logout : {method : 'POST', url : __apiBase__ + 'api/authentication/logout'},
getLoggedInUser : {method : 'GET', url : __apiBase__ + 'api/authentication/loggedinUser'}
}),
Role : $resource(__apiBase__ + 'api/roles/:id', {id: '@id'}),
Profile : $resource(__apiBase__ + 'api/profiles/:id', {id: '@id'}),
UserProfileRule : $resource(__apiBase__ + 'api/userProfileRules/:id', {id: '@id', newStatus:'@newStatus'},{
togglePermission : {method : 'POST', url : __apiBase__ + 'api/userProfileRules/:id/toggleStatus'}
}),
SchemeAccess : $resource(__apiBase__ + 'api/schemeAccess/:id', {id: '@id'}, {
toggleAccess : {method : 'POST', url : __apiBase__ + 'api/schemeAccess/:id/toggleAccess'},
switchOrganization : {method : 'POST', url : __apiBase__ + 'api/schemeAccess/:id/switchScheme'},
}),
UserOrganization : $resource(__apiBase__ + 'api/userOrganizations/:id', {id: '@id'}),
Permission : $resource(__apiBase__ + 'api/permissions/:id', {id: '@id'}, {
createPermissions : {method : 'POST', url : 'api/permissions/createPermissions'}
}),
UserPermission : $resource(__apiBase__ + 'api/user_permissions/:userId', {id: '@userId'}),
SQLExecutor : $resource(__apiBase__ + 'api/sqlExecutor/:id', {id: '@id'},{
execute : {method : 'POST', url : __apiBase__ + 'api/sqlExecutor/execute', isArray: true}
})
}
}
); | kodero/generic-angular-frontend | app/common/services/EntityFactory.js | JavaScript | apache-2.0 | 2,708 |
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "subprocess.h"
#include <stdio.h>
#include <algorithm>
#include "util.h"
namespace {
void Win32Fatal(const char* function) {
Fatal("%s: %s", function, GetLastErrorString().c_str());
}
} // anonymous namespace
Subprocess::Subprocess() : child_(NULL) , overlapped_() {
}
Subprocess::~Subprocess() {
// Reap child if forgotten.
if (child_)
Finish();
}
HANDLE Subprocess::SetupPipe(HANDLE ioport) {
char pipe_name[100];
snprintf(pipe_name, sizeof(pipe_name),
"\\\\.\\pipe\\ninja_pid%u_sp%p", GetCurrentProcessId(), this);
pipe_ = ::CreateNamedPipeA(pipe_name,
PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED,
PIPE_TYPE_BYTE,
PIPE_UNLIMITED_INSTANCES,
0, 0, INFINITE, NULL);
if (pipe_ == INVALID_HANDLE_VALUE)
Win32Fatal("CreateNamedPipe");
if (!CreateIoCompletionPort(pipe_, ioport, (ULONG_PTR)this, 0))
Win32Fatal("CreateIoCompletionPort");
memset(&overlapped_, 0, sizeof(overlapped_));
if (!ConnectNamedPipe(pipe_, &overlapped_) &&
GetLastError() != ERROR_IO_PENDING) {
Win32Fatal("ConnectNamedPipe");
}
// Get the write end of the pipe as a handle inheritable across processes.
HANDLE output_write_handle = CreateFile(pipe_name, GENERIC_WRITE, 0,
NULL, OPEN_EXISTING, 0, NULL);
HANDLE output_write_child;
if (!DuplicateHandle(GetCurrentProcess(), output_write_handle,
GetCurrentProcess(), &output_write_child,
0, TRUE, DUPLICATE_SAME_ACCESS)) {
Win32Fatal("DuplicateHandle");
}
CloseHandle(output_write_handle);
return output_write_child;
}
bool Subprocess::Start(SubprocessSet* set, const string& command) {
HANDLE child_pipe = SetupPipe(set->ioport_);
STARTUPINFOA startup_info;
memset(&startup_info, 0, sizeof(startup_info));
startup_info.cb = sizeof(STARTUPINFO);
startup_info.dwFlags = STARTF_USESTDHANDLES;
startup_info.hStdOutput = child_pipe;
// TODO: what does this hook up stdin to?
startup_info.hStdInput = NULL;
// TODO: is it ok to reuse pipe like this?
startup_info.hStdError = child_pipe;
PROCESS_INFORMATION process_info;
memset(&process_info, 0, sizeof(process_info));
// Do not prepend 'cmd /c' on Windows, this breaks command
// lines greater than 8,191 chars.
if (!CreateProcessA(NULL, (char*)command.c_str(), NULL, NULL,
/* inherit handles */ TRUE, 0,
NULL, NULL,
&startup_info, &process_info)) {
Win32Fatal("CreateProcess");
}
// Close pipe channel only used by the child.
if (child_pipe)
CloseHandle(child_pipe);
CloseHandle(process_info.hThread);
child_ = process_info.hProcess;
return true;
}
void Subprocess::OnPipeReady() {
DWORD bytes;
if (!GetOverlappedResult(pipe_, &overlapped_, &bytes, TRUE)) {
if (GetLastError() == ERROR_BROKEN_PIPE) {
CloseHandle(pipe_);
pipe_ = NULL;
return;
}
Win32Fatal("GetOverlappedResult");
}
if (bytes)
buf_.append(overlapped_buf_, bytes);
memset(&overlapped_, 0, sizeof(overlapped_));
if (!::ReadFile(pipe_, overlapped_buf_, sizeof(overlapped_buf_),
&bytes, &overlapped_)) {
if (GetLastError() == ERROR_BROKEN_PIPE) {
CloseHandle(pipe_);
pipe_ = NULL;
return;
}
if (GetLastError() != ERROR_IO_PENDING)
Win32Fatal("ReadFile");
}
// Even if we read any bytes in the readfile call, we'll enter this
// function again later and get them at that point.
}
bool Subprocess::Finish() {
// TODO: add error handling for all of these.
WaitForSingleObject(child_, INFINITE);
DWORD exit_code = 0;
GetExitCodeProcess(child_, &exit_code);
CloseHandle(child_);
child_ = NULL;
return exit_code == 0;
}
bool Subprocess::Done() const {
return pipe_ == NULL;
}
const string& Subprocess::GetOutput() const {
return buf_;
}
SubprocessSet::SubprocessSet() {
ioport_ = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
if (!ioport_)
Win32Fatal("CreateIoCompletionPort");
}
SubprocessSet::~SubprocessSet() {
CloseHandle(ioport_);
}
void SubprocessSet::Add(Subprocess* subprocess) {
running_.push_back(subprocess);
}
void SubprocessSet::DoWork() {
DWORD bytes_read;
Subprocess* subproc;
OVERLAPPED* overlapped;
if (!GetQueuedCompletionStatus(ioport_, &bytes_read, (PULONG_PTR)&subproc,
&overlapped, INFINITE)) {
if (GetLastError() != ERROR_BROKEN_PIPE)
Win32Fatal("GetQueuedCompletionStatus");
}
subproc->OnPipeReady();
if (subproc->Done()) {
vector<Subprocess*>::iterator end =
std::remove(running_.begin(), running_.end(), subproc);
if (running_.end() != end) {
finished_.push(subproc);
running_.resize(end - running_.begin());
}
}
}
Subprocess* SubprocessSet::NextFinished() {
if (finished_.empty())
return NULL;
Subprocess* subproc = finished_.front();
finished_.pop();
return subproc;
}
| nornagon/ninja | src/subprocess-win32.cc | C++ | apache-2.0 | 5,723 |
package org.omg.CosNaming.NamingContextPackage;
/**
* org/omg/CosNaming/NamingContextPackage/NotEmptyHelper.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from /HUDSON3/workspace/8-2-build-linux-amd64/jdk8u121/8372/corba/src/share/classes/org/omg/CosNaming/nameservice.idl
* Monday, December 12, 2016 4:37:46 PM PST
*/
abstract public class NotEmptyHelper
{
private static String _id = "IDL:omg.org/CosNaming/NamingContext/NotEmpty:1.0";
public static void insert (org.omg.CORBA.Any a, NotEmpty that)
{
org.omg.CORBA.portable.OutputStream out = a.create_output_stream ();
a.type (type ());
write (out, that);
a.read_value (out.create_input_stream (), type ());
}
public static NotEmpty extract (org.omg.CORBA.Any a)
{
return read (a.create_input_stream ());
}
private static org.omg.CORBA.TypeCode __typeCode = null;
private static boolean __active = false;
synchronized public static org.omg.CORBA.TypeCode type ()
{
if (__typeCode == null)
{
synchronized (org.omg.CORBA.TypeCode.class)
{
if (__typeCode == null)
{
if (__active)
{
return org.omg.CORBA.ORB.init().create_recursive_tc ( _id );
}
__active = true;
org.omg.CORBA.StructMember[] _members0 = new org.omg.CORBA.StructMember [0];
org.omg.CORBA.TypeCode _tcOf_members0 = null;
__typeCode = org.omg.CORBA.ORB.init ().create_exception_tc (NotEmptyHelper.id (), "NotEmpty", _members0);
__active = false;
}
}
}
return __typeCode;
}
public static String id ()
{
return _id;
}
public static NotEmpty read (org.omg.CORBA.portable.InputStream istream)
{
NotEmpty value = new NotEmpty ();
// read and discard the repository ID
istream.read_string ();
return value;
}
public static void write (org.omg.CORBA.portable.OutputStream ostream, NotEmpty value)
{
// write the repository ID
ostream.write_string (id ());
}
}
| wangsongpeng/jdk-src | src/main/java/org/omg/CosNaming/NamingContextPackage/NotEmptyHelper.java | Java | apache-2.0 | 2,045 |
/*
* 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.flink.runtime.blob;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.security.MessageDigest;
import java.util.Collections;
import java.util.List;
import org.apache.flink.configuration.BlobServerOptions;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.api.common.JobID;
import org.apache.flink.configuration.SecurityOptions;
import org.apache.flink.core.fs.Path;
import org.apache.flink.util.TestLogger;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* This class contains unit tests for the {@link BlobClient} with ssl enabled.
*/
public class BlobClientSslTest extends TestLogger {
/** The buffer size used during the tests in bytes. */
private static final int TEST_BUFFER_SIZE = 17 * 1000;
/** The instance of the SSL BLOB server used during the tests. */
private static BlobServer BLOB_SSL_SERVER;
/** The SSL blob service client configuration */
private static Configuration sslClientConfig;
/** The instance of the non-SSL BLOB server used during the tests. */
private static BlobServer BLOB_SERVER;
/** The non-ssl blob service client configuration */
private static Configuration clientConfig;
/**
* Starts the SSL enabled BLOB server.
*/
@BeforeClass
public static void startSSLServer() throws IOException {
Configuration config = new Configuration();
config.setBoolean(SecurityOptions.SSL_ENABLED, true);
config.setString(SecurityOptions.SSL_KEYSTORE, "src/test/resources/local127.keystore");
config.setString(SecurityOptions.SSL_KEYSTORE_PASSWORD, "password");
config.setString(SecurityOptions.SSL_KEY_PASSWORD, "password");
BLOB_SSL_SERVER = new BlobServer(config, new VoidBlobStore());
sslClientConfig = new Configuration();
sslClientConfig.setBoolean(SecurityOptions.SSL_ENABLED, true);
sslClientConfig.setString(SecurityOptions.SSL_TRUSTSTORE, "src/test/resources/local127.truststore");
sslClientConfig.setString(SecurityOptions.SSL_TRUSTSTORE_PASSWORD, "password");
}
/**
* Starts the SSL disabled BLOB server.
*/
@BeforeClass
public static void startNonSSLServer() throws IOException {
Configuration config = new Configuration();
config.setBoolean(SecurityOptions.SSL_ENABLED, true);
config.setBoolean(BlobServerOptions.SSL_ENABLED, false);
config.setString(SecurityOptions.SSL_KEYSTORE, "src/test/resources/local127.keystore");
config.setString(SecurityOptions.SSL_KEYSTORE_PASSWORD, "password");
config.setString(SecurityOptions.SSL_KEY_PASSWORD, "password");
BLOB_SERVER = new BlobServer(config, new VoidBlobStore());
clientConfig = new Configuration();
clientConfig.setBoolean(SecurityOptions.SSL_ENABLED, true);
clientConfig.setBoolean(BlobServerOptions.SSL_ENABLED, false);
clientConfig.setString(SecurityOptions.SSL_TRUSTSTORE, "src/test/resources/local127.truststore");
clientConfig.setString(SecurityOptions.SSL_TRUSTSTORE_PASSWORD, "password");
}
/**
* Shuts the BLOB server down.
*/
@AfterClass
public static void stopServers() throws IOException {
if (BLOB_SSL_SERVER != null) {
BLOB_SSL_SERVER.close();
}
if (BLOB_SERVER != null) {
BLOB_SERVER.close();
}
}
/**
* Prepares a test file for the unit tests, i.e. the methods fills the file with a particular byte patterns and
* computes the file's BLOB key.
*
* @param file
* the file to prepare for the unit tests
* @return the BLOB key of the prepared file
* @throws IOException
* thrown if an I/O error occurs while writing to the test file
*/
private static BlobKey prepareTestFile(File file) throws IOException {
MessageDigest md = BlobUtils.createMessageDigest();
final byte[] buf = new byte[TEST_BUFFER_SIZE];
for (int i = 0; i < buf.length; ++i) {
buf[i] = (byte) (i % 128);
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
for (int i = 0; i < 20; ++i) {
fos.write(buf);
md.update(buf);
}
} finally {
if (fos != null) {
fos.close();
}
}
return new BlobKey(md.digest());
}
/**
* Validates the result of a GET operation by comparing the data from the retrieved input stream to the content of
* the specified file.
*
* @param inputStream
* the input stream returned from the GET operation
* @param file
* the file to compare the input stream's data to
* @throws IOException
* thrown if an I/O error occurs while reading the input stream or the file
*/
private static void validateGet(final InputStream inputStream, final File file) throws IOException {
InputStream inputStream2 = null;
try {
inputStream2 = new FileInputStream(file);
while (true) {
final int r1 = inputStream.read();
final int r2 = inputStream2.read();
assertEquals(r2, r1);
if (r1 < 0) {
break;
}
}
} finally {
if (inputStream2 != null) {
inputStream2.close();
}
}
}
/**
* Tests the PUT/GET operations for content-addressable streams.
*/
@Test
public void testContentAddressableStream() {
BlobClient client = null;
InputStream is = null;
try {
File testFile = File.createTempFile("testfile", ".dat");
testFile.deleteOnExit();
BlobKey origKey = prepareTestFile(testFile);
InetSocketAddress serverAddress = new InetSocketAddress("localhost", BLOB_SSL_SERVER.getPort());
client = new BlobClient(serverAddress, sslClientConfig);
// Store the data
is = new FileInputStream(testFile);
BlobKey receivedKey = client.put(is);
assertEquals(origKey, receivedKey);
is.close();
is = null;
// Retrieve the data
is = client.get(receivedKey);
validateGet(is, testFile);
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
finally {
if (is != null) {
try {
is.close();
} catch (Throwable t) {}
}
if (client != null) {
try {
client.close();
} catch (Throwable t) {}
}
}
}
/**
* Tests the PUT/GET operations for regular (non-content-addressable) streams.
*/
@Test
public void testRegularStream() {
final JobID jobID = JobID.generate();
final String key = "testkey3";
try {
final File testFile = File.createTempFile("testfile", ".dat");
testFile.deleteOnExit();
prepareTestFile(testFile);
BlobClient client = null;
InputStream is = null;
try {
final InetSocketAddress serverAddress = new InetSocketAddress("localhost", BLOB_SSL_SERVER.getPort());
client = new BlobClient(serverAddress, sslClientConfig);
// Store the data
is = new FileInputStream(testFile);
client.put(jobID, key, is);
is.close();
is = null;
// Retrieve the data
is = client.get(jobID, key);
validateGet(is, testFile);
}
finally {
if (is != null) {
is.close();
}
if (client != null) {
client.close();
}
}
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/**
* Tests the static {@link BlobClient#uploadJarFiles(InetSocketAddress, Configuration, List)} helper.
*/
private void uploadJarFile(BlobServer blobServer, Configuration blobClientConfig) throws Exception {
final File testFile = File.createTempFile("testfile", ".dat");
testFile.deleteOnExit();
prepareTestFile(testFile);
InetSocketAddress serverAddress = new InetSocketAddress("localhost", blobServer.getPort());
List<BlobKey> blobKeys = BlobClient.uploadJarFiles(serverAddress, blobClientConfig,
Collections.singletonList(new Path(testFile.toURI())));
assertEquals(1, blobKeys.size());
try (BlobClient blobClient = new BlobClient(serverAddress, blobClientConfig)) {
InputStream is = blobClient.get(blobKeys.get(0));
validateGet(is, testFile);
}
}
/**
* Verify ssl client to ssl server upload
*/
@Test
public void testUploadJarFilesHelper() throws Exception {
uploadJarFile(BLOB_SSL_SERVER, sslClientConfig);
}
/**
* Verify ssl client to non-ssl server failure
*/
@Test
public void testSSLClientFailure() throws Exception {
try {
uploadJarFile(BLOB_SERVER, sslClientConfig);
fail("SSL client connected to non-ssl server");
} catch (Exception e) {
// Exception expected
}
}
/**
* Verify non-ssl client to ssl server failure
*/
@Test
public void testSSLServerFailure() throws Exception {
try {
uploadJarFile(BLOB_SSL_SERVER, clientConfig);
fail("Non-SSL client connected to ssl server");
} catch (Exception e) {
// Exception expected
}
}
/**
* Verify non-ssl connection sanity
*/
@Test
public void testNonSSLConnection() throws Exception {
uploadJarFile(BLOB_SERVER, clientConfig);
}
}
| hongyuhong/flink | flink-runtime/src/test/java/org/apache/flink/runtime/blob/BlobClientSslTest.java | Java | apache-2.0 | 9,674 |
//-------------------------------------------------------------------------------
// <copyright file="InMemoryTraceListener.cs" company="frokonet.ch">
// Copyright (C) frokonet.ch, 2014-2020
//
// 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>
//-------------------------------------------------------------------------------
namespace SimpleDomain.Common
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
/// <summary>
/// A trace listener which holds all traced messages in a list
/// </summary>
public class InMemoryTraceListener : TraceListener
{
private static readonly Lazy<InMemoryTraceListener> InternalInstance = new Lazy<InMemoryTraceListener>(() => new InMemoryTraceListener());
private static readonly List<string> InternalLogMessages = new List<string>();
private static bool locked;
/// <summary>
/// Gets a singleton instance of this class
/// </summary>
public static TraceListener Instance => InternalInstance.Value;
/// <summary>
/// Gets all recorded log messages
/// </summary>
public static IEnumerable<string> LogMessages => InternalLogMessages;
/// <summary>
/// Clears all recorded log messages
/// </summary>
public static void ClearLogMessages()
{
WaitForUnlock();
InternalLogMessages.Clear();
}
/// <summary>
/// Locks the listener
/// </summary>
public static void Lock()
{
locked = true;
}
/// <summary>
/// Unlocks the listener
/// </summary>
public static void Unlock()
{
locked = false;
}
/// <inheritdoc />
public override void Write(string message)
{
WaitForUnlock();
InternalLogMessages.Add(message);
}
/// <inheritdoc />
public override void WriteLine(string message)
{
WaitForUnlock();
InternalLogMessages.Add(message);
}
private static void WaitForUnlock()
{
while (locked)
{
Thread.Sleep(100);
}
}
}
} | froko/SimpleDomain | src/SimpleDomain/Common/InMemoryTraceListener.cs | C# | apache-2.0 | 2,853 |
package com.jan.flc.firstlinecode.activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.jan.flc.firstlinecode.R;
/**
* Created by huangje on 17-3-8.
*/
public class UIActivity extends BaseActivity {
public static final String[] UI_SECTIONS = new String[]{
"常用控件", "布局-百分比布局", "ListView", "RecyclerView", "聊天界面"
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chapter_ui);
ListView lv = (ListView) findViewById(R.id.uiChapterList);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, UI_SECTIONS);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
switch (position) {
case 0:
startActivity(new Intent(UIActivity.this, BaseUIActivity.class));
break;
case 1:
startActivity(new Intent(UIActivity.this, PercentLayoutActivity.class));
break;
case 2:
startActivity(new Intent(UIActivity.this, ListViewActivity.class));
break;
case 3:
setRecyclerViewStyle();
break;
case 4:
startActivity(new Intent(UIActivity.this, ChatActivity.class));
break;
default:
break;
}
}
});
}
private void setRecyclerViewStyle() {
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setItems(new String[]{"纵向", "横向", "表格", "瀑布流"}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(UIActivity.this, RecyclerViewActivity.class);
intent.putExtra("style", i);
startActivity(intent);
}
});
builder.create().show();
}
}
| uzmakinaruto/FirstLineCode | app/src/main/java/com/jan/flc/firstlinecode/activity/UIActivity.java | Java | apache-2.0 | 2,700 |
package org.marketcetera.photon.quickfix;
import junit.framework.TestCase;
import org.marketcetera.quickfix.FIXVersion;
import quickfix.ConfigError;
import quickfix.DataDictionary;
import quickfix.FieldNotFound;
import quickfix.FieldType;
import quickfix.InvalidMessage;
import quickfix.Message;
import quickfix.field.OrderQty;
import quickfix.field.Side;
import quickfix.field.Symbol;
public class QuickFIXTest extends TestCase {
public void testMessageConstructor() throws InvalidMessage, FieldNotFound
{
String messageString = "8=FIX.4.29=12035=W31=17.5955=asdf268=2269=0270=17.58271=200273=01:20:04275=BGUS269=1270=17.59271=300273=01:20:04275=BGUS10=207";
Message aMessage = new Message(messageString, false);
assertEquals("asdf",aMessage.getString(Symbol.FIELD));
}
public void testQuickFIXAssumptions() throws ConfigError {
boolean orderQtyIsInt;
DataDictionary dictionary;
FIXVersion version;
version = FIXVersion.FIX40;
dictionary = new DataDictionary(version.getDataDictionaryURL());
orderQtyIsInt = (FieldType.Int == dictionary.getFieldTypeEnum(OrderQty.FIELD));
assertEquals(true, orderQtyIsInt);
assertTrue(FieldType.String.equals(dictionary.getFieldTypeEnum(Side.FIELD)));
version = FIXVersion.FIX41;
dictionary = new DataDictionary(version.getDataDictionaryURL());
orderQtyIsInt = (FieldType.Int == dictionary.getFieldTypeEnum(OrderQty.FIELD));
assertEquals(true, orderQtyIsInt);
assertTrue(FieldType.String.equals(dictionary.getFieldTypeEnum(Side.FIELD)));
version = FIXVersion.FIX42;
dictionary = new DataDictionary(version.getDataDictionaryURL());
orderQtyIsInt = (FieldType.Int == dictionary.getFieldTypeEnum(OrderQty.FIELD));
assertEquals(false, orderQtyIsInt);
assertTrue(FieldType.Char.equals(dictionary.getFieldTypeEnum(Side.FIELD)));
version = FIXVersion.FIX43;
dictionary = new DataDictionary(version.getDataDictionaryURL());
orderQtyIsInt = (FieldType.Int == dictionary.getFieldTypeEnum(OrderQty.FIELD));
assertEquals(false, orderQtyIsInt);
assertTrue(FieldType.Char.equals(dictionary.getFieldTypeEnum(Side.FIELD)));
version = FIXVersion.FIX44;
dictionary = new DataDictionary(version.getDataDictionaryURL());
orderQtyIsInt = (FieldType.Int == dictionary.getFieldTypeEnum(OrderQty.FIELD));
assertEquals(false, orderQtyIsInt);
assertTrue(FieldType.Char.equals(dictionary.getFieldTypeEnum(Side.FIELD)));
version = FIXVersion.FIX_SYSTEM;
dictionary = new DataDictionary(version.getDataDictionaryURL());
orderQtyIsInt = (FieldType.Int == dictionary.getFieldTypeEnum(OrderQty.FIELD));
assertEquals(false, orderQtyIsInt);
assertTrue(FieldType.Char.equals(dictionary.getFieldTypeEnum(Side.FIELD)));
}
}
| nagyist/marketcetera | photon/photon/plugins/org.marketcetera.photon.testfragment/src/test/java/org/marketcetera/photon/quickfix/QuickFIXTest.java | Java | apache-2.0 | 2,808 |
#!/usr/bin/ruby
#
# Author:: api.sgomes@gmail.com (Sérgio Gomes)
#
# Copyright:: Copyright 2011, Google Inc. All Rights Reserved.
#
# License:: Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This example illustrates how to create a negative campaign criterion for a
# given campaign. To create a campaign, run add_campaign.rb.
#
# Tags: CampaignCriterionService.mutate
require 'rubygems'
gem 'google-adwords-api'
require 'adwords_api'
API_VERSION = :v201003
def add_negative_campaign_criterion()
# AdwordsApi::Api will read a config file from ENV['HOME']/adwords_api.yml
# when called without parameters.
adwords = AdwordsApi::Api.new
campaign_criterion_srv =
adwords.service(:CampaignCriterionService, API_VERSION)
campaign_id = 'INSERT_CAMPAIGN_ID_HERE'.to_i
# Prepare for adding criterion.
operation = {
:operator => 'ADD',
:operand => {
# The 'xsi_type' field allows you to specify the xsi:type of the object
# being created. It's only necessary when you must provide an explicit
# type that the client library can't infer.
:xsi_type => 'NegativeCampaignCriterion',
:campaign_id => campaign_id,
:criterion => {
:xsi_type => 'Keyword',
:text => 'jupiter cruise',
:match_type => 'BROAD'
}
}
}
# Add criterion.
response = campaign_criterion_srv.mutate([operation])
campaign_criterion = response[:value].first
puts 'Campaign criterion id %d was successfully added.' %
campaign_criterion[:criterion][:id]
end
if __FILE__ == $0
# To enable logging of SOAP requests, set the ADWORDSAPI_DEBUG environment
# variable to 'true'. This can be done either from your operating system
# environment or via code, as done below.
ENV['ADWORDSAPI_DEBUG'] = 'false'
begin
add_negative_campaign_criterion()
# Connection error. Likely transitory.
rescue Errno::ECONNRESET, SOAP::HTTPStreamError, SocketError => e
puts 'Connection Error: %s' % e
puts 'Source: %s' % e.backtrace.first
# API Error.
rescue AdwordsApi::Errors::ApiException => e
puts 'API Exception caught.'
puts 'Message: %s' % e.message
puts 'Code: %d' % e.code if e.code
puts 'Trigger: %s' % e.trigger if e.trigger
puts 'Errors:'
if e.errors
e.errors.each_with_index do |error, index|
puts ' %d. Error type is %s. Fields:' % [index + 1, error[:xsi_type]]
error.each_pair do |field, value|
if field != :xsi_type
puts ' %s: %s' % [field, value]
end
end
end
end
end
end
| sylow/google-adwords-api | examples/v201003/add_negative_campaign_criterion.rb | Ruby | apache-2.0 | 3,158 |
/*
* Copyright 2019 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import static com.google.javascript.jscomp.Es6ToEs3Util.CANNOT_CONVERT_YET;
import com.google.javascript.jscomp.CompilerOptions.LanguageMode;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link RewriteNewDotTarget}. */
@RunWith(JUnit4.class)
@SuppressWarnings("RhinoNodeGetFirstFirstChild")
public class RewriteNewDotTargetTest extends CompilerTestCase {
@Before
public void enableTypeCheckBeforePass() {
enableTypeCheck();
enableTypeInfoValidation();
}
@Override
protected CompilerPass getProcessor(Compiler compiler) {
return new RewriteNewDotTarget(compiler);
}
@Override
protected CompilerOptions getOptions() {
CompilerOptions options = super.getOptions();
options.setLanguageIn(LanguageMode.ECMASCRIPT_NEXT_IN);
options.setLanguageOut(LanguageMode.ECMASCRIPT5_STRICT);
return options;
}
@Test
public void testNewTargetInNonConstructorMethod() {
testError(
lines(
"", //
"/** @constructor */",
"function Foo() { new.target; }", // not an ES6 class constructor
""),
CANNOT_CONVERT_YET);
testError(
"function foo() { new.target; }", // not a constructor at all
CANNOT_CONVERT_YET);
testError(
lines(
"", //
"class Foo {",
" method() {", // not a constructor
" new.target;",
" }",
"}",
""),
CANNOT_CONVERT_YET);
}
@Test
public void testNewTargetInEs6Constructor() {
test(
lines(
"", //
"class Foo {",
" constructor() {",
" new.target;",
" () => new.target;", // works in arrow functions, too
" }",
"}",
""),
lines(
"", //
"class Foo {",
" constructor() {",
" this.constructor;",
" () => this.constructor;", // works in arrow functions, too
" }",
"}",
""));
}
@Test
public void testNewTargetInEs6Constructor_superCtorReturnsObject() {
// TODO(b/157140030): This is an unexpected behaviour change.
test(
lines(
"/** @constructor */",
"function Base() {",
" return {};",
"}",
"",
"class Child extends Base {",
" constructor() {",
" super();",
" new.target;", // Child
" }",
"}"),
lines(
"/** @constructor */",
"function Base() {",
" return {};",
"}",
"",
"class Child extends Base {",
" constructor() {",
" super();",
" this.constructor;", // Object
" }",
"}"));
}
@Test
public void testNewTargetInEs6Constructor_beforeSuper() {
test(
lines(
"class Foo extends Object {",
" constructor() {",
" new.target;",
" super();",
" }",
"}"),
lines(
"class Foo extends Object {",
" constructor() {",
" this.constructor;", // `this` before `super`
" super();",
" }",
"}"));
}
}
| vobruba-martin/closure-compiler | test/com/google/javascript/jscomp/RewriteNewDotTargetTest.java | Java | apache-2.0 | 4,093 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Xml.Serialization;
using System.Configuration;
using System.IO;
namespace GetServiceInfo
{
class GetOutletServiceInfo
{
static void Main(string[] args)
{
// Your username, password and customer number are imported from the following file
// CPCWS_ServiceInfo_DotNet_Samples\REST\serviceinfo\user.xml
var username = ConfigurationSettings.AppSettings["username"];
var password = ConfigurationSettings.AppSettings["password"];
// REST URI
String url = "https://ct.soa-gw.canadapost.ca/rs/serviceinfo/outlet";
var method = "GET"; // HTTP Method
String responseAsString = ".NET Framework " + Environment.Version.ToString() + "\r\n\r\n";
try
{
// Create REST Request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method;
// Set Basic Authentication Header using username and password variables
string auth = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(username + ":" + password));
request.Headers = new WebHeaderCollection();
request.Headers.Add("Authorization", auth);
request.Headers.Add("Accept-Language", "en-CA");
request.Accept = "application/vnd.cpc.serviceinfo-v2+xml";
// Execute REST Request
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
responseAsString += "HTTP Response Status: " + (int)response.StatusCode + "\r\n\r\n";
// Deserialize xml response to customer object
XmlSerializer serializer = new XmlSerializer(typeof(InfoMessagesType));
TextReader reader = new StreamReader(response.GetResponseStream());
InfoMessagesType infoMessages = (InfoMessagesType)serializer.Deserialize(reader);
if (infoMessages.infomessage != null)
{
foreach (InfoMessageType infoMessage in infoMessages.infomessage)
{
responseAsString += " Message Type is :" + infoMessage.messagetype + "\r\n";
responseAsString += " Message Text is :" + infoMessage.messagetext + "\r\n";
responseAsString += " Message Start Time is :" + infoMessage.fromdatetime + "\r\n";
responseAsString += " Message End Time is :" + infoMessage.todatetime + "\r\n";
}
}
}
catch (WebException webEx)
{
HttpWebResponse response = (HttpWebResponse)webEx.Response;
if (response != null)
{
responseAsString += "HTTP Response Status: " + webEx.Message + "\r\n";
// Retrieve errors from messages object
try
{
// Deserialize xml response to messages object
XmlSerializer serializer = new XmlSerializer(typeof(messages));
TextReader reader = new StreamReader(response.GetResponseStream());
messages myMessages = (messages)serializer.Deserialize(reader);
if (myMessages.message != null)
{
foreach (var item in myMessages.message)
{
responseAsString += "Error Code: " + item.code + "\r\n";
responseAsString += "Error Msg: " + item.description + "\r\n";
}
}
}
catch (Exception ex)
{
// Misc Exception
responseAsString += "ERROR: " + ex.Message;
}
}
else
{
// Invalid Request
responseAsString += "ERROR: " + webEx.Message;
}
}
catch (Exception ex)
{
// Misc Exception
responseAsString += "ERROR: " + ex.Message;
}
Console.WriteLine(responseAsString);
Console.WriteLine("Press any key to continue...");
Console.ReadKey(true);
}
}
}
| Kiandr/MS | Languages/CSharp/CPCWS_DotNet_Samples/REST/serviceinfo/GetOutletServiceInfo/GetOutletServiceInfo.cs | C# | apache-2.0 | 4,631 |
/*
* Copyright 2011 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.
*/
package com.google.android.apps.iosched.ui;
import com.google.android.apps.iosched.R;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
/**
* A {@link BaseActivity} that simply contains a single fragment. The intent used to invoke this
* activity is forwarded to the fragment as arguments during fragment instantiation. Derived
* activities should only need to implement
* {@link com.google.android.apps.iosched.ui.BaseSinglePaneActivity#onCreatePane()}.
*/
public abstract class BaseSinglePaneActivity extends BaseActivity {
private Fragment mFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_singlepane_empty);
final String customTitle = getIntent().getStringExtra(Intent.EXTRA_TITLE);
//getActivityHelper().setActionBarTitle(customTitle != null ? customTitle : getTitle());
if (savedInstanceState == null) {
mFragment = onCreatePane();
mFragment.setArguments(intentToFragmentArguments(getIntent()));
getSupportFragmentManager().beginTransaction()
.add(R.id.root_container, mFragment)
.commit();
}
}
/**
* Called in <code>onCreate</code> when the fragment constituting this activity is needed.
* The returned fragment's arguments will be set to the intent used to invoke this activity.
*/
protected abstract Fragment onCreatePane();
}
| skyisle/iosched2011 | android/src/com/google/android/apps/iosched/ui/BaseSinglePaneActivity.java | Java | apache-2.0 | 2,149 |
/*
* Copyright 2017-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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spring.data.datastore.core.mapping.event;
import org.springframework.context.ApplicationEvent;
/** An event published when entities are read from Cloud Datastore. */
public class ReadEvent extends ApplicationEvent {
/**
* Constructor.
*
* @param results A list of results from the read operation where each item was mapped from a
* Cloud Datastore entity.
*/
public ReadEvent(Iterable results) {
super(results);
}
/**
* Get the list of results from the read operation.
*
* @return the list of results from the read operation.
*/
public Iterable getResults() {
return (Iterable) getSource();
}
}
| GoogleCloudPlatform/spring-cloud-gcp | spring-cloud-gcp-data-datastore/src/main/java/com/google/cloud/spring/data/datastore/core/mapping/event/ReadEvent.java | Java | apache-2.0 | 1,298 |
import logging
from types import FunctionType
import ray
import ray.cloudpickle as pickle
from ray.experimental.internal_kv import _internal_kv_initialized, \
_internal_kv_get, _internal_kv_put
from ray.tune.error import TuneError
TRAINABLE_CLASS = "trainable_class"
ENV_CREATOR = "env_creator"
RLLIB_MODEL = "rllib_model"
RLLIB_PREPROCESSOR = "rllib_preprocessor"
RLLIB_ACTION_DIST = "rllib_action_dist"
TEST = "__test__"
KNOWN_CATEGORIES = [
TRAINABLE_CLASS, ENV_CREATOR, RLLIB_MODEL, RLLIB_PREPROCESSOR,
RLLIB_ACTION_DIST, TEST
]
logger = logging.getLogger(__name__)
def has_trainable(trainable_name):
return _global_registry.contains(TRAINABLE_CLASS, trainable_name)
def get_trainable_cls(trainable_name):
validate_trainable(trainable_name)
return _global_registry.get(TRAINABLE_CLASS, trainable_name)
def validate_trainable(trainable_name):
if not has_trainable(trainable_name):
# Make sure everything rllib-related is registered.
from ray.rllib import _register_all
_register_all()
if not has_trainable(trainable_name):
raise TuneError("Unknown trainable: " + trainable_name)
def register_trainable(name, trainable, warn=True):
"""Register a trainable function or class.
This enables a class or function to be accessed on every Ray process
in the cluster.
Args:
name (str): Name to register.
trainable (obj): Function or tune.Trainable class. Functions must
take (config, status_reporter) as arguments and will be
automatically converted into a class during registration.
"""
from ray.tune.trainable import Trainable
from ray.tune.function_runner import wrap_function
if isinstance(trainable, type):
logger.debug("Detected class for trainable.")
elif isinstance(trainable, FunctionType):
logger.debug("Detected function for trainable.")
trainable = wrap_function(trainable, warn=warn)
elif callable(trainable):
logger.info(
"Detected unknown callable for trainable. Converting to class.")
trainable = wrap_function(trainable, warn=warn)
if not issubclass(trainable, Trainable):
raise TypeError("Second argument must be convertable to Trainable",
trainable)
_global_registry.register(TRAINABLE_CLASS, name, trainable)
def register_env(name, env_creator):
"""Register a custom environment for use with RLlib.
This enables the environment to be accessed on every Ray process
in the cluster.
Args:
name (str): Name to register.
env_creator (obj): Function that creates an env.
"""
if not isinstance(env_creator, FunctionType):
raise TypeError("Second argument must be a function.", env_creator)
_global_registry.register(ENV_CREATOR, name, env_creator)
def check_serializability(key, value):
_global_registry.register(TEST, key, value)
def _make_key(category, key):
"""Generate a binary key for the given category and key.
Args:
category (str): The category of the item
key (str): The unique identifier for the item
Returns:
The key to use for storing a the value.
"""
return (b"TuneRegistry:" + category.encode("ascii") + b"/" +
key.encode("ascii"))
class _Registry:
def __init__(self):
self._to_flush = {}
def register(self, category, key, value):
"""Registers the value with the global registry.
Raises:
PicklingError if unable to pickle to provided file.
"""
if category not in KNOWN_CATEGORIES:
from ray.tune import TuneError
raise TuneError("Unknown category {} not among {}".format(
category, KNOWN_CATEGORIES))
self._to_flush[(category, key)] = pickle.dumps_debug(value)
if _internal_kv_initialized():
self.flush_values()
def contains(self, category, key):
if _internal_kv_initialized():
value = _internal_kv_get(_make_key(category, key))
return value is not None
else:
return (category, key) in self._to_flush
def get(self, category, key):
if _internal_kv_initialized():
value = _internal_kv_get(_make_key(category, key))
if value is None:
raise ValueError(
"Registry value for {}/{} doesn't exist.".format(
category, key))
return pickle.loads(value)
else:
return pickle.loads(self._to_flush[(category, key)])
def flush_values(self):
for (category, key), value in self._to_flush.items():
_internal_kv_put(_make_key(category, key), value, overwrite=True)
self._to_flush.clear()
_global_registry = _Registry()
ray.worker._post_init_hooks.append(_global_registry.flush_values)
class _ParameterRegistry:
def __init__(self):
self.to_flush = {}
self.references = {}
def put(self, k, v):
self.to_flush[k] = v
if ray.is_initialized():
self.flush()
def get(self, k):
if not ray.is_initialized():
return self.to_flush[k]
return ray.get(self.references[k])
def flush(self):
for k, v in self.to_flush.items():
self.references[k] = ray.put(v)
self.to_flush.clear()
parameter_registry = _ParameterRegistry()
ray.worker._post_init_hooks.append(parameter_registry.flush)
| richardliaw/ray | python/ray/tune/registry.py | Python | apache-2.0 | 5,525 |
# Copyright (c) 2018-2021 Micro Focus or one of its affiliates.
# Copyright (c) 2018 Uber Technologies, 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.
# Copyright (c) 2013-2017 Uber Technologies, Inc.
#
# 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.
from __future__ import print_function, division, absolute_import
from six import text_type, binary_type
from ..message import BulkFrontendMessage
class CopyData(BulkFrontendMessage):
message_id = b'd'
def __init__(self, data, unicode_error='strict'):
BulkFrontendMessage.__init__(self)
if isinstance(data, text_type):
self.bytes_ = data.encode(encoding='utf-8', errors=unicode_error)
elif isinstance(data, binary_type):
self.bytes_ = data
else:
raise TypeError("Data should be string or bytes")
def read_bytes(self):
return self.bytes_
| uber/vertica-python | vertica_python/vertica/messages/frontend_messages/copy_data.py | Python | apache-2.0 | 2,393 |
package com.sdw.soft.demo.rxjava;
import com.google.common.base.Joiner;
import org.junit.Test;
import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func1;
/**
* Created by shangyd on 2017/5/13.
*/
public class TestRxJava {
@Test
public void test01() {
Observable observable = Observable.just("hello").map(new Func1() {
@Override
public Object call(Object o) {
return Joiner.on(" ").useForNull("").join(new Object[]{o,"world"});
}
});
observable.subscribe(new Action1() {
@Override
public void call(Object o) {
System.out.println(o.toString());
}
});
}
}
| sdw2330976/SpringBC | springbootjpa/src/test/java/com/sdw/soft/demo/rxjava/TestRxJava.java | Java | apache-2.0 | 726 |
"use strict";
require('../core/setup');
var $ = require('jquery'),
L = require('leaflet'),
assert = require('chai').assert,
sinon = require('sinon'),
Marionette = require('../../shim/backbone.marionette'),
App = require('../app'),
models = require('./models'),
utils = require('./utils'),
views = require('./views'),
settings = require('../core/settings'),
testUtils = require('../core/testUtils');
var sandboxId = 'sandbox',
sandboxSelector = '#' + sandboxId,
TEST_SHAPE = {
'type': 'MultiPolygon',
'coordinates': [[[-5e6, -1e6], [-4e6, 1e6], [-3e6, -1e6]]]
};
var SandboxRegion = Marionette.Region.extend({
el: sandboxSelector
});
describe('Draw', function() {
before(function() {
// Ensure that draw tools are enabled before testing
settings.set('draw_tools', [
'SelectArea', // Boundary Selector
'Draw', // Custom Area or 1 Sq Km stamp
'PlaceMarker', // Delineate Watershed
'ResetDraw',
]);
});
beforeEach(function() {
$('body').append('<div id="sandbox">');
});
afterEach(function() {
$(sandboxSelector).remove();
window.location.hash = '';
testUtils.resetApp(App);
});
describe('ToolbarView', function() {
// Setup the toolbar controls, enable/disable them, and verify
// the correct CSS classes are applied.
it('enables/disables toolbar controls when the model enableTools/disableTools methods are called', function() {
var sandbox = new SandboxRegion(),
$el = sandbox.$el,
model = new models.ToolbarModel(),
view = new views.ToolbarView({
model: model
});
sandbox.show(view);
populateSelectAreaDropdown($el, model);
// Nothing should be disabled at this point.
// Test that toggling the `toolsEnabled` property on the model
// will disable all drawing tools.
assert.equal($el.find('.disabled').size(), 0);
model.disableTools();
assert.equal($el.find('.disabled').size(), 3);
model.enableTools();
assert.equal($el.find('.disabled').size(), 0);
});
it('adds an AOI to the map after calling getShapeAndAnalyze', function(done) {
var successCount = 2,
deferred = setupGetShapeAndAnalyze(successCount),
success;
deferred.
done(function() {
assert.equal(App.map.get('areaOfInterest'), TEST_SHAPE);
success = true;
}).
fail(function() {
success = false;
}).
always(function() {
assert.equal(success, true);
done();
});
});
it('fails to add AOI when shape id cannot be retrieved by getShapeAndAnalyze', function(done) {
// Set successCount high enough so that the polling will fail.
var successCount = 6,
deferred = setupGetShapeAndAnalyze(successCount),
success;
deferred.
done(function() {
success = true;
}).
fail(function() {
success = false;
}).
always(function() {
assert.equal(success, false);
done();
});
});
it('resets the current area of interest on Reset', function() {
var setup = setupResetTestObject();
App.map.set('areaOfInterest', TEST_SHAPE);
setup.resetRegion.currentView.resetDrawingState();
assert.isNull(App.map.get('areaOfInterest',
'Area of Interest was not removed on reset from the map'));
});
it('resets the boundary layer on Reset', function() {
var setup = setupResetTestObject(),
ofg = L.featureGroup(),
testFeature = {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-104.99404, 39.75621]
}
};
ofg.addLayer(L.geoJson(testFeature));
assert.equal(ofg.getLayers().length, 1);
setup.model.set('outlineFeatureGroup', ofg);
setup.resetRegion.currentView.resetDrawingState();
assert.equal(ofg.getLayers().length, 0,
'Boundary Layer should have been removed from layer group');
});
it('removes in progress drawing on Reset', function() {
var setup = setupResetTestObject(),
spy = sinon.spy(utils, 'cancelDrawing');
utils.drawPolygon(setup.map);
setup.resetRegion.currentView.resetDrawingState();
assert.equal(spy.callCount, 1);
});
});
});
function setupGetShapeAndAnalyze(successCount) {
var sandbox = new SandboxRegion(),
model = new models.ToolbarModel(),
view = new views.ToolbarView({
model: model
}),
shapeId = 1,
e = {latlng: L.latLng(50.5, 30.5)},
ofg = model.get('outlineFeatureGroup'),
grid = {
callCount: 0,
_objectForEvent: function() { //mock grid returns shapeId on second call
this.callCount++;
if (this.callCount >= successCount) {
return {data: {id: shapeId}};
} else {
return {};
}
}
},
tableId = 2;
sandbox.show(view);
App.restApi = {
getPolygon: function() {
return $.Deferred().resolve(TEST_SHAPE).promise();
}
};
return views.getShapeAndAnalyze(e, model, ofg, grid, tableId);
}
function setupResetTestObject() {
var sandbox = new SandboxRegion(),
model = new models.ToolbarModel(),
view = new views.ToolbarView({
model: model
}),
resetRegion = view.getRegion('resetRegion'),
map = App.getLeafletMap();
sandbox.show(view);
return {
sandbox: sandbox,
model: model,
view: view,
resetRegion: resetRegion,
map: map
};
}
function assertTextEqual($el, sel, text) {
assert.equal($el.find(sel).text().trim(), text);
}
function populateSelectAreaDropdown($el, toolbarModel) {
// This control should start off in a Loading state.
assertTextEqual($el, '#select-area-region button', 'Loading...');
// Load some shapes...
toolbarModel.set('predefinedShapeTypes', [
{
"endpoint": "http://localhost:4000/0/{z}/{x}/{y}",
"display": "Congressional Districts",
"name": "tiles"
}]);
// This dropdown should now be populated.
assertTextEqual($el, '#select-area-region button', 'Select by Boundary');
assertTextEqual($el, '#select-area-region li', 'Congressional Districts');
}
| lliss/model-my-watershed | src/mmw/js/src/draw/tests.js | JavaScript | apache-2.0 | 7,248 |
/**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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.gravitee.am.service.validators;
import io.gravitee.am.service.exception.InvalidPathException;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* @author Jeoffrey HAEYAERT (jeoffrey.haeyaert at graviteesource.com)
* @author GraviteeSource Team
*/
public class PathValidatorTest {
@Test
public void validate() {
Throwable throwable = PathValidator.validate("/test").blockingGet();
assertNull(throwable);
}
@Test
public void validateSpecialCharacters() {
Throwable throwable = PathValidator.validate("/test/subpath/subpath2_with-and.dot/AND_UPPERCASE").blockingGet();
assertNull(throwable);
}
@Test
public void validate_invalidEmptyPath() {
Throwable throwable = PathValidator.validate("").blockingGet();
assertNotNull(throwable);
assertTrue(throwable instanceof InvalidPathException);
}
@Test
public void validate_nullPath() {
Throwable throwable = PathValidator.validate(null).blockingGet();
assertNotNull(throwable);
assertTrue(throwable instanceof InvalidPathException);
}
@Test
public void validate_multipleSlashesPath() {
Throwable throwable = PathValidator.validate("/////test////").blockingGet();
assertNotNull(throwable);
assertTrue(throwable instanceof InvalidPathException);
}
@Test
public void validate_invalidCharacters() {
Throwable throwable = PathValidator.validate("/test$:\\;,+").blockingGet();
assertNotNull(throwable);
assertTrue(throwable instanceof InvalidPathException);
}
} | gravitee-io/graviteeio-access-management | gravitee-am-service/src/test/java/io/gravitee/am/service/validators/PathValidatorTest.java | Java | apache-2.0 | 2,272 |
<?php
/**
* 支付配置
* @author hfc
* @date 2015-8-31
*/
namespace apps\admin\controllers;
use apps\admin\models\Payment;
use apps\admin\models\PaymentPlugin;
use enums\SystemEnums;
use Phalcon\Db\Profiler;
use Phalcon\Paginator\Adapter\Model as PaginatorModel;
use Phalcon\Validation;
use Phalcon\Validation\Validator\PresenceOf;
class PayconfigController extends AdminBaseController
{
public function initialize()
{
parent::initialize();
}
/**
* @author( author='hfc' )
* @date( date = '2015-8-31' )
* @comment( comment = '使用支付' )
* @method( method = 'indexAction' )
* @op( op = 'r' )
*/
public function indexAction()
{
$pageNum = $this->request->getQuery( 'page', 'int' );
$currentPage = $pageNum ? $pageNum : 1;
$payModel = new Payment();
$pay = $payModel->getPayment( $this->shopId );
$pagination = new PaginatorModel( array( 'data' => $pay,
'limit' => 10,
'page' => $currentPage
));
$page = $pagination->getPaginate();
$this->view->page = $page;
}
/**
* @author( author='hfc' )
* @date( date = '2015-8-31' )
* @comment( comment = '全部支付' )
* @method( method = 'indexAction' )
* @op( op = 'r' )
*/
public function allAction()
{
$pageNum = $this->request->getQuery( 'page', 'int' );
$currentPage = $pageNum ? $pageNum : 1;
$pay = PaymentPlugin::find( 'delsign=' . SystemEnums::DELSIGN_NO );
$pagination = new PaginatorModel( array( 'data' => $pay,
'limit' => 10,
'page' => $currentPage
));
$page = $pagination->getPaginate();
$this->view->page = $page;
}
/**
* @author( author='hfc' )
* @date( date = '2015-8-31' )
* @comment( comment = '删除已使用的支付' )
* @method( method = 'deleteAction' )
* @op( op = 'd' )
*/
public function deleteAction()
{
$id = $this->request->getPost( 'id', 'int' );
$profile = new Profiler();
$payment = Payment::findFirst( array( 'id=?0', 'bind' => array( $id )));
if( $payment )
{
$status = $payment->update( array( 'delsign' => SystemEnums::DELSIGN_YES ) );
if( $status )
{
$this->success( '删除成功' );
}
else
{
$this->error( '删除失败' );
}
}
}
/**
* @author( author='hfc' )
* @date( date = '2015-9-1' )
* @comment( comment = '使用支付的添加显示' )
* @method( method = 'editAction' )
* @op( op = '' )
*/
public function addAction()
{
$id = $this->request->getQuery( 'id', 'int' );
if( $id )
{
$plugin = PaymentPlugin::findFirst( array( 'id=?0', 'bind' => array( $id ), 'columns' => 'id,name'));
if( $plugin )
{
$this->view->plugin = $plugin->toArray();
}
}
}
/**
* @author( author='hfc' )
* @date( date = '2015-9-1' )
* @comment( comment = '使用支付的编辑' )
* @method( method = 'editAction' )
* @op( op = '' )
*/
public function editAction()
{
$id = $this->request->getQuery( 'id', 'int' );
$pay = Payment::findFirst( array( 'id=?0', 'bind' => array( $id )));
if( $pay )
{
$this->view->pay = $pay->toArray();
}
}
/**
* @author( author='hfc' )
* @date( date = '2015-9-1' )
* @comment( comment = '使用支付的编辑' )
* @method( method = 'editAction' )
* @op( op = '' )
*/
public function readAction()
{
$this->editAction();
$this->view->isRead = true;
$this->view->pick( 'payconfig/edit' );
}
/**
* @author( author='hfc' )
* @date( date = '2015-9-1' )
* @comment( comment = '使用支付的更新' )
* @method( method = 'updateAction' )
* @op( op = 'u' )
*/
public function updateAction()
{
$this->csrfCheck();
$id = $this->request->getPost( 'id', 'int' );
$data[ 'pay_name' ] = $this->request->getPost( 'pay_name', 'string' );
$data[ 'partner_id' ] = $this->request->getPost( 'partner_id', 'string' );
$data[ 'partner_key' ] = $this->request->getPost( 'partner_key', 'string' );
$data[ 'status' ] = $this->request->getPost( 'status', 'int' );
$data[ 'sort' ] = $this->request->getPost( 'sort', 'int' );
$this->validation( $data );
$pay = Payment::findFirst( array( 'id=?0', 'bind' => array( $id )));
if( $pay )
{
$status = $pay->update( $data );
if( $status )
{
$this->success( '更新成功' );
}
}
$this->error( '更新失败' );
}
/**
* @author( author='hfc' )
* @date( date = '2015-9-1' )
* @comment( comment = '使用支付的添加' )
* @method( method = 'insertAction' )
* @op( op = 'c' )
*/
public function insertAction()
{
$this->csrfCheck();
$data[ 'pay_name' ] = $this->request->getPost( 'pay_name', 'string' );
$data[ 'plugin_id' ] = $this->request->getPost( 'plugin_id', 'string' );
$data[ 'partner_id' ] = $this->request->getPost( 'partner_id', 'string' );
$data[ 'partner_key' ] = $this->request->getPost( 'partner_key', 'string' );
$data[ 'status' ] = $this->request->getPost( 'status', 'int' );
$data[ 'sort' ] = $this->request->getPost( 'sort', 'int' );
$this->validation( $data );
$data[ 'delsign' ] = $data[ 'status' ] = 0;
$data[ 'shop_id' ] = $this->shopId;
$pay = new Payment();
if( $pay )
{
$status = $pay->save( $data );
if( $status )
{
$this->success( '添加成功' );
}
}
$this->error( '添加失败' );
}
/**
* @author( author='hfc' )
* @date( date = '2015-9-1' )
* @comment( comment = '验证数据' )
* @method( method = 'validation' )
* @op( op = 'u' )
*/
private function validation( $data )
{
$validation = new Validation();
$validation->add( 'partner_id', new PresenceOf( array(
'message' => '合作者身份必学填写'
) ) );
$validation->add( 'partner_key', new PresenceOf( array(
'message' => '安全校验码必学填写'
) ) );
$msgs = $validation->validate( $data );
if( count( $msgs ))
{
foreach( $msgs as $m )
{
$this->error( $m->getMessage() );
}
}
}
}
| sxyunfeng/fcms | apps/admin/controllers/PayconfigController.php | PHP | apache-2.0 | 7,003 |
<?php
/*
* Copyright 2021 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 WARNING
* Generated by gapic-generator-php from the file
* https://github.com/google/googleapis/blob/master/google/ads/googleads/v8/services/ad_group_service.proto
* Updates to the above are reflected here through a refresh process.
*/
namespace Google\Ads\GoogleAds\V8\Services\Gapic;
use Google\Ads\GoogleAds\V8\Resources\AdGroup;
use Google\Ads\GoogleAds\V8\Services\AdGroupOperation;
use Google\Ads\GoogleAds\V8\Services\GetAdGroupRequest;
use Google\Ads\GoogleAds\V8\Services\MutateAdGroupsRequest;
use Google\Ads\GoogleAds\V8\Services\MutateAdGroupsResponse;
use Google\ApiCore\ApiException;
use Google\ApiCore\CredentialsWrapper;
use Google\ApiCore\GapicClientTrait;
use Google\ApiCore\PathTemplate;
use Google\ApiCore\RequestParamsHeaderDescriptor;
use Google\ApiCore\RetrySettings;
use Google\ApiCore\Transport\TransportInterface;
use Google\ApiCore\ValidationException;
use Google\Auth\FetchAuthTokenInterface;
/**
* Service Description: Service to manage ad groups.
*
* This class provides the ability to make remote calls to the backing service through method
* calls that map to API methods. Sample code to get started:
*
* ```
* $adGroupServiceClient = new AdGroupServiceClient();
* try {
* $formattedResourceName = $adGroupServiceClient->adGroupName('[CUSTOMER_ID]', '[AD_GROUP_ID]');
* $response = $adGroupServiceClient->getAdGroup($formattedResourceName);
* } finally {
* $adGroupServiceClient->close();
* }
* ```
*
* Many parameters require resource names to be formatted in a particular way. To
* assist with these names, this class includes a format method for each type of
* name, and additionally a parseName method to extract the individual identifiers
* contained within formatted names that are returned by the API.
*/
class AdGroupServiceGapicClient
{
use GapicClientTrait;
/**
* The name of the service.
*/
const SERVICE_NAME = 'google.ads.googleads.v8.services.AdGroupService';
/**
* The default address of the service.
*/
const SERVICE_ADDRESS = 'googleads.googleapis.com';
/**
* The default port of the service.
*/
const DEFAULT_SERVICE_PORT = 443;
/**
* The name of the code generator, to be included in the agent header.
*/
const CODEGEN_NAME = 'gapic';
/**
* The default scopes required by the service.
*/
public static $serviceScopes = [
'https://www.googleapis.com/auth/adwords',
];
private static $adGroupNameTemplate;
private static $pathTemplateMap;
private static function getClientDefaults()
{
return [
'serviceName' => self::SERVICE_NAME,
'serviceAddress' => self::SERVICE_ADDRESS . ':' . self::DEFAULT_SERVICE_PORT,
'clientConfig' => __DIR__ . '/../resources/ad_group_service_client_config.json',
'descriptorsConfigPath' => __DIR__ . '/../resources/ad_group_service_descriptor_config.php',
'gcpApiConfigPath' => __DIR__ . '/../resources/ad_group_service_grpc_config.json',
'credentialsConfig' => [
'defaultScopes' => self::$serviceScopes,
],
'transportConfig' => [
'rest' => [
'restClientConfigPath' => __DIR__ . '/../resources/ad_group_service_rest_client_config.php',
],
],
];
}
private static function getAdGroupNameTemplate()
{
if (self::$adGroupNameTemplate == null) {
self::$adGroupNameTemplate = new PathTemplate('customers/{customer_id}/adGroups/{ad_group_id}');
}
return self::$adGroupNameTemplate;
}
private static function getPathTemplateMap()
{
if (self::$pathTemplateMap == null) {
self::$pathTemplateMap = [
'adGroup' => self::getAdGroupNameTemplate(),
];
}
return self::$pathTemplateMap;
}
/**
* Formats a string containing the fully-qualified path to represent a ad_group
* resource.
*
* @param string $customerId
* @param string $adGroupId
*
* @return string The formatted ad_group resource.
*/
public static function adGroupName($customerId, $adGroupId)
{
return self::getAdGroupNameTemplate()->render([
'customer_id' => $customerId,
'ad_group_id' => $adGroupId,
]);
}
/**
* Parses a formatted name string and returns an associative array of the components in the name.
* The following name formats are supported:
* Template: Pattern
* - adGroup: customers/{customer_id}/adGroups/{ad_group_id}
*
* The optional $template argument can be supplied to specify a particular pattern,
* and must match one of the templates listed above. If no $template argument is
* provided, or if the $template argument does not match one of the templates
* listed, then parseName will check each of the supported templates, and return
* the first match.
*
* @param string $formattedName The formatted name string
* @param string $template Optional name of template to match
*
* @return array An associative array from name component IDs to component values.
*
* @throws ValidationException If $formattedName could not be matched.
*/
public static function parseName($formattedName, $template = null)
{
$templateMap = self::getPathTemplateMap();
if ($template) {
if (!isset($templateMap[$template])) {
throw new ValidationException("Template name $template does not exist");
}
return $templateMap[$template]->match($formattedName);
}
foreach ($templateMap as $templateName => $pathTemplate) {
try {
return $pathTemplate->match($formattedName);
} catch (ValidationException $ex) {
// Swallow the exception to continue trying other path templates
}
}
throw new ValidationException("Input did not match any known format. Input: $formattedName");
}
/**
* Constructor.
*
* @param array $options {
* Optional. Options for configuring the service API wrapper.
*
* @type string $serviceAddress
* The address of the API remote host. May optionally include the port, formatted
* as "<uri>:<port>". Default 'googleads.googleapis.com:443'.
* @type string|array|FetchAuthTokenInterface|CredentialsWrapper $credentials
* The credentials to be used by the client to authorize API calls. This option
* accepts either a path to a credentials file, or a decoded credentials file as a
* PHP array.
* *Advanced usage*: In addition, this option can also accept a pre-constructed
* {@see \Google\Auth\FetchAuthTokenInterface} object or
* {@see \Google\ApiCore\CredentialsWrapper} object. Note that when one of these
* objects are provided, any settings in $credentialsConfig will be ignored.
* @type array $credentialsConfig
* Options used to configure credentials, including auth token caching, for the
* client. For a full list of supporting configuration options, see
* {@see \Google\ApiCore\CredentialsWrapper::build()} .
* @type bool $disableRetries
* Determines whether or not retries defined by the client configuration should be
* disabled. Defaults to `false`.
* @type string|array $clientConfig
* Client method configuration, including retry settings. This option can be either
* a path to a JSON file, or a PHP array containing the decoded JSON data. By
* default this settings points to the default client config file, which is
* provided in the resources folder.
* @type string|TransportInterface $transport
* The transport used for executing network requests. May be either the string
* `rest` or `grpc`. Defaults to `grpc` if gRPC support is detected on the system.
* *Advanced usage*: Additionally, it is possible to pass in an already
* instantiated {@see \Google\ApiCore\Transport\TransportInterface} object. Note
* that when this object is provided, any settings in $transportConfig, and any
* $serviceAddress setting, will be ignored.
* @type array $transportConfig
* Configuration options that will be used to construct the transport. Options for
* each supported transport type should be passed in a key for that transport. For
* example:
* $transportConfig = [
* 'grpc' => [...],
* 'rest' => [...],
* ];
* See the {@see \Google\ApiCore\Transport\GrpcTransport::build()} and
* {@see \Google\ApiCore\Transport\RestTransport::build()} methods for the
* supported options.
* @type callable $clientCertSource
* A callable which returns the client cert as a string. This can be used to
* provide a certificate and private key to the transport layer for mTLS.
* }
*
* @throws ValidationException
*/
public function __construct(array $options = [])
{
$clientOptions = $this->buildClientOptions($options);
$this->setClientOptions($clientOptions);
}
/**
* Returns the requested ad group in full detail.
*
* List of thrown errors:
* [AuthenticationError]()
* [AuthorizationError]()
* [HeaderError]()
* [InternalError]()
* [QuotaError]()
* [RequestError]()
*
* Sample code:
* ```
* $adGroupServiceClient = new AdGroupServiceClient();
* try {
* $formattedResourceName = $adGroupServiceClient->adGroupName('[CUSTOMER_ID]', '[AD_GROUP_ID]');
* $response = $adGroupServiceClient->getAdGroup($formattedResourceName);
* } finally {
* $adGroupServiceClient->close();
* }
* ```
*
* @param string $resourceName Required. The resource name of the ad group to fetch.
* @param array $optionalArgs {
* Optional.
*
* @type RetrySettings|array $retrySettings
* Retry settings to use for this call. Can be a
* {@see Google\ApiCore\RetrySettings} object, or an associative array of retry
* settings parameters. See the documentation on
* {@see Google\ApiCore\RetrySettings} for example usage.
* }
*
* @return \Google\Ads\GoogleAds\V8\Resources\AdGroup
*
* @throws ApiException if the remote call fails
*/
public function getAdGroup($resourceName, array $optionalArgs = [])
{
$request = new GetAdGroupRequest();
$requestParamHeaders = [];
$request->setResourceName($resourceName);
$requestParamHeaders['resource_name'] = $resourceName;
$requestParams = new RequestParamsHeaderDescriptor($requestParamHeaders);
$optionalArgs['headers'] = isset($optionalArgs['headers']) ? array_merge($requestParams->getHeader(), $optionalArgs['headers']) : $requestParams->getHeader();
return $this->startCall('GetAdGroup', AdGroup::class, $optionalArgs, $request)->wait();
}
/**
* Creates, updates, or removes ad groups. Operation statuses are returned.
*
* List of thrown errors:
* [AdGroupError]()
* [AdxError]()
* [AuthenticationError]()
* [AuthorizationError]()
* [BiddingError]()
* [BiddingStrategyError]()
* [DatabaseError]()
* [DateError]()
* [DistinctError]()
* [FieldError]()
* [FieldMaskError]()
* [HeaderError]()
* [IdError]()
* [InternalError]()
* [ListOperationError]()
* [MultiplierError]()
* [MutateError]()
* [NewResourceCreationError]()
* [NotEmptyError]()
* [NullError]()
* [OperationAccessDeniedError]()
* [OperatorError]()
* [QuotaError]()
* [RangeError]()
* [RequestError]()
* [ResourceCountLimitExceededError]()
* [SettingError]()
* [SizeLimitError]()
* [StringFormatError]()
* [StringLengthError]()
* [UrlFieldError]()
*
* Sample code:
* ```
* $adGroupServiceClient = new AdGroupServiceClient();
* try {
* $customerId = 'customer_id';
* $operations = [];
* $response = $adGroupServiceClient->mutateAdGroups($customerId, $operations);
* } finally {
* $adGroupServiceClient->close();
* }
* ```
*
* @param string $customerId Required. The ID of the customer whose ad groups are being modified.
* @param AdGroupOperation[] $operations Required. The list of operations to perform on individual ad groups.
* @param array $optionalArgs {
* Optional.
*
* @type bool $partialFailure
* If true, successful operations will be carried out and invalid
* operations will return errors. If false, all operations will be carried
* out in one transaction if and only if they are all valid.
* Default is false.
* @type bool $validateOnly
* If true, the request is validated but not executed. Only errors are
* returned, not results.
* @type int $responseContentType
* The response content type setting. Determines whether the mutable resource
* or just the resource name should be returned post mutation.
* For allowed values, use constants defined on {@see \Google\Ads\GoogleAds\V8\Enums\ResponseContentTypeEnum\ResponseContentType}
* @type RetrySettings|array $retrySettings
* Retry settings to use for this call. Can be a
* {@see Google\ApiCore\RetrySettings} object, or an associative array of retry
* settings parameters. See the documentation on
* {@see Google\ApiCore\RetrySettings} for example usage.
* }
*
* @return \Google\Ads\GoogleAds\V8\Services\MutateAdGroupsResponse
*
* @throws ApiException if the remote call fails
*/
public function mutateAdGroups($customerId, $operations, array $optionalArgs = [])
{
$request = new MutateAdGroupsRequest();
$requestParamHeaders = [];
$request->setCustomerId($customerId);
$request->setOperations($operations);
$requestParamHeaders['customer_id'] = $customerId;
if (isset($optionalArgs['partialFailure'])) {
$request->setPartialFailure($optionalArgs['partialFailure']);
}
if (isset($optionalArgs['validateOnly'])) {
$request->setValidateOnly($optionalArgs['validateOnly']);
}
if (isset($optionalArgs['responseContentType'])) {
$request->setResponseContentType($optionalArgs['responseContentType']);
}
$requestParams = new RequestParamsHeaderDescriptor($requestParamHeaders);
$optionalArgs['headers'] = isset($optionalArgs['headers']) ? array_merge($requestParams->getHeader(), $optionalArgs['headers']) : $requestParams->getHeader();
return $this->startCall('MutateAdGroups', MutateAdGroupsResponse::class, $optionalArgs, $request)->wait();
}
}
| googleads/google-ads-php | src/Google/Ads/GoogleAds/V8/Services/Gapic/AdGroupServiceGapicClient.php | PHP | apache-2.0 | 16,250 |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.6.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
import unittest
import kubernetes.client
from kubernetes.client.rest import ApiException
from kubernetes.client.models.v1beta1_cluster_role_list import V1beta1ClusterRoleList
class TestV1beta1ClusterRoleList(unittest.TestCase):
""" V1beta1ClusterRoleList unit test stubs """
def setUp(self):
pass
def tearDown(self):
pass
def testV1beta1ClusterRoleList(self):
"""
Test V1beta1ClusterRoleList
"""
model = kubernetes.client.models.v1beta1_cluster_role_list.V1beta1ClusterRoleList()
if __name__ == '__main__':
unittest.main()
| skuda/client-python | kubernetes/test/test_v1beta1_cluster_role_list.py | Python | apache-2.0 | 917 |
/*
* Copyright 2014-2020 Groupon, Inc
* Copyright 2020-2021 Equinix, Inc
* Copyright 2014-2021 The Billing Project, LLC
*
* The Billing Project 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.beatrix.integration;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.killbill.billing.ErrorCode;
import org.killbill.billing.ObjectType;
import org.killbill.billing.account.api.Account;
import org.killbill.billing.api.TestApiListener.NextEvent;
import org.killbill.billing.beatrix.util.InvoiceChecker.ExpectedInvoiceItemCheck;
import org.killbill.billing.catalog.api.BillingActionPolicy;
import org.killbill.billing.catalog.api.BillingPeriod;
import org.killbill.billing.catalog.api.PlanPhaseSpecifier;
import org.killbill.billing.catalog.api.ProductCategory;
import org.killbill.billing.entitlement.api.DefaultEntitlement;
import org.killbill.billing.entitlement.api.DefaultEntitlementSpecifier;
import org.killbill.billing.entitlement.api.Entitlement;
import org.killbill.billing.entitlement.api.Entitlement.EntitlementActionPolicy;
import org.killbill.billing.invoice.api.Invoice;
import org.killbill.billing.invoice.api.InvoiceApiException;
import org.killbill.billing.invoice.api.InvoiceItem;
import org.killbill.billing.invoice.api.InvoiceItemType;
import org.killbill.billing.invoice.api.InvoiceStatus;
import org.killbill.billing.invoice.model.CreditAdjInvoiceItem;
import org.killbill.billing.payment.api.Payment;
import org.killbill.billing.payment.api.PluginProperty;
import org.killbill.billing.subscription.api.user.DefaultSubscriptionBase;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
public class TestIntegrationVoidInvoice extends TestIntegrationBase {
@Test(groups = "slow")
public void testVoidInvoice() throws Exception {
final int billingDay = 14;
final DateTime initialCreationDate = new DateTime(2015, 5, 15, 0, 0, 0, 0, testTimeZone);
// set clock to the initial start date
clock.setTime(initialCreationDate);
log.info("Beginning test with BCD of " + billingDay);
final Account account = createAccountWithNonOsgiPaymentMethod(getAccountData(billingDay));
add_AUTO_PAY_OFF_Tag(account.getId(), ObjectType.ACCOUNT);
DefaultEntitlement baseEntitlement = createBaseEntitlementAndCheckForCompletion(account.getId(), "bundleKey", "Shotgun", ProductCategory.BASE, BillingPeriod.MONTHLY, NextEvent.CREATE, NextEvent.BLOCK, NextEvent.INVOICE);
DefaultSubscriptionBase subscription = subscriptionDataFromSubscription(baseEntitlement.getSubscriptionBase());
final List<ExpectedInvoiceItemCheck> expectedInvoices = new ArrayList<ExpectedInvoiceItemCheck>();
expectedInvoices.add(new ExpectedInvoiceItemCheck(new LocalDate(2015, 6, 14), new LocalDate(2015, 7, 14), InvoiceItemType.RECURRING, new BigDecimal("249.95")));
// Move through time and verify we get the same invoice
busHandler.pushExpectedEvents(NextEvent.PHASE, NextEvent.INVOICE);
clock.addDays(30);
assertListenerStatus();
List<Invoice> invoices = invoiceUserApi.getInvoicesByAccount(account.getId(), false, false, callContext);
invoiceChecker.checkInvoice(invoices.get(1).getId(), callContext, expectedInvoices);
// Void the invoice
busHandler.pushExpectedEvents(NextEvent.INVOICE_ADJUSTMENT);
invoiceUserApi.voidInvoice(invoices.get(1).getId(), callContext);
assertListenerStatus();
remove_AUTO_PAY_OFF_Tag(account.getId(), ObjectType.ACCOUNT);
// Move through time
busHandler.pushExpectedEvents(NextEvent.INVOICE, NextEvent.PAYMENT, NextEvent.INVOICE_PAYMENT);
clock.addDays(31);
assertListenerStatus();
// get all invoices including the VOIDED; includeVoidedInvoices = true;
invoices = invoiceUserApi.getInvoicesByAccount(account.getId(), false, true, callContext);
assertEquals(invoices.size(), 3);
// verify integrity of the voided
invoiceChecker.checkInvoice(invoices.get(1).getId(), callContext, expectedInvoices);
assertEquals(invoices.get(1).getStatus(), InvoiceStatus.VOID);
// verify that the new invoice contains current and VOIDED charge
expectedInvoices.add(new ExpectedInvoiceItemCheck(new LocalDate(2015, 7, 14), new LocalDate(2015, 8, 14), InvoiceItemType.RECURRING, new BigDecimal("249.95")));
invoiceChecker.checkInvoice(invoices.get(2).getId(), callContext, expectedInvoices);
// verify that the account balance is fully paid and a payment exists
final BigDecimal accountBalance = invoiceUserApi.getAccountBalance(account.getId(), callContext);
assertTrue(accountBalance.compareTo(BigDecimal.ZERO) == 0);
final List<Payment> payments = paymentApi.getAccountPayments(account.getId(), false, false, ImmutableList.<PluginProperty>of(), callContext);
assertEquals(payments.size(), 1);
final Payment payment = payments.get(0);
assertTrue(payment.getPurchasedAmount().compareTo(invoices.get(2).getChargedAmount()) == 0);
// try to void an invoice that is already paid, it should fail.
try {
invoiceUserApi.voidInvoice(invoices.get(2).getId(), callContext);
Assert.fail("Should fail to void invoice that is already paid");
} catch (final InvoiceApiException e) {
Assert.assertEquals(e.getCode(), ErrorCode.CAN_NOT_VOID_INVOICE_THAT_IS_PAID.getCode());
}
// Refund the payment
busHandler.pushExpectedEvents(NextEvent.PAYMENT, NextEvent.INVOICE_PAYMENT);
paymentApi.createRefundWithPaymentControl(account, payment.getId(), payment.getPurchasedAmount(), payment.getCurrency(), clock.getUTCNow(), null, PLUGIN_PROPERTIES, PAYMENT_OPTIONS, callContext);
assertListenerStatus();
busHandler.pushExpectedEvents(NextEvent.INVOICE_ADJUSTMENT);
invoiceUserApi.voidInvoice(invoices.get(2).getId(), callContext);
assertListenerStatus();
invoices = invoiceUserApi.getInvoicesByAccount(account.getId(), false, true, callContext);
assertEquals(invoices.size(), 3);
assertEquals(invoices.get(1).getStatus(), InvoiceStatus.VOID);
assertEquals(invoices.get(2).getStatus(), InvoiceStatus.VOID);
}
@Test(groups = "slow")
public void testVoidRepairedInvoice() throws Exception {
final DateTime initialDate = new DateTime(2013, 6, 15, 0, 0, 0, 0, testTimeZone);
final LocalDate startDate = initialDate.toLocalDate();
clock.setDeltaFromReality(initialDate.getMillis() - clock.getUTCNow().getMillis());
final Account account = createAccountWithNonOsgiPaymentMethod(getAccountData(15));
assertNotNull(account);
add_AUTO_PAY_OFF_Tag(account.getId(), ObjectType.ACCOUNT);
final PlanPhaseSpecifier spec = new PlanPhaseSpecifier("pistol-monthly-notrial");
busHandler.pushExpectedEvents(NextEvent.INVOICE);
final InvoiceItem inputCredit = new CreditAdjInvoiceItem(null, account.getId(), startDate, "credit invoice", new BigDecimal("20.00"), account.getCurrency(), null);
invoiceUserApi.insertCredits(account.getId(), startDate, ImmutableList.of(inputCredit), true, null, callContext);
assertListenerStatus();
final BigDecimal accountBalance1 = invoiceUserApi.getAccountBalance(account.getId(), callContext);
final BigDecimal accountCBA1 = invoiceUserApi.getAccountCBA(account.getId(), callContext);
busHandler.pushExpectedEvents(NextEvent.BLOCK, NextEvent.CREATE, NextEvent.INVOICE);
final UUID entitlementId = entitlementApi.createBaseEntitlement(account.getId(), new DefaultEntitlementSpecifier(spec, null, null, null), null, startDate, startDate, false, false, ImmutableList.<PluginProperty>of(), callContext);
final Entitlement bpEntitlement = entitlementApi.getEntitlementForId(entitlementId, callContext);
assertListenerStatus();
final Invoice invoice2 = invoiceChecker.checkInvoice(account.getId(), 2, callContext,
new ExpectedInvoiceItemCheck(new LocalDate(2013, 6, 15), new LocalDate(2013, 7, 15), InvoiceItemType.RECURRING, new BigDecimal("19.95")),
new ExpectedInvoiceItemCheck(new LocalDate(2013, 6, 15), new LocalDate(2013, 6, 15), InvoiceItemType.CBA_ADJ, new BigDecimal("-19.95")));
// 2013-07-01
clock.addDays(16);
busHandler.pushExpectedEvents(NextEvent.BLOCK, NextEvent.CANCEL, NextEvent.INVOICE);
bpEntitlement.cancelEntitlementWithPolicyOverrideBillingPolicy(EntitlementActionPolicy.IMMEDIATE, BillingActionPolicy.IMMEDIATE, ImmutableList.<PluginProperty>of(), callContext);
assertListenerStatus();
final Invoice invoice3 = invoiceChecker.checkInvoice(account.getId(), 3, callContext,
new ExpectedInvoiceItemCheck(new LocalDate(2013, 7, 1), new LocalDate(2013, 7, 15), InvoiceItemType.REPAIR_ADJ, new BigDecimal("-9.31")),
new ExpectedInvoiceItemCheck(new LocalDate(2013, 7, 1), new LocalDate(2013, 7, 1), InvoiceItemType.CBA_ADJ, new BigDecimal("9.31")));
// We disallow to void the invoice as it was repaired
try {
invoiceUserApi.voidInvoice(invoice2.getId(), callContext);
Assert.fail("Should fail to void a repaired invoice");
} catch (final RuntimeException e) {
assertTrue(e.getMessage().contains("because it contains items being repaired"));
}
// Void the invoice where the REPAIR_ADJ occurred first
busHandler.pushExpectedEvents(NextEvent.INVOICE_ADJUSTMENT);
invoiceUserApi.voidInvoice(invoice3.getId(), callContext);
assertListenerStatus();
// NOW check we allow voiding the invoice2
busHandler.pushExpectedEvents(NextEvent.INVOICE_ADJUSTMENT);
invoiceUserApi.voidInvoice(invoice2.getId(), callContext);
assertListenerStatus();
// We were left with an unstable state by VOIDing the previous periods....
busHandler.pushExpectedEvents(NextEvent.INVOICE);
invoiceUserApi.triggerInvoiceGeneration(account.getId(), clock.getUTCToday(), callContext);
assertListenerStatus();
invoiceChecker.checkInvoice(account.getId(), 2, callContext,
new ExpectedInvoiceItemCheck(new LocalDate(2013, 6, 15), new LocalDate(2013, 7, 1), InvoiceItemType.RECURRING, new BigDecimal("10.64")),
new ExpectedInvoiceItemCheck(new LocalDate(2013, 7, 1), new LocalDate(2013, 7, 1), InvoiceItemType.CBA_ADJ, new BigDecimal("-10.64")));
// 20 - 10.64 = 9.36
final BigDecimal accountBalance2 = invoiceUserApi.getAccountBalance(account.getId(), callContext);
Assert.assertEquals(accountBalance2.compareTo(new BigDecimal("-9.36")), 0);
final BigDecimal accountCBA2 = invoiceUserApi.getAccountCBA(account.getId(), callContext);
Assert.assertEquals(accountCBA2.compareTo(new BigDecimal("9.36")), 0);
checkNoMoreInvoiceToGenerate(account.getId());
}
} | killbill/killbill | beatrix/src/test/java/org/killbill/billing/beatrix/integration/TestIntegrationVoidInvoice.java | Java | apache-2.0 | 12,168 |
/*
* Licensed to Crate under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership. Crate 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.
*
* However, if you have executed another commercial license agreement
* with Crate these terms will supersede the license and you may use the
* software solely pursuant to the terms of the relevant commercial
* agreement.
*/
package io.crate.execution.ddl;
import io.crate.metadata.RelationName;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import java.io.IOException;
public final class RelationNameSwap implements Writeable {
private final RelationName source;
private final RelationName target;
public RelationNameSwap(RelationName source, RelationName target) {
this.source = source;
this.target = target;
}
public RelationNameSwap(StreamInput in) throws IOException {
this.source = new RelationName(in);
this.target = new RelationName(in);
}
public RelationName source() {
return source;
}
public RelationName target() {
return target;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
source.writeTo(out);
target.writeTo(out);
}
}
| EvilMcJerkface/crate | server/src/main/java/io/crate/execution/ddl/RelationNameSwap.java | Java | apache-2.0 | 1,976 |
/**
* 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
*
* 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 axios, { AxiosBasicCredentials, AxiosError, AxiosInstance } from 'axios';
import addOAuthInterceptor from 'axios-oauth-1.0a';
import { Request, Response } from 'express';
import firebase from 'firebase/app';
import * as fs from 'fs';
import {
BlockTwitterUsersRequest,
BlockTwitterUsersResponse,
GetTweetsRequest,
GetTweetsResponse,
HideRepliesTwitterRequest,
HideRepliesTwitterResponse,
MuteTwitterUsersRequest,
MuteTwitterUsersResponse,
Tweet,
TweetObject,
TwitterApiResponse,
} from '../../common-types';
import { TwitterApiCredentials } from '../serving';
// Max results per twitter call.
const BATCH_SIZE = 500;
interface TwitterApiRequest {
query: string;
maxResults?: number;
fromDate?: string;
toDate?: string;
next?: string;
}
export async function getTweets(
req: Request,
res: Response,
apiCredentials: TwitterApiCredentials
) {
let twitterDataPromise: Promise<TwitterApiResponse>;
if (fs.existsSync('src/server/twitter_sample_results.json')) {
twitterDataPromise = loadLocalTwitterData();
} else {
if (!enterpriseSearchCredentialsAreValid(apiCredentials)) {
res.send(new Error('Invalid Twitter Enterprise Search API credentials'));
return;
}
twitterDataPromise = loadTwitterData(apiCredentials, req.body);
}
try {
const twitterData = await twitterDataPromise;
const tweets = twitterData.results.map(parseTweet);
res.send({ tweets, nextPageToken: twitterData.next } as GetTweetsResponse);
} catch (e) {
console.error('Error loading Twitter data: ' + e);
res.status(500).send('Error loading Twitter data');
}
}
export async function blockTwitterUsers(
req: Request,
res: Response,
apiCredentials: TwitterApiCredentials
) {
if (!standardApiCredentialsAreValid(apiCredentials)) {
res.send(new Error('Invalid Twitter Standard API credentials'));
return;
}
const request = req.body as BlockTwitterUsersRequest;
const userCredential = firebase.auth.AuthCredential.fromJSON(
request.credential
) as firebase.auth.OAuthCredential;
const response = await blockUsers(apiCredentials, userCredential, request);
if (response.error) {
// All block API requests failed. Send an error.
res.status(500).send(response);
} else {
res.send(response);
}
}
export async function muteTwitterUsers(
req: Request,
res: Response,
apiCredentials: TwitterApiCredentials
) {
if (!standardApiCredentialsAreValid(apiCredentials)) {
res.send(new Error('Invalid Twitter Standard API credentials'));
return;
}
const request = req.body as MuteTwitterUsersRequest;
const userCredential = firebase.auth.AuthCredential.fromJSON(
request.credential
) as firebase.auth.OAuthCredential;
const response = await muteUsers(apiCredentials, userCredential, request);
if (response.error) {
// All mute API requests failed. Send an error.
res.status(500).send(response);
} else {
res.send(response);
}
}
export async function hideTwitterReplies(
req: Request,
res: Response,
apiCredentials: TwitterApiCredentials
) {
if (!standardApiCredentialsAreValid(apiCredentials)) {
res.send(new Error('Invalid Twitter Standard API credentials'));
return;
}
const request = req.body as HideRepliesTwitterRequest;
const userCredential = firebase.auth.AuthCredential.fromJSON(
request.credential
) as firebase.auth.OAuthCredential;
const response = await hideReplies(apiCredentials, userCredential, request);
if (response.error) {
// All hide reply API requests failed. Send an error.
res.status(500).send(response);
} else {
res.send(response);
}
}
async function blockUsers(
apiCredentials: TwitterApiCredentials,
userCredential: firebase.auth.OAuthCredential,
request: BlockTwitterUsersRequest
): Promise<BlockTwitterUsersResponse> {
const client = createAxiosInstance(apiCredentials, userCredential);
const requestUrl = 'https://api.twitter.com/1.1/blocks/create.json';
const response: BlockTwitterUsersResponse = {};
const requests = request.users.map(user =>
client
.post<BlockTwitterUsersResponse>(
requestUrl,
{},
{ params: { screen_name: user } }
)
.catch(e => {
console.error(`Unable to block Twitter user: @${user} because ${e}`);
response.failedScreennames = [
...(response.failedScreennames ?? []),
user,
];
})
);
await Promise.all(requests);
if (request.users.length === response.failedScreennames?.length) {
response.error = 'Unable to block Twitter users';
}
return response;
}
async function muteUsers(
apiCredentials: TwitterApiCredentials,
userCredential: firebase.auth.OAuthCredential,
request: MuteTwitterUsersRequest
): Promise<MuteTwitterUsersResponse> {
const client = createAxiosInstance(apiCredentials, userCredential);
const requestUrl = 'https://api.twitter.com/1.1/mutes/users/create.json';
const response: MuteTwitterUsersResponse = {};
const requests = request.users.map(user =>
client
.post<MuteTwitterUsersResponse>(
requestUrl,
{},
{ params: { screen_name: user } }
)
.catch(e => {
console.error(`Unable to mute Twitter user: @${user} because ${e}`);
response.failedScreennames = [
...(response.failedScreennames ?? []),
user,
];
})
);
await Promise.all(requests);
if (request.users.length === response.failedScreennames?.length) {
response.error = 'Unable to mute Twitter users';
}
return response;
}
async function hideReplies(
apiCredentials: TwitterApiCredentials,
userCredential: firebase.auth.OAuthCredential,
request: HideRepliesTwitterRequest
): Promise<HideRepliesTwitterResponse> {
const client = createAxiosInstance(apiCredentials, userCredential);
const response: HideRepliesTwitterResponse = {};
let quotaExhaustedErrors = 0;
let otherErrors = 0;
const requests = request.tweetIds.map(id =>
client
.put<HideRepliesTwitterResponse>(
`https://api.twitter.com/2/tweets/${id}/hidden`,
{ hidden: true }
)
.catch((e: AxiosError) => {
console.error(`Unable to hide tweet ID: ${id} because ${e}`);
if (
e.response?.status === 429 ||
e.response?.statusText.includes('Too Many Requests')
) {
quotaExhaustedErrors += 1;
} else {
otherErrors += 1;
}
})
);
await Promise.all(requests);
response.numQuotaFailures = quotaExhaustedErrors;
response.numOtherFailures = otherErrors;
if (otherErrors === request.tweetIds.length) {
response.error = 'Unable to hide replies';
}
return response;
}
function loadTwitterData(
credentials: TwitterApiCredentials,
request: GetTweetsRequest
): Promise<TwitterApiResponse> {
const requestUrl = `https://gnip-api.twitter.com/search/fullarchive/accounts/${credentials.accountName}/prod.json`;
// These are the *user's* credentials for Twitter.
const user = request.credentials?.additionalUserInfo?.username;
if (!user) {
throw new Error('No user credentials in GetTweetsRequest');
}
const twitterApiRequest: TwitterApiRequest = {
query: `(@${user} OR url:twitter.com/${user}) -from:${user} -is:retweet`,
maxResults: BATCH_SIZE,
};
if (request.fromDate) {
twitterApiRequest.fromDate = request.fromDate;
}
if (request.toDate) {
twitterApiRequest.toDate = request.toDate;
}
if (request.nextPageToken) {
twitterApiRequest.next = request.nextPageToken;
}
const auth: AxiosBasicCredentials = {
username: credentials!.username,
password: credentials!.password,
};
return axios
.post<TwitterApiResponse>(requestUrl, twitterApiRequest, { auth })
.then(response => response.data)
.catch(error => {
const errorStr =
`Error while fetching tweets with request ` +
`${JSON.stringify(request)}: ${error}`;
throw new Error(errorStr);
});
}
function loadLocalTwitterData(): Promise<TwitterApiResponse> {
return fs.promises
.readFile('src/server/twitter_sample_results.json')
.then((data: Buffer) => {
// Remove the `next` page token so the client doesn't infinitely issue
// requests for a next page of data.
const response = JSON.parse(data.toString()) as TwitterApiResponse;
response.next = '';
return response;
});
}
function enterpriseSearchCredentialsAreValid(
credentials: TwitterApiCredentials
): boolean {
return (
!!credentials.accountName &&
!!credentials.username &&
!!credentials.password
);
}
function standardApiCredentialsAreValid(
credentials: TwitterApiCredentials
): boolean {
return !!credentials.appKey && !!credentials.appToken;
}
function createAxiosInstance(
apiCredentials: TwitterApiCredentials,
userCredential: firebase.auth.OAuthCredential
): AxiosInstance {
const token = userCredential.accessToken;
const tokenSecret = userCredential.secret;
if (!token || !tokenSecret) {
throw new Error('Twitter user access token and secret are missing');
}
const client = axios.create();
// Add OAuth 1.0a credentials.
addOAuthInterceptor(client, {
algorithm: 'HMAC-SHA1',
key: apiCredentials.appKey,
includeBodyHash: false,
secret: apiCredentials.appToken,
token,
tokenSecret,
});
return client;
}
function parseTweet(tweetObject: TweetObject): Tweet {
// Still pass the rest of the metadata in case we want to use it
// later, but surface the comment in a top-level field.
//
// Firestore doesn't support writing nested arrays, so we have to
// manually build the Tweet object to avoid accidentally including the nested
// arrays in the TweetObject from the Twitter API response.
const tweet: Tweet = {
created_at: tweetObject.created_at,
date: new Date(),
display_text_range: tweetObject.display_text_range,
entities: tweetObject.entities,
extended_entities: tweetObject.extended_entities,
extended_tweet: tweetObject.extended_tweet,
favorite_count: tweetObject.favorite_count,
favorited: tweetObject.favorited,
in_reply_to_status_id: tweetObject.in_reply_to_status_id,
id_str: tweetObject.id_str,
lang: tweetObject.lang,
reply_count: tweetObject.reply_count,
retweet_count: tweetObject.retweet_count,
retweeted_status: tweetObject.retweeted_status,
source: tweetObject.source,
text: tweetObject.text,
truncated: tweetObject.truncated,
url: `https://twitter.com/i/web/status/${tweetObject.id_str}`,
user: tweetObject.user,
};
if (tweetObject.truncated && tweetObject.extended_tweet) {
tweet.text = tweetObject.extended_tweet.full_text;
}
if (tweetObject.created_at) {
tweet.date = new Date(tweetObject.created_at);
}
if (tweetObject.user) {
tweet.authorName = tweetObject.user.name;
tweet.authorScreenName = tweetObject.user.screen_name;
tweet.authorUrl = `https://twitter.com/${tweetObject.user.screen_name}`;
tweet.authorAvatarUrl = tweetObject.user.profile_image_url;
tweet.verified = tweetObject.user.verified;
}
if (tweetObject.extended_entities && tweetObject.extended_entities.media) {
tweet.hasImage = true;
}
return tweet;
}
| conversationai/harassment-manager | src/server/middleware/twitter.middleware.ts | TypeScript | apache-2.0 | 11,910 |
/**
* 添加教师js,主要处理积点的问题。
* 分模块化
* Created by admin on 2016/9/26.
*/
$(function(){
//第一个问题
var work_load = $('#is_work_load').val();
$("#work_load input[type='checkbox']").live('click', function(e){
var is_work_load = $(this).val();
if($(this).is(':checked') && is_work_load == 1){
$("#is_work_load").val(1);
$('#work_load').find(".no").attr('checked', false);
$('#work_load').find(".yes").attr('checked', true);
}else{
$("#is_work_load").val(0);
$('#work_load').find(".no").attr('checked', true);
$('#work_load').find(".yes").attr('checked', false);
}
});
//第二个问题
var teaching_good = $('#is_teaching_good').val();
$("#teaching_good input[type='checkbox']").live('click', function(e){
var is_teaching_good = $(this).val();
if($(this).is(':checked') && is_teaching_good == 1){
$("#is_teaching_good").val(1);
$('#teaching_good').find(".no").attr('checked', false);
$('#teaching_good').find(".yes").attr('checked', true);
}else{
$("#is_teaching_good").val(0);
$('#teaching_good').find(".no").attr('checked', true);
$('#teaching_good').find(".yes").attr('checked', false);
}
});
//第三个问题
var teaching_behavior = $('#is_teaching_behavior').val();
$("#teaching_behavior input[type='checkbox']").live('click', function(e){
var is_teaching_behavior = $(this).val();
if($(this).is(':checked') && is_teaching_behavior == 1){
$("#is_teaching_behavior").val(1);
$('#teaching_behavior').find(".no").attr('checked', false);
$('#teaching_behavior').find(".yes").attr('checked', true);
}else{
$("#is_teaching_behavior").val(0);
$('#teaching_behavior').find(".no").attr('checked', true);
$('#teaching_behavior').find(".yes").attr('checked', false);
}
});
//第四个问题
var student_statis = $('#is_student_statis').val();
$("#student_statis input[type='checkbox']").live('click', function(e){
var is_student_statis = $(this).val();
if($(this).is(':checked') && is_student_statis == 1){
$("#is_student_statis").val(1);
$('#student_statis').find(".no").attr('checked', false);
$('#student_statis').find(".yes").attr('checked', true);
}else{
$("#is_student_statis").val(0);
$('#student_statis').find(".no").attr('checked', true);
$('#student_statis').find(".yes").attr('checked', false);
}
});
//第五个问题
var subject_good = $('#is_subject_good').val();
$("#subject_good input[type='checkbox']").live('click', function(e){
var is_subject_good = $(this).val();
if($(this).is(':checked') && is_subject_good == 1){
$("#is_subject_good").val(1);
$('#subject_good').find(".no").attr('checked', false);
$('#subject_good').find(".yes").attr('checked', true);
}else{
$("#is_subject_good").val(0);
$('#subject_good').find(".no").attr('checked', true);
$('#subject_good').find(".yes").attr('checked', false);
}
});
//第六个问题
var academic = $('#is_academic').val();
$("#academic input[type='checkbox']").live('click', function(e){
var is_academic = $(this).val();
if($(this).is(':checked') && is_academic == 1){
$("#is_academic").val(1);
$('#academic').find(".no").attr('checked', false);
$('#academic').find(".yes").attr('checked', true);
}else{
$("#is_academic").val(0);
$('#academic').find(".no").attr('checked', true);
$('#academic').find(".yes").attr('checked', false);
}
});
//第七个问题
var organ_sub = $('#is_organ_sub').val();
$("#organ_sub input[type='checkbox']").live('click', function(e){
var is_organ_sub = $(this).val();
if($(this).is(':checked') && is_organ_sub == 1){
$("#is_organ_sub").val(1);
$('#organ_sub').find(".no").attr('checked', false);
$('#organ_sub').find(".yes").attr('checked', true);
}else{
$("#is_organ_sub").val(0);
$('#organ_sub').find(".no").attr('checked', true);
$('#organ_sub').find(".yes").attr('checked', false);
}
});
//第八个问题
var school_forum = $('#is_school_forum').val();
$("#school_forum input[type='checkbox']").live('click', function(e){
var is_school_forum = $(this).val();
if($(this).is(':checked') && is_school_forum == 1){
$("#is_school_forum").val(1);
$('#school_forum').find(".no").attr('checked', false);
$('#school_forum').find(".yes").attr('checked', true);
}else{
$("#is_school_forum").val(0);
$('#school_forum').find(".no").attr('checked', true);
$('#school_forum').find(".yes").attr('checked', false);
}
});
//第九个问题
var backtone_teacher = $('#is_backtone_teacher').val();
$("#backtone_teacher input[type='checkbox']").live('click', function(e){
var is_backtone_teacher = $(this).val();
if($(this).is(':checked') && is_backtone_teacher == 1){
$("#is_backtone_teacher").val(1);
$('#backtone_teacher').find(".no").attr('checked', false);
$('#backtone_teacher').find(".yes").attr('checked', true);
}else{
$("#is_backtone_teacher").val(0);
$('#backtone_teacher').find(".no").attr('checked', true);
$('#backtone_teacher').find(".yes").attr('checked', false);
}
});
//第10个问题
var teach_intern = $('#is_teach_intern').val();
$("#teach_intern input[type='checkbox']").live('click', function(e){
var is_teach_intern = $(this).val();
if($(this).is(':checked') && is_teach_intern == 1){
$("#is_teach_intern").val(1);
$('#teach_intern').find(".no").attr('checked', false);
$('#teach_intern').find(".yes").attr('checked', true);
}else{
$("#is_teach_intern").val(0);
$('#teach_intern').find(".no").attr('checked', true);
$('#teach_intern').find(".yes").attr('checked', false);
}
});
//第11个问题
var person_write = $('#is_person_write').val();
$("#person_write input[type='checkbox']").live('click', function(e){
var is_person_write = $(this).val();
if($(this).is(':checked') && is_person_write == 1){
$("#is_teach_intern").val(1);
$('#person_write').find(".no").attr('checked', false);
$('#person_write').find(".yes").attr('checked', true);
}else{
$("#is_person_write").val(0);
$('#person_write').find(".no").attr('checked', true);
$('#person_write').find(".yes").attr('checked', false);
}
});
//第12个问题
var semester = $('#is_semester').val();
$("#semester input[type='checkbox']").live('click', function(e){
var is_semester = $(this).val();
if($(this).is(':checked') && is_semester == 1){
$("#is_teach_intern").val(1);
$('#semester').find(".no").attr('checked', false);
$('#semester').find(".yes").attr('checked', true);
}else{
$("#is_semester").val(0);
$('#semester').find(".no").attr('checked', true);
$('#semester').find(".yes").attr('checked', false);
}
});
//第13个问题
var head_teacher = $('#is_head_teacher').val();
$("#head_teacher input[type='checkbox']").live('click', function(e){
var is_head_teacher = $(this).val();
if($(this).is(':checked') && is_head_teacher == 1){
$("#is_head_teacher").val(1);
$('#head_teacher').find(".no").attr('checked', false);
$('#head_teacher').find(".yes").attr('checked', true);
}else{
$("#is_head_teacher").val(0);
$('#head_teacher').find(".no").attr('checked', true);
$('#head_teacher').find(".yes").attr('checked', false);
}
});
//第14个问题
var learning_exper = $('#is_learning_exper').val();
$("#learning_exper input[type='checkbox']").live('click', function(e){
var is_learning_exper = $(this).val();
if($(this).is(':checked') && is_learning_exper == 1){
$("#is_learning_exper").val(1);
$('#learning_exper').find(".no").attr('checked', false);
$('#learning_exper').find(".yes").attr('checked', true);
}else{
$("#is_learning_exper").val(0);
$('#learning_exper').find(".no").attr('checked', true);
$('#learning_exper').find(".yes").attr('checked', false);
}
});
//第15个问题
var class_meeting = $('#is_class_meeting').val();
$("#class_meeting input[type='checkbox']").live('click', function(e){
var is_class_meeting = $(this).val();
if($(this).is(':checked') && is_class_meeting == 1){
$("#is_class_meeting").val(1);
$('#class_meeting').find(".no").attr('checked', false);
$('#class_meeting').find(".yes").attr('checked', true);
}else{
$("#is_class_meeting").val(0);
$('#class_meeting').find(".no").attr('checked', true);
$('#class_meeting').find(".yes").attr('checked', false);
}
});
//第16个问题
var good_head_teacher = $('#is_good_head_teacher').val();
$("#good_head_teacher input[type='checkbox']").live('click', function(e){
var is_good_head_teacher = $(this).val();
if($(this).is(':checked') && is_good_head_teacher == 1){
$("#is_good_head_teacher").val(1);
$('#good_head_teacher').find(".no").attr('checked', false);
$('#good_head_teacher').find(".yes").attr('checked', true);
}else{
$("#is_good_head_teacher").val(0);
$('#good_head_teacher').find(".no").attr('checked', true);
$('#good_head_teacher').find(".yes").attr('checked', false);
}
});
//第17个问题
var fes_activity = $('#is_fes_activity').val();
$("#fes_activity input[type='checkbox']").live('click', function(e){
var is_fes_activity = $(this).val();
if($(this).is(':checked') && is_fes_activity == 1){
$("#is_fes_activity").val(1);
$('#fes_activity').find(".no").attr('checked', false);
$('#fes_activity').find(".yes").attr('checked', true);
}else{
$("#is_fes_activity").val(0);
$('#fes_activity').find(".no").attr('checked', true);
$('#fes_activity').find(".yes").attr('checked', false);
}
});
//第18个问题
var work_for_school = $('#is_work_for_school').val();
$("#work_for_school input[type='checkbox']").live('click', function(e){
var is_work_for_school = $(this).val();
if($(this).is(':checked') && is_work_for_school == 1){
$("#is_work_for_school").val(1);
$('#work_for_school').find(".no").attr('checked', false);
$('#work_for_school').find(".yes").attr('checked', true);
}else{
$("#is_work_for_school").val(0);
$('#work_for_school').find(".no").attr('checked', true);
$('#work_for_school').find(".yes").attr('checked', false);
}
});
//第19个问题
var manange_school = $('#is_manange_school').val();
$("#manange_school input[type='checkbox']").live('click', function(e){
var is_manange_school = $(this).val();
if($(this).is(':checked') && is_manange_school == 1){
$("#is_manange_school").val(1);
$('#manange_school').find(".no").attr('checked', false);
$('#manange_school').find(".yes").attr('checked', true);
}else{
$("#is_manange_school").val(0);
$('#manange_school').find(".no").attr('checked', true);
$('#manange_school').find(".yes").attr('checked', false);
}
});
//第20个问题
var research_school = $('#is_research_school').val();
$("#research_school input[type='checkbox']").live('click', function(e){
var is_research_school = $(this).val();
if($(this).is(':checked') && is_research_school == 1){
$("#is_research_school").val(1);
$('#research_school').find(".no").attr('checked', false);
$('#research_school').find(".yes").attr('checked', true);
}else{
$("#is_research_school").val(0);
$('#research_school').find(".no").attr('checked', true);
$('#research_school').find(".yes").attr('checked', false);
}
});
});
| lnc2014/school | template/js/add_per.js | JavaScript | apache-2.0 | 13,016 |
// Copyright 2009-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#include "AlphaCompositeTileOperation.h"
#include <memory>
#include "../../fb/DistributedFrameBuffer.h"
#include "fb/DistributedFrameBuffer_ispc.h"
namespace ospray {
struct BufferedTile
{
ospray::Tile tile;
/*! determines order of this tile relative to other tiles.
Tiles will get blended with the 'over' operator in
increasing 'BufferedTile::sortOrder' value */
float sortOrder;
};
/* LiveTileOperation for data-parallel or hybrid-parallel rendering, where
* different (or partially shared) data is rendered on each rank
*/
struct LiveAlphaCompositeTile : public LiveTileOperation
{
LiveAlphaCompositeTile(DistributedFrameBuffer *dfb,
const vec2i &begin,
size_t tileID,
size_t ownerID);
void newFrame() override;
void process(const ospray::Tile &tile) override;
private:
std::vector<std::unique_ptr<BufferedTile>> bufferedTiles;
int currentGeneration;
int expectedInNextGeneration;
int missingInCurrentGeneration;
std::mutex mutex;
void reportCompositingError(const vec2i &tile);
};
LiveAlphaCompositeTile::LiveAlphaCompositeTile(DistributedFrameBuffer *dfb,
const vec2i &begin,
size_t tileID,
size_t ownerID)
: LiveTileOperation(dfb, begin, tileID, ownerID)
{}
void LiveAlphaCompositeTile::newFrame()
{
std::lock_guard<std::mutex> lock(mutex);
currentGeneration = 0;
expectedInNextGeneration = 0;
missingInCurrentGeneration = 1;
if (!bufferedTiles.empty()) {
handleError(OSP_INVALID_OPERATION,
std::to_string(mpicommon::workerRank())
+ " is starting with buffered tiles!");
}
}
void LiveAlphaCompositeTile::process(const ospray::Tile &tile)
{
std::lock_guard<std::mutex> lock(mutex);
{
auto addTile = rkcommon::make_unique<BufferedTile>();
std::memcpy(&addTile->tile, &tile, sizeof(tile));
bufferedTiles.push_back(std::move(addTile));
}
if (tile.generation == currentGeneration) {
--missingInCurrentGeneration;
expectedInNextGeneration += tile.children;
if (missingInCurrentGeneration < 0) {
reportCompositingError(tile.region.lower);
}
while (missingInCurrentGeneration == 0 && expectedInNextGeneration > 0) {
currentGeneration++;
missingInCurrentGeneration = expectedInNextGeneration;
expectedInNextGeneration = 0;
for (uint32_t i = 0; i < bufferedTiles.size(); i++) {
const BufferedTile *bt = bufferedTiles[i].get();
if (bt->tile.generation == currentGeneration) {
--missingInCurrentGeneration;
expectedInNextGeneration += bt->tile.children;
}
if (missingInCurrentGeneration < 0) {
reportCompositingError(tile.region.lower);
}
}
}
}
if (missingInCurrentGeneration < 0) {
reportCompositingError(tile.region.lower);
}
if (missingInCurrentGeneration == 0) {
// Sort for back-to-front blending
std::sort(bufferedTiles.begin(),
bufferedTiles.end(),
[](const std::unique_ptr<BufferedTile> &a,
const std::unique_ptr<BufferedTile> &b) {
return a->tile.sortOrder > b->tile.sortOrder;
});
Tile **tileArray = STACK_BUFFER(Tile *, bufferedTiles.size());
std::transform(bufferedTiles.begin(),
bufferedTiles.end(),
tileArray,
[](std::unique_ptr<BufferedTile> &t) { return &t->tile; });
ispc::DFB_sortAndBlendFragments(
(ispc::VaryingTile **)tileArray, bufferedTiles.size());
finished.region = tile.region;
finished.fbSize = tile.fbSize;
finished.rcp_fbSize = tile.rcp_fbSize;
accumulate(bufferedTiles[0]->tile);
bufferedTiles.clear();
tileIsFinished();
}
}
void LiveAlphaCompositeTile::reportCompositingError(const vec2i &tile)
{
std::stringstream str;
str << "negative missing on " << mpicommon::workerRank()
<< ", missing = " << missingInCurrentGeneration
<< ", expectedInNex = " << expectedInNextGeneration
<< ", current generation = " << currentGeneration << ", tile = " << tile;
handleError(OSP_INVALID_OPERATION, str.str());
}
std::shared_ptr<LiveTileOperation> AlphaCompositeTileOperation::makeTile(
DistributedFrameBuffer *dfb,
const vec2i &tileBegin,
size_t tileID,
size_t ownerID)
{
return std::make_shared<LiveAlphaCompositeTile>(
dfb, tileBegin, tileID, ownerID);
}
std::string AlphaCompositeTileOperation::toString() const
{
return "ospray::AlphaCompositeTileOperation";
}
} // namespace ospray
| ospray/OSPRay | modules/mpi/ospray/render/distributed/AlphaCompositeTileOperation.cpp | C++ | apache-2.0 | 4,549 |
/*
* Copyright 2020 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.services.clientpolicy;
/**
* Events on which client policies mechanism detects and do its operation
*
* @author <a href="mailto:takashi.norimatsu.ws@hitachi.com">Takashi Norimatsu</a>
*/
public enum ClientPolicyEvent {
REGISTER,
REGISTERED,
UPDATE,
UPDATED,
VIEW,
UNREGISTER,
AUTHORIZATION_REQUEST,
TOKEN_REQUEST,
SERVICE_ACCOUNT_TOKEN_REQUEST,
TOKEN_REFRESH,
TOKEN_REVOKE,
TOKEN_INTROSPECT,
USERINFO_REQUEST,
LOGOUT_REQUEST,
BACKCHANNEL_AUTHENTICATION_REQUEST,
BACKCHANNEL_TOKEN_REQUEST,
PUSHED_AUTHORIZATION_REQUEST,
DEVICE_AUTHORIZATION_REQUEST,
DEVICE_TOKEN_REQUEST
}
| pedroigor/keycloak | server-spi/src/main/java/org/keycloak/services/clientpolicy/ClientPolicyEvent.java | Java | apache-2.0 | 1,353 |
# -*- coding:utf-8 -*-
from test_stub import *
class HOST(MINI):
def __init__(self, uri=None, initialized=False):
self.host_name = None
self.host_list = []
if initialized:
# if initialized is True, uri should not be None
self.uri = uri
return
super(HOST, self).__init__()
def host_ops(self, host_name, action, details_page=False):
self.navigate('minihost')
host_list = []
if isinstance(host_name, types.ListType):
host_list = host_name
else:
host_list.append(host_name)
ops_list = {'enable': u'启用',
'disable': u'停用',
'reconnect': u'重连',
'maintenance': u'维护模式',
'light': u'识别灯亮'}
test_util.test_logger('Host (%s) execute action[%s]' % (' '.join(host_list), action))
for host in host_list:
for elem in self.get_elements('ant-row-flex-middle'):
if host in elem.text:
if not details_page:
if not elem.get_element(CHECKBOX).selected:
elem.get_element(CHECKBOX).click()
else:
elem.get_element('left-part').click()
time.sleep(1)
break
if details_page:
self.get_element(MOREOPERATIONBTN).click()
time.sleep(1)
self.operate(ops_list[action])
else:
if action in ['enable', 'disable']:
self.click_button(ops_list[action])
else:
self.get_element(MOREOPERATIONBTN).click()
time.sleep(1)
self.operate(ops_list[action])
self.wait_for_element(MESSAGETOAST, timeout=300, target='disappear')
| zstackio/zstack-woodpecker | integrationtest/vm/e2e_mini/host/host.py | Python | apache-2.0 | 1,882 |
var THREE = require('three');
var cgaprocessor = require('./cgaprocessor')
// function t(sizes, size, repeat) {
// console.log(sizes, size, repeat);
// console.log(cgaprocessor._compute_splits( sizes, size, repeat ));
// }
// t([ { size: 2 } ], 4, true);
// t([ { size: 2 } ], 5, true);
// t([ { size: 2 }, { size: 2 } ], 4, true);
// t([ { size: 2 }, { size: 2 } ], 5, true);
// t([ { size: 2, _float: true }, { size: 2 } ], 3, true);
// t([ { size: 2 }, { size: 2, _float: true }, { size: 2 } ], 4.5, true);
// t([ { size: 2 }, { size: 1, _float: true }, { size: 2, _float: true }, { size: 2 } ], 4.5, true);
//var preg = new THREE.BoxGeometry(2,2,2);
var preg = new THREE.Geometry();
preg.vertices.push(new THREE.Vector3(0,0,0),
new THREE.Vector3(1,1,0),
new THREE.Vector3(2,0,0));
preg.faces.push(new THREE.Face3(0,1,2));
//preg.translate(2,0,0);
// var preg = new THREE.Geometry();
// preg.vertices.push(new THREE.Vector3(-1,0,0),
// new THREE.Vector3(-1,1,0),
// new THREE.Vector3(1,0,0));
// preg.faces.push(new THREE.Face3(0,1,2));
// preg.translate(2,0,0);
preg.computeBoundingBox();
console.dir(preg.boundingBox);
console.log(preg.vertices.length, preg.faces.length);
debugger;
var g = cgaprocessor.split_geometry('x', preg, 0.5, 1.5);
g.computeBoundingBox();
console.dir(g.boundingBox);
console.log(g.vertices.length, g.faces.length);
g.vertices.forEach( v => console.log(v) );
g.faces.forEach( v => console.log(v.a,v.b,v.c) );
| gromgull/cgajs | test/test_splitting.js | JavaScript | apache-2.0 | 1,531 |
require 'docker_paas/family/common'
module Docker_paas; module Family
class Test < Common
def test_target
assert_env 'TEST_TARGET', ['puppet']
end
def short_tag
test_target
end
def early_run
assert_env 'DIST', ['stretch']
super + [
# octocatalog-diff is not in stretch, take it from sid
'head -1 /etc/apt/sources.list | sed s/stretch/sid/ > /etc/apt/sources.list.d/sid.list &&',
"echo 'APT::Default-Release \"stretch\";' > /etc/apt/apt.conf.d/default-release &&",
]
end
def packages
super + [
'git',
'octocatalog-diff',
'puppet-lint',
'r10k',
'rgxg',
'ruby-puppetlabs-spec-helper',
'ruby-puppet-syntax',
'ruby-rspec-puppet',
]
end
def after_run
[
'USER nobody',
]
end
end
end; end
| nantesmetropole/docker-paas | lib/docker_paas/family/test.rb | Ruby | apache-2.0 | 880 |
import { Entity } from '../entity/entity';
/*******************************************************************************************************************************************************************************************************
*
* @data FragmentType - FragmentType inherited from Entity it is a specific type of a LevelGraphNode
*
* Entity
* @superFields - id: number - ID of the FragmentType
* @superFields - name: string - Name of the FragmentType
* @superFields - expectedProperties: ExpectedProperty[] - Array of expected properties of the FragmentType
* @superFields - providedProperties: ProvidedProperty[] - Array of provided properties of the FragmentType
*
* @author Arthur Kaul
*
******************************************************************************************************************************************************************************************************/
export class FragmentType extends Entity {
constructor() {
super();
}
}
| kaular/ArchRef | ArchRefClient/ArchRefClient/src/app/shared/datamodels/types/fragmenttype.ts | TypeScript | apache-2.0 | 1,002 |
// Copyright (C) 2015 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.extensions.events;
import com.google.common.flogger.FluentLogger;
import com.google.gerrit.entities.PatchSet;
import com.google.gerrit.exceptions.StorageException;
import com.google.gerrit.extensions.api.changes.NotifyHandling;
import com.google.gerrit.extensions.common.AccountInfo;
import com.google.gerrit.extensions.common.ChangeInfo;
import com.google.gerrit.extensions.common.RevisionInfo;
import com.google.gerrit.extensions.events.ChangeRestoredListener;
import com.google.gerrit.server.GpgException;
import com.google.gerrit.server.account.AccountState;
import com.google.gerrit.server.patch.PatchListNotAvailableException;
import com.google.gerrit.server.patch.PatchListObjectTooLargeException;
import com.google.gerrit.server.permissions.PermissionBackendException;
import com.google.gerrit.server.plugincontext.PluginSetContext;
import com.google.gerrit.server.query.change.ChangeData;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.io.IOException;
import java.time.Instant;
/** Helper class to fire an event when a change has been restored. */
@Singleton
public class ChangeRestored {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private final PluginSetContext<ChangeRestoredListener> listeners;
private final EventUtil util;
@Inject
ChangeRestored(PluginSetContext<ChangeRestoredListener> listeners, EventUtil util) {
this.listeners = listeners;
this.util = util;
}
public void fire(
ChangeData changeData, PatchSet ps, AccountState restorer, String reason, Instant when) {
if (listeners.isEmpty()) {
return;
}
try {
Event event =
new Event(
util.changeInfo(changeData),
util.revisionInfo(changeData.project(), ps),
util.accountInfo(restorer),
reason,
when);
listeners.runEach(l -> l.onChangeRestored(event));
} catch (PatchListObjectTooLargeException e) {
logger.atWarning().log("Couldn't fire event: %s", e.getMessage());
} catch (PatchListNotAvailableException
| GpgException
| IOException
| StorageException
| PermissionBackendException e) {
logger.atSevere().withCause(e).log("Couldn't fire event");
}
}
/** Event to be fired when a change has been restored. */
private static class Event extends AbstractRevisionEvent implements ChangeRestoredListener.Event {
private String reason;
Event(
ChangeInfo change,
RevisionInfo revision,
AccountInfo restorer,
String reason,
Instant when) {
super(change, revision, restorer, when, NotifyHandling.ALL);
this.reason = reason;
}
@Override
public String getReason() {
return reason;
}
}
}
| GerritCodeReview/gerrit | java/com/google/gerrit/server/extensions/events/ChangeRestored.java | Java | apache-2.0 | 3,450 |
package net.safedata.spring.boot.training.solace.publisher;
import net.safedata.spring.boot.training.solace.channel.OutboundChannels;
import net.safedata.spring.boot.training.solace.event.AddProductToOrderCommand;
import net.safedata.spring.boot.training.solace.event.OrderUpdatedEvent;
import net.safedata.spring.boot.training.solace.message.MessageCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.stereotype.Component;
@Component
@EnableBinding(OutboundChannels.class)
public class MessagePublisher {
private final OutboundChannels outboundChannels;
@Autowired
public MessagePublisher(final OutboundChannels outboundChannels) {
this.outboundChannels = outboundChannels;
}
public void publishAddProductToOrderEvent(final AddProductToOrderCommand addProductToOrderCommand) {
outboundChannels.addProductToOrder()
.send(MessageCreator.create(addProductToOrderCommand));
}
public void publishOrderUpdatedEvent(final OrderUpdatedEvent orderUpdatedEvent) {
outboundChannels.orderUpdated()
.send(MessageCreator.create(orderUpdatedEvent));
}
}
| bogdansolga/spring-boot-training | d04/d04s01-async-processing/d04s01e05-async-messaging-using-solace/d04s01e05-product-publisher/src/main/java/net/safedata/spring/boot/training/solace/publisher/MessagePublisher.java | Java | apache-2.0 | 1,255 |
package cn.demoz.www.adapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import java.util.List;
import cn.demoz.www.holder.BaseHolder;
import cn.demoz.www.holder.MoreHolder;
import cn.demoz.www.manager.ThreadManager;
import cn.demoz.www.tools.UiUtils;
public abstract class DefaultAdapter<Data> extends BaseAdapter implements OnItemClickListener {
protected List<Data> datas;
private static final int DEFAULT_ITEM = 0;
private static final int MORE_ITEM = 1;
private ListView lv;
public List<Data> getDatas() {
return datas;
}
public void setDatas(List<Data> datas) {
this.datas = datas;
}
public DefaultAdapter(List<Data> datas, ListView lv) {
this.datas = datas;
// 给ListView设置条目的点击事件
lv.setOnItemClickListener(this);
this.lv = lv;
}
// ListView 条目点击事件回调的方法
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
//Toast.makeText(UiUtils.getContext(), "position:"+position, 0).show();
position = position - lv.getHeaderViewsCount();// 获取到顶部条目的数量 位置去掉顶部view的数量
onInnerItemClick(position);
}
/**
* 在该方法去处理条目的点击事件
*/
public void onInnerItemClick(int position) {
}
@Override
public int getCount() {
return datas.size() + 1; // 最后的一个条目 就是加载更多的条目
}
@Override
public Object getItem(int position) {
return datas.get(position);
}
/**
* 根据位置 判断当前条目是什么类型
*/
@Override
public int getItemViewType(int position) { //20
if (position == datas.size()) { // 当前是最后一个条目
return MORE_ITEM;
}
return getInnerItemViewType(position); // 如果不是最后一个条目 返回默认类型
}
protected int getInnerItemViewType(int position) {
return DEFAULT_ITEM;
}
/**
* 当前ListView 有几种不同的条目类型
*/
@Override
public int getViewTypeCount() {
return super.getViewTypeCount() + 1; // 2 有两种不同的类型
}
@Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
BaseHolder holder = null;
switch (getItemViewType(position)) { // 判断当前条目时什么类型
case MORE_ITEM:
if (convertView == null) {
holder = getMoreHolder();
} else {
holder = (BaseHolder) convertView.getTag();
}
break;
default:
if (convertView == null) {
holder = getHolder();
} else {
holder = (BaseHolder) convertView.getTag();
}
if (position < datas.size()) {
holder.setData(datas.get(position));
}
break;
}
return holder.getContentView(); // 如果当前Holder 恰好是MoreHolder 证明MoreHOlder已经显示
}
private MoreHolder holder;
private BaseHolder getMoreHolder() {
if (holder != null) {
return holder;
} else {
holder = new MoreHolder(this, hasMore());
return holder;
}
}
/**
* 是否有额外的数据
*
* @return
*/
protected boolean hasMore() {
return true;
}
protected abstract BaseHolder<Data> getHolder();
/**
* 当加载更多条目显示的时候 调用该方法
*/
public void loadMore() {
ThreadManager.getInstance().createLongPool().execute(new Runnable() {
@Override
public void run() {
// 在子线程中加载更多
final List<Data> newData = onload();
UiUtils.runOnUiThread(new Runnable() {
@Override
public void run() {
if (newData == null) {
holder.setData(MoreHolder.LOAD_ERROR);//
} else if (newData.size() == 0) {
holder.setData(MoreHolder.HAS_NO_MORE);
} else {
// 成功了
holder.setData(MoreHolder.HAS_MORE);
datas.addAll(newData);// 给listView之前的集合添加一个新的集合
notifyDataSetChanged();// 刷新界面
}
}
});
}
});
}
/**
* 加载更多数据
*/
protected abstract List<Data> onload();
}
| jxent/Demoz | Demoz/app/src/main/java/cn/demoz/www/adapter/DefaultAdapter.java | Java | apache-2.0 | 5,112 |
/*
* Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.tools.attach;
import com.sun.tools.attach.AgentLoadException;
import com.sun.tools.attach.AttachNotSupportedException;
import com.sun.tools.attach.spi.AttachProvider;
import java.io.InputStream;
import java.io.IOException;
import java.io.File;
/*
* Linux implementation of HotSpotVirtualMachine
*/
public class LinuxVirtualMachine extends HotSpotVirtualMachine {
// "/tmp" is used as a global well-known location for the files
// .java_pid<pid>. and .attach_pid<pid>. It is important that this
// location is the same for all processes, otherwise the tools
// will not be able to find all Hotspot processes.
// Any changes to this needs to be synchronized with HotSpot.
private static final String tmpdir = "/tmp";
// Indicates if this machine uses the old LinuxThreads
static boolean isLinuxThreads;
// The patch to the socket file created by the target VM
String path;
/**
* Attaches to the target VM
*/
public LinuxVirtualMachine(AttachProvider provider, String vmid)
throws AttachNotSupportedException, IOException
{
super(provider, vmid);
// This provider only understands pids
int pid;
try {
pid = Integer.parseInt(vmid);
} catch (NumberFormatException x) {
throw new AttachNotSupportedException("Invalid process identifier");
}
// Find the socket file. If not found then we attempt to start the
// attach mechanism in the target VM by sending it a QUIT signal.
// Then we attempt to find the socket file again.
path = findSocketFile(pid);
if (path == null) {
File f = createAttachFile(pid);
try {
// On LinuxThreads each thread is a process and we don't have the
// pid of the VMThread which has SIGQUIT unblocked. To workaround
// this we get the pid of the "manager thread" that is created
// by the first call to pthread_create. This is parent of all
// threads (except the initial thread).
if (isLinuxThreads) {
int mpid;
try {
mpid = getLinuxThreadsManager(pid);
} catch (IOException x) {
throw new AttachNotSupportedException(x.getMessage());
}
assert(mpid >= 1);
sendQuitToChildrenOf(mpid);
} else {
sendQuitTo(pid);
}
// give the target VM time to start the attach mechanism
int i = 0;
long delay = 200;
int retries = (int)(attachTimeout() / delay);
do {
try {
Thread.sleep(delay);
} catch (InterruptedException x) { }
path = findSocketFile(pid);
i++;
} while (i <= retries && path == null);
if (path == null) {
throw new AttachNotSupportedException(
"Unable to open socket file: target process not responding " +
"or HotSpot VM not loaded");
}
} finally {
f.delete();
}
}
// Check that the file owner/permission to avoid attaching to
// bogus process
checkPermissions(path);
// Check that we can connect to the process
// - this ensures we throw the permission denied error now rather than
// later when we attempt to enqueue a command.
int s = socket();
try {
connect(s, path);
} finally {
close(s);
}
}
/**
* Detach from the target VM
*/
@Override
public void detach() throws IOException {
synchronized (this) {
if (this.path != null) {
this.path = null;
}
}
}
// protocol version
private final static String PROTOCOL_VERSION = "1";
// known errors
private final static int ATTACH_ERROR_BADVERSION = 101;
/**
* Execute the given command in the target VM.
*/
@Override
InputStream execute(String cmd, Object ... args) throws AgentLoadException, IOException {
assert args.length <= 3; // includes null
// did we detach?
String p;
synchronized (this) {
if (this.path == null) {
throw new IOException("Detached from target VM");
}
p = this.path;
}
// create UNIX socket
int s = socket();
// connect to target VM
try {
connect(s, p);
} catch (IOException x) {
close(s);
throw x;
}
IOException ioe = null;
// connected - write request
// <ver> <cmd> <args...>
try {
writeString(s, PROTOCOL_VERSION);
writeString(s, cmd);
for (int i=0; i<3; i++) {
if (i < args.length && args[i] != null) {
writeString(s, (String)args[i]);
} else {
writeString(s, "");
}
}
} catch (IOException x) {
ioe = x;
}
// Create an input stream to read reply
SocketInputStream sis = new SocketInputStream(s);
// Read the command completion status
int completionStatus;
try {
completionStatus = readInt(sis);
} catch (IOException x) {
sis.close();
if (ioe != null) {
throw ioe;
} else {
throw x;
}
}
if (completionStatus != 0) {
sis.close();
// In the event of a protocol mismatch then the target VM
// returns a known error so that we can throw a reasonable
// error.
if (completionStatus == ATTACH_ERROR_BADVERSION) {
throw new IOException("Protocol mismatch with target VM");
}
// Special-case the "load" command so that the right exception is
// thrown.
if (cmd.equals("load")) {
throw new AgentLoadException("Failed to load agent library");
} else {
throw new IOException("Command failed in target VM");
}
}
// Return the input stream so that the command output can be read
return sis;
}
/*
* InputStream for the socket connection to get target VM
*/
private class SocketInputStream extends InputStream {
int s;
public SocketInputStream(int s) {
this.s = s;
}
@Override
public synchronized int read() throws IOException {
byte b[] = new byte[1];
int n = this.read(b, 0, 1);
if (n == 1) {
return b[0] & 0xff;
} else {
return -1;
}
}
@Override
public synchronized int read(byte[] bs, int off, int len) throws IOException {
if ((off < 0) || (off > bs.length) || (len < 0) ||
((off + len) > bs.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
} else if (len == 0)
return 0;
return LinuxVirtualMachine.read(s, bs, off, len);
}
@Override
public void close() throws IOException {
LinuxVirtualMachine.close(s);
}
}
// Return the socket file for the given process.
private String findSocketFile(int pid) {
File f = new File(tmpdir, ".java_pid" + pid);
if (!f.exists()) {
return null;
}
return f.getPath();
}
// On Solaris/Linux a simple handshake is used to start the attach mechanism
// if not already started. The client creates a .attach_pid<pid> file in the
// target VM's working directory (or temp directory), and the SIGQUIT handler
// checks for the file.
private File createAttachFile(int pid) throws IOException {
String fn = ".attach_pid" + pid;
String path = "/proc/" + pid + "/cwd/" + fn;
File f = new File(path);
try {
f.createNewFile();
} catch (IOException x) {
f = new File(tmpdir, fn);
f.createNewFile();
}
return f;
}
/*
* Write/sends the given to the target VM. String is transmitted in
* UTF-8 encoding.
*/
private void writeString(int fd, String s) throws IOException {
if (s.length() > 0) {
byte b[];
try {
b = s.getBytes("UTF-8");
} catch (java.io.UnsupportedEncodingException x) {
throw new InternalError();
}
LinuxVirtualMachine.write(fd, b, 0, b.length);
}
byte b[] = new byte[1];
b[0] = 0;
write(fd, b, 0, 1);
}
//-- native methods
static native boolean isLinuxThreads();
static native int getLinuxThreadsManager(int pid) throws IOException;
static native void sendQuitToChildrenOf(int pid) throws IOException;
static native void sendQuitTo(int pid) throws IOException;
static native void checkPermissions(String path) throws IOException;
static native int socket() throws IOException;
static native void connect(int fd, String path) throws IOException;
static native void close(int fd) throws IOException;
static native int read(int fd, byte buf[], int off, int bufLen) throws IOException;
static native void write(int fd, byte buf[], int off, int bufLen) throws IOException;
static {
System.loadLibrary("attach");
isLinuxThreads = isLinuxThreads();
}
}
| gstamac/powermock | powermock-modules/powermock-module-javaagent/src/main/java/sun/tools/attach/LinuxVirtualMachine.java | Java | apache-2.0 | 11,227 |
/**
* Copyright 2015 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 {
AsyncResolverDef,
ResolverReturnDef,
SyncResolverDef,
VariableSource,
getNavigationData,
getTimingDataAsync,
getTimingDataSync,
} from './variable-source';
import {Expander, NOENCODE_WHITELIST} from './url-expander/expander';
import {Services} from '../services';
import {WindowInterface} from '../window-interface';
import {
addMissingParamsToUrl,
addParamsToUrl,
getSourceUrl,
isProtocolValid,
parseQueryString,
parseUrlDeprecated,
removeAmpJsParamsFromUrl,
removeFragment,
} from '../url';
import {dev, rethrowAsync, user} from '../log';
import {getMode} from '../mode';
import {getTrackImpressionPromise} from '../impression.js';
import {hasOwn} from '../utils/object';
import {
installServiceInEmbedScope,
registerServiceBuilderForDoc,
} from '../service';
import {isExperimentOn} from '../experiments';
import {tryResolve} from '../utils/promise';
/** @private @const {string} */
const TAG = 'UrlReplacements';
const EXPERIMENT_DELIMITER = '!';
const VARIANT_DELIMITER = '.';
const GEO_DELIM = ',';
const ORIGINAL_HREF_PROPERTY = 'amp-original-href';
const ORIGINAL_VALUE_PROPERTY = 'amp-original-value';
/**
* Returns a encoded URI Component, or an empty string if the value is nullish.
* @param {*} val
* @return {string}
*/
function encodeValue(val) {
if (val == null) {
return '';
}
return encodeURIComponent(/** @type {string} */(val));
}
/**
* Returns a function that executes method on a new Date instance. This is a
* byte saving hack.
*
* @param {string} method
* @return {!SyncResolverDef}
*/
function dateMethod(method) {
return () => new Date()[method]();
}
/**
* Returns a function that returns property of screen. This is a byte saving
* hack.
*
* @param {!Screen} screen
* @param {string} property
* @return {!SyncResolverDef}
*/
function screenProperty(screen, property) {
return () => screen[property];
}
/**
* Class to provide variables that pertain to top level AMP window.
*/
export class GlobalVariableSource extends VariableSource {
/**
* @param {!./ampdoc-impl.AmpDoc} ampdoc
*/
constructor(ampdoc) {
super(ampdoc);
/** @private {?Promise<?Object<string, string>>} */
this.variants_ = null;
/** @private {?Promise<?ShareTrackingFragmentsDef>} */
this.shareTrackingFragments_ = null;
}
/**
* Utility function for setting resolver for timing data that supports
* sync and async.
* @param {string} varName
* @param {string} startEvent
* @param {string=} endEvent
* @return {!VariableSource}
* @private
*/
setTimingResolver_(varName, startEvent, endEvent) {
return this.setBoth(varName, () => {
return getTimingDataSync(this.ampdoc.win, startEvent, endEvent);
}, () => {
return getTimingDataAsync(this.ampdoc.win, startEvent, endEvent);
});
}
/** @override */
initialize() {
/** @const {!./viewport/viewport-impl.Viewport} */
const viewport = Services.viewportForDoc(this.ampdoc);
// Returns a random value for cache busters.
this.set('RANDOM', () => Math.random());
// Provides a counter starting at 1 per given scope.
const counterStore = Object.create(null);
this.set('COUNTER', scope => {
return counterStore[scope] = (counterStore[scope] | 0) + 1;
});
// Returns the canonical URL for this AMP document.
this.set('CANONICAL_URL', this.getDocInfoUrl_('canonicalUrl'));
// Returns the host of the canonical URL for this AMP document.
this.set('CANONICAL_HOST', this.getDocInfoUrl_('canonicalUrl', 'host'));
// Returns the hostname of the canonical URL for this AMP document.
this.set('CANONICAL_HOSTNAME', this.getDocInfoUrl_('canonicalUrl',
'hostname'));
// Returns the path of the canonical URL for this AMP document.
this.set('CANONICAL_PATH', this.getDocInfoUrl_('canonicalUrl', 'pathname'));
// Returns the referrer URL.
this.setAsync('DOCUMENT_REFERRER', /** @type {AsyncResolverDef} */(() => {
return Services.viewerForDoc(this.ampdoc).getReferrerUrl();
}));
// Like DOCUMENT_REFERRER, but returns null if the referrer is of
// same domain or the corresponding CDN proxy.
this.setAsync('EXTERNAL_REFERRER', /** @type {AsyncResolverDef} */(() => {
return Services.viewerForDoc(this.ampdoc).getReferrerUrl()
.then(referrer => {
if (!referrer) {
return null;
}
const referrerHostname = parseUrlDeprecated(getSourceUrl(referrer))
.hostname;
const currentHostname =
WindowInterface.getHostname(this.ampdoc.win);
return referrerHostname === currentHostname ? null : referrer;
});
}));
// Returns the title of this AMP document.
this.set('TITLE', () => {
// The environment may override the title and set originalTitle. Prefer
// that if available.
return this.ampdoc.win.document['originalTitle'] ||
this.ampdoc.win.document.title;
});
// Returns the URL for this AMP document.
this.set('AMPDOC_URL', () => {
return removeFragment(
this.addReplaceParamsIfMissing_(
this.ampdoc.win.location.href));
});
// Returns the host of the URL for this AMP document.
this.set('AMPDOC_HOST', () => {
const url = parseUrlDeprecated(this.ampdoc.win.location.href);
return url && url.host;
});
// Returns the hostname of the URL for this AMP document.
this.set('AMPDOC_HOSTNAME', () => {
const url = parseUrlDeprecated(this.ampdoc.win.location.href);
return url && url.hostname;
});
// Returns the Source URL for this AMP document.
const expandSourceUrl = () => {
const docInfo = Services.documentInfoForDoc(this.ampdoc);
return removeFragment(this.addReplaceParamsIfMissing_(docInfo.sourceUrl));
};
this.setBoth('SOURCE_URL',
() => expandSourceUrl(),
() => getTrackImpressionPromise().then(() => expandSourceUrl()));
// Returns the host of the Source URL for this AMP document.
this.set('SOURCE_HOST', this.getDocInfoUrl_('sourceUrl', 'host'));
// Returns the hostname of the Source URL for this AMP document.
this.set('SOURCE_HOSTNAME', this.getDocInfoUrl_('sourceUrl', 'hostname'));
// Returns the path of the Source URL for this AMP document.
this.set('SOURCE_PATH', this.getDocInfoUrl_('sourceUrl', 'pathname'));
// Returns a random string that will be the constant for the duration of
// single page view. It should have sufficient entropy to be unique for
// all the page views a single user is making at a time.
this.set('PAGE_VIEW_ID', this.getDocInfoUrl_('pageViewId'));
this.setBoth('QUERY_PARAM', (param, defaultValue = '') => {
return this.getQueryParamData_(param, defaultValue);
}, (param, defaultValue = '') => {
return getTrackImpressionPromise().then(() => {
return this.getQueryParamData_(param, defaultValue);
});
});
// Returns the value of the given field name in the fragment query string.
// Second parameter is an optional default value.
// For example, if location is 'pub.com/amp.html?x=1#y=2' then
// FRAGMENT_PARAM(y) returns '2' and FRAGMENT_PARAM(z, 3) returns 3.
this.setAsync('FRAGMENT_PARAM',
this.getViewerIntegrationValue_('fragmentParam', 'FRAGMENT_PARAM'));
// Returns the first item in the ancestorOrigins array, if available.
this.setAsync('ANCESTOR_ORIGIN',
this.getViewerIntegrationValue_('ancestorOrigin', 'ANCESTOR_ORIGIN'));
/**
* Stores client ids that were generated during this page view
* indexed by scope.
* @type {?Object<string, string>}
*/
let clientIds = null;
// Synchronous alternative. Only works for scopes that were previously
// requested using the async method.
this.setBoth('CLIENT_ID', scope => {
if (!clientIds) {
return null;
}
return clientIds[dev().assertString(scope)];
}, (scope, opt_userNotificationId, opt_cookieName) => {
user().assertString(scope,
'The first argument to CLIENT_ID, the fallback' +
/*OK*/' Cookie name, is required');
if (getMode().runtime == 'inabox') {
return /** @type {!Promise<ResolverReturnDef>} */(Promise.resolve(null));
}
let consent = Promise.resolve();
// If no `opt_userNotificationId` argument is provided then
// assume consent is given by default.
if (opt_userNotificationId) {
consent = Services.userNotificationManagerForDoc(this.ampdoc)
.then(service => {
return service.get(opt_userNotificationId);
});
}
return Services.cidForDoc(this.ampdoc).then(cid => {
return cid.get({
scope: dev().assertString(scope),
createCookieIfNotPresent: true,
cookieName: opt_cookieName,
}, consent);
}).then(cid => {
if (!clientIds) {
clientIds = Object.create(null);
}
// A temporary work around to extract Client ID from _ga cookie. #5761
// TODO: replace with "filter" when it's in place. #2198
const cookieName = opt_cookieName || scope;
if (cid && cookieName == '_ga') {
if (typeof cid === 'string') {
cid = extractClientIdFromGaCookie(cid);
} else {
// TODO(@jridgewell, #11120): remove once #11120 is figured out.
// Do not log the CID directly, that's PII.
dev().error(TAG, 'non-string cid, what is it?', Object.keys(cid));
}
}
clientIds[scope] = cid;
return cid;
});
});
// Returns assigned variant name for the given experiment.
this.setAsync('VARIANT', /** @type {AsyncResolverDef} */(experiment => {
return this.getVariantsValue_(variants => {
const variant = variants[/** @type {string} */(experiment)];
user().assert(variant !== undefined,
'The value passed to VARIANT() is not a valid experiment name:' +
experiment);
// When no variant assigned, use reserved keyword 'none'.
return variant === null ? 'none' : /** @type {string} */(variant);
}, 'VARIANT');
}));
// Returns all assigned experiment variants in a serialized form.
this.setAsync('VARIANTS', /** @type {AsyncResolverDef} */(() => {
return this.getVariantsValue_(variants => {
const experiments = [];
for (const experiment in variants) {
const variant = variants[experiment];
experiments.push(
experiment + VARIANT_DELIMITER + (variant || 'none'));
}
return experiments.join(EXPERIMENT_DELIMITER);
}, 'VARIANTS');
}));
// Returns assigned geo value for geoType or all groups.
this.setAsync('AMP_GEO', /** @type {AsyncResolverDef} */(geoType => {
return this.getGeo_(geos => {
if (geoType) {
user().assert(geoType === 'ISOCountry',
'The value passed to AMP_GEO() is not valid name:' + geoType);
return /** @type {string} */ (geos[geoType] || 'unknown');
}
return /** @type {string} */ (geos.ISOCountryGroups.join(GEO_DELIM));
}, 'AMP_GEO');
}));
// Returns incoming share tracking fragment.
this.setAsync('SHARE_TRACKING_INCOMING', /** @type {AsyncResolverDef} */(
() => {
return this.getShareTrackingValue_(fragments => {
return fragments.incomingFragment;
}, 'SHARE_TRACKING_INCOMING');
}));
// Returns outgoing share tracking fragment.
this.setAsync('SHARE_TRACKING_OUTGOING', /** @type {AsyncResolverDef} */(
() => {
return this.getShareTrackingValue_(fragments => {
return fragments.outgoingFragment;
}, 'SHARE_TRACKING_OUTGOING');
}));
// Returns the number of milliseconds since 1 Jan 1970 00:00:00 UTC.
this.set('TIMESTAMP', dateMethod('getTime'));
// Returns the human readable timestamp in format of
// 2011-01-01T11:11:11.612Z.
this.set('TIMESTAMP_ISO', dateMethod('toISOString'));
// Returns the user's time-zone offset from UTC, in minutes.
this.set('TIMEZONE', dateMethod('getTimezoneOffset'));
// Returns the IANA timezone code
this.set('TIMEZONE_CODE', () => {
let tzCode;
if ('Intl' in this.ampdoc.win &&
'DateTimeFormat' in this.ampdoc.win.Intl) {
// It could be undefined (i.e. IE11)
tzCode = new Intl.DateTimeFormat().resolvedOptions().timeZone;
}
return tzCode || '';
});
// Returns a promise resolving to viewport.getScrollTop.
this.set('SCROLL_TOP', () => viewport.getScrollTop());
// Returns a promise resolving to viewport.getScrollLeft.
this.set('SCROLL_LEFT', () => viewport.getScrollLeft());
// Returns a promise resolving to viewport.getScrollHeight.
this.set('SCROLL_HEIGHT', () => viewport.getScrollHeight());
// Returns a promise resolving to viewport.getScrollWidth.
this.set('SCROLL_WIDTH', () => viewport.getScrollWidth());
// Returns the viewport height.
this.set('VIEWPORT_HEIGHT', () => viewport.getHeight());
// Returns the viewport width.
this.set('VIEWPORT_WIDTH', () => viewport.getWidth());
const {screen} = this.ampdoc.win;
// Returns screen.width.
this.set('SCREEN_WIDTH', screenProperty(screen, 'width'));
// Returns screen.height.
this.set('SCREEN_HEIGHT', screenProperty(screen, 'height'));
// Returns screen.availHeight.
this.set('AVAILABLE_SCREEN_HEIGHT', screenProperty(screen, 'availHeight'));
// Returns screen.availWidth.
this.set('AVAILABLE_SCREEN_WIDTH', screenProperty(screen, 'availWidth'));
// Returns screen.ColorDepth.
this.set('SCREEN_COLOR_DEPTH', screenProperty(screen, 'colorDepth'));
// Returns document characterset.
this.set('DOCUMENT_CHARSET', () => {
const doc = this.ampdoc.win.document;
return doc.characterSet || doc.charset;
});
// Returns the browser language.
this.set('BROWSER_LANGUAGE', () => {
const nav = this.ampdoc.win.navigator;
return (nav.language || nav.userLanguage || nav.browserLanguage || '')
.toLowerCase();
});
// Returns the user agent.
this.set('USER_AGENT', () => {
const nav = this.ampdoc.win.navigator;
return nav.userAgent;
});
// Returns the time it took to load the whole page. (excludes amp-* elements
// that are not rendered by the system yet.)
this.setTimingResolver_(
'PAGE_LOAD_TIME', 'navigationStart', 'loadEventStart');
// Returns the time it took to perform DNS lookup for the domain.
this.setTimingResolver_(
'DOMAIN_LOOKUP_TIME', 'domainLookupStart', 'domainLookupEnd');
// Returns the time it took to connect to the server.
this.setTimingResolver_(
'TCP_CONNECT_TIME', 'connectStart', 'connectEnd');
// Returns the time it took for server to start sending a response to the
// request.
this.setTimingResolver_(
'SERVER_RESPONSE_TIME', 'requestStart', 'responseStart');
// Returns the time it took to download the page.
this.setTimingResolver_(
'PAGE_DOWNLOAD_TIME', 'responseStart', 'responseEnd');
// Returns the time it took for redirects to complete.
this.setTimingResolver_(
'REDIRECT_TIME', 'navigationStart', 'fetchStart');
// Returns the time it took for DOM to become interactive.
this.setTimingResolver_(
'DOM_INTERACTIVE_TIME', 'navigationStart', 'domInteractive');
// Returns the time it took for content to load.
this.setTimingResolver_(
'CONTENT_LOAD_TIME', 'navigationStart', 'domContentLoadedEventStart');
// Access: Reader ID.
this.setAsync('ACCESS_READER_ID', /** @type {AsyncResolverDef} */(() => {
return this.getAccessValue_(accessService => {
return accessService.getAccessReaderId();
}, 'ACCESS_READER_ID');
}));
// Access: data from the authorization response.
this.setAsync('AUTHDATA', /** @type {AsyncResolverDef} */(field => {
user().assert(field,
'The first argument to AUTHDATA, the field, is required');
return this.getAccessValue_(accessService => {
return accessService.getAuthdataField(field);
}, 'AUTHDATA');
}));
// Returns an identifier for the viewer.
this.setAsync('VIEWER', () => {
return Services.viewerForDoc(this.ampdoc)
.getViewerOrigin().then(viewer => {
return viewer == undefined ? '' : viewer;
});
});
// Returns the total engaged time since the content became viewable.
this.setAsync('TOTAL_ENGAGED_TIME', () => {
return Services.activityForDoc(this.ampdoc).then(activity => {
return activity.getTotalEngagedTime();
});
});
// Returns the incremental engaged time since the last push under the
// same name.
this.setAsync('INCREMENTAL_ENGAGED_TIME', (name, reset) => {
return Services.activityForDoc(this.ampdoc).then(activity => {
return activity.getIncrementalEngagedTime(name, reset !== 'false');
});
});
this.set('NAV_TIMING', (startAttribute, endAttribute) => {
user().assert(startAttribute, 'The first argument to NAV_TIMING, the ' +
'start attribute name, is required');
return getTimingDataSync(
this.ampdoc.win,
/**@type {string}*/(startAttribute),
/**@type {string}*/(endAttribute));
});
this.setAsync('NAV_TIMING', (startAttribute, endAttribute) => {
user().assert(startAttribute, 'The first argument to NAV_TIMING, the ' +
'start attribute name, is required');
return getTimingDataAsync(
this.ampdoc.win,
/**@type {string}*/(startAttribute),
/**@type {string}*/(endAttribute));
});
this.set('NAV_TYPE', () => {
return getNavigationData(this.ampdoc.win, 'type');
});
this.set('NAV_REDIRECT_COUNT', () => {
return getNavigationData(this.ampdoc.win, 'redirectCount');
});
// returns the AMP version number
this.set('AMP_VERSION', () => '$internalRuntimeVersion$');
this.set('BACKGROUND_STATE', () => {
return Services.viewerForDoc(this.ampdoc).isVisible() ? '0' : '1';
});
this.setAsync('VIDEO_STATE', (id, property) => {
const root = this.ampdoc.getRootNode();
const video = user().assertElement(
root.getElementById(/** @type {string} */ (id)),
`Could not find an element with id="${id}" for VIDEO_STATE`);
return Services.videoManagerForDoc(this.ampdoc)
.getAnalyticsDetails(video)
.then(details => details ? details[property] : '');
});
this.setAsync('STORY_PAGE_INDEX', this.getStoryValue_('pageIndex',
'STORY_PAGE_INDEX'));
this.setAsync('STORY_PAGE_ID', this.getStoryValue_('pageId',
'STORY_PAGE_ID'));
this.setAsync('FIRST_CONTENTFUL_PAINT', () => {
return tryResolve(() =>
Services.performanceFor(this.ampdoc.win).getFirstContentfulPaint());
});
this.setAsync('FIRST_VIEWPORT_READY', () => {
return tryResolve(() =>
Services.performanceFor(this.ampdoc.win).getFirstViewportReady());
});
this.setAsync('MAKE_BODY_VISIBLE', () => {
return tryResolve(() =>
Services.performanceFor(this.ampdoc.win).getMakeBodyVisible());
});
this.setAsync('AMP_STATE', key => {
return Services.bindForDocOrNull(this.ampdoc).then(bind => {
if (!bind) {
return '';
}
return bind.getStateValue(/** @type {string} */ (key));
});
});
}
/**
* Merges any replacement parameters into a given URL's query string,
* preferring values set in the original query string.
* @param {string} orig The original URL
* @return {string} The resulting URL
* @private
*/
addReplaceParamsIfMissing_(orig) {
const {replaceParams} =
/** @type {!Object} */ (Services.documentInfoForDoc(this.ampdoc));
if (!replaceParams) {
return orig;
}
return addMissingParamsToUrl(removeAmpJsParamsFromUrl(orig), replaceParams);
}
/**
* Resolves the value via one of document info's urls.
* @param {string} field A field on the docInfo
* @param {string=} opt_urlProp A subproperty of the field
* @return {T}
* @template T
*/
getDocInfoUrl_(field, opt_urlProp) {
return () => {
const docInfo = Services.documentInfoForDoc(this.ampdoc);
const value = docInfo[field];
return opt_urlProp ? parseUrlDeprecated(value)[opt_urlProp] : value;
};
}
/**
* Resolves the value via access service. If access service is not configured,
* the resulting value is `null`.
* @param {function(!../../extensions/amp-access/0.1/access-vars.AccessVars):(T|!Promise<T>)} getter
* @param {string} expr
* @return {T|null}
* @template T
* @private
*/
getAccessValue_(getter, expr) {
return Promise.all([
Services.accessServiceForDocOrNull(this.ampdoc),
Services.subscriptionsServiceForDocOrNull(this.ampdoc),
]).then(services => {
const service = /** @type {?../../extensions/amp-access/0.1/access-vars.AccessVars} */ (
services[0] || services[1]);
if (!service) {
// Access/subscriptions service is not installed.
user().error(
TAG,
'Access or subsciptions service is not installed to access: ',
expr);
return null;
}
return getter(service);
});
}
/**
* Return the QUERY_PARAM from the current location href
* @param {*} param
* @param {string} defaultValue
* @return {string}
* @private
*/
getQueryParamData_(param, defaultValue) {
user().assert(param,
'The first argument to QUERY_PARAM, the query string ' +
'param is required');
const url = parseUrlDeprecated(
removeAmpJsParamsFromUrl(this.ampdoc.win.location.href));
const params = parseQueryString(url.search);
const key = user().assertString(param);
const {replaceParams} = Services.documentInfoForDoc(this.ampdoc);
if (typeof params[key] !== 'undefined') {
return params[key];
}
if (replaceParams && typeof replaceParams[key] !== 'undefined') {
return /** @type {string} */(replaceParams[key]);
}
return defaultValue;
}
/**
* Resolves the value via amp-experiment's variants service.
* @param {function(!Object<string, string>):(?string)} getter
* @param {string} expr
* @return {!Promise<?string>}
* @template T
* @private
*/
getVariantsValue_(getter, expr) {
if (!this.variants_) {
this.variants_ = Services.variantForOrNull(this.ampdoc.win);
}
return this.variants_.then(variants => {
user().assert(variants,
'To use variable %s, amp-experiment should be configured',
expr);
return getter(variants);
});
}
/**
* Resolves the value via geo service.
* @param {function(Object<string, string>)} getter
* @param {string} expr
* @return {!Promise<Object<string,(string|Array<string>)>>}
* @template T
* @private
*/
getGeo_(getter, expr) {
return Services.geoForDocOrNull(this.ampdoc)
.then(geo => {
user().assert(geo,
'To use variable %s, amp-geo should be configured',
expr);
return getter(geo);
});
}
/**
* Resolves the value via amp-share-tracking's service.
* @param {function(!ShareTrackingFragmentsDef):T} getter
* @param {string} expr
* @return {!Promise<T>}
* @template T
* @private
*/
getShareTrackingValue_(getter, expr) {
if (!this.shareTrackingFragments_) {
this.shareTrackingFragments_ =
Services.shareTrackingForOrNull(this.ampdoc.win);
}
return this.shareTrackingFragments_.then(fragments => {
user().assert(fragments, 'To use variable %s, ' +
'amp-share-tracking should be configured',
expr);
return getter(/** @type {!ShareTrackingFragmentsDef} */ (fragments));
});
}
/**
* Resolves the value via amp-story's service.
* @param {string} property
* @param {string} name
* @return {!AsyncResolverDef}
* @private
*/
getStoryValue_(property, name) {
return () => {
const service = Services.storyVariableServiceForOrNull(this.ampdoc.win);
return service.then(storyVariables => {
user().assert(storyVariables,
'To use variable %s amp-story should be configured', name);
return storyVariables[property];
});
};
}
/**
* Resolves the value via amp-viewer-integration's service.
* @param {string} property
* @param {string} name
* @return {!AsyncResolverDef}
* @private
*/
getViewerIntegrationValue_(property, name) {
return /** @type {!AsyncResolverDef} */ (
(param, defaultValue = '') => {
const service =
Services.viewerIntegrationVariableServiceForOrNull(this.ampdoc.win);
return service.then(viewerIntegrationVariables => {
user().assert(viewerIntegrationVariables, 'To use variable %s ' +
'amp-viewer-integration must be installed', name);
return viewerIntegrationVariables[property](param, defaultValue);
});
});
}
}
/**
* This class replaces substitution variables with their values.
* Document new values in ../spec/amp-var-substitutions.md
* @package For export
*/
export class UrlReplacements {
/**
* @param {!./ampdoc-impl.AmpDoc} ampdoc
* @param {!VariableSource} variableSource
*/
constructor(ampdoc, variableSource) {
/** @const {!./ampdoc-impl.AmpDoc} */
this.ampdoc = ampdoc;
/** @type {VariableSource} */
this.variableSource_ = variableSource;
/** @type {!Expander} */
this.expander_ = new Expander(this.variableSource_);
}
/**
* Synchronously expands the provided source by replacing all known variables
* with their resolved values. Optional `opt_bindings` can be used to add new
* variables or override existing ones. Any async bindings are ignored.
* @param {string} source
* @param {!Object<string, (ResolverReturnDef|!SyncResolverDef)>=} opt_bindings
* @param {!Object<string, ResolverReturnDef>=} opt_collectVars
* @param {!Object<string, boolean>=} opt_whiteList Optional white list of
* names that can be substituted.
* @return {string}
*/
expandStringSync(source, opt_bindings, opt_collectVars, opt_whiteList) {
return /** @type {string} */ (
this.expand_(source, opt_bindings, opt_collectVars, /* opt_sync */ true,
opt_whiteList));
}
/**
* Expands the provided source by replacing all known variables with their
* resolved values. Optional `opt_bindings` can be used to add new variables
* or override existing ones.
* @param {string} source
* @param {!Object<string, *>=} opt_bindings
* @param {!Object<string, boolean>=} opt_whiteList
* @return {!Promise<string>}
*/
expandStringAsync(source, opt_bindings, opt_whiteList) {
return /** @type {!Promise<string>} */ (this.expand_(source, opt_bindings,
/* opt_collectVars */ undefined,
/* opt_sync */ undefined, opt_whiteList));
}
/**
* Synchronously expands the provided URL by replacing all known variables
* with their resolved values. Optional `opt_bindings` can be used to add new
* variables or override existing ones. Any async bindings are ignored.
* @param {string} url
* @param {!Object<string, (ResolverReturnDef|!SyncResolverDef)>=} opt_bindings
* @param {!Object<string, ResolverReturnDef>=} opt_collectVars
* @param {!Object<string, boolean>=} opt_whiteList Optional white list of
* names that can be substituted.
* @return {string}
*/
expandUrlSync(url, opt_bindings, opt_collectVars, opt_whiteList) {
return this.ensureProtocolMatches_(url, /** @type {string} */ (this.expand_(
url, opt_bindings, opt_collectVars, /* opt_sync */ true,
opt_whiteList)));
}
/**
* Expands the provided URL by replacing all known variables with their
* resolved values. Optional `opt_bindings` can be used to add new variables
* or override existing ones.
* @param {string} url
* @param {!Object<string, *>=} opt_bindings
* @param {!Object<string, boolean>=} opt_whiteList Optional white list of names
* that can be substituted.
* @return {!Promise<string>}
*/
expandUrlAsync(url, opt_bindings, opt_whiteList) {
return /** @type {!Promise<string>} */ (
this.expand_(url, opt_bindings, undefined, undefined,
opt_whiteList).then(
replacement => this.ensureProtocolMatches_(url, replacement)));
}
/**
* Expands an input element value attribute with variable substituted.
* @param {!HTMLInputElement} element
* @return {!Promise<string>}
*/
expandInputValueAsync(element) {
return /** @type {!Promise<string>} */ (
this.expandInputValue_(element, /*opt_sync*/ false));
}
/**
* Expands an input element value attribute with variable substituted.
* @param {!HTMLInputElement} element
* @return {string} Replaced string for testing
*/
expandInputValueSync(element) {
return /** @type {string} */ (
this.expandInputValue_(element, /*opt_sync*/ true));
}
/**
* Expands in input element value attribute with variable substituted.
* @param {!HTMLInputElement} element
* @param {boolean=} opt_sync
* @return {string|!Promise<string>}
*/
expandInputValue_(element, opt_sync) {
dev().assert(element.tagName == 'INPUT' &&
(element.getAttribute('type') || '').toLowerCase() == 'hidden',
'Input value expansion only works on hidden input fields: %s', element);
const whitelist = this.getWhitelistForElement_(element);
if (!whitelist) {
return opt_sync ? element.value : Promise.resolve(element.value);
}
if (element[ORIGINAL_VALUE_PROPERTY] === undefined) {
element[ORIGINAL_VALUE_PROPERTY] = element.value;
}
const result = this.expand_(
element[ORIGINAL_VALUE_PROPERTY] || element.value,
/* opt_bindings */ undefined,
/* opt_collectVars */ undefined,
/* opt_sync */ opt_sync,
/* opt_whitelist */ whitelist);
if (opt_sync) {
return element.value = result;
}
return result.then(newValue => {
element.value = newValue;
return newValue;
});
}
/**
* Returns a replacement whitelist from elements' data-amp-replace attribute.
* @param {!Element} element
* @param {!Object<string, boolean>=} opt_supportedReplacement Optional supported
* replacement that filters whitelist to a subset.
* @return {!Object<string, boolean>|undefined}
*/
getWhitelistForElement_(element, opt_supportedReplacement) {
const whitelist = element.getAttribute('data-amp-replace');
if (!whitelist) {
return;
}
const requestedReplacements = {};
whitelist.trim().split(/\s+/).forEach(replacement => {
if (!opt_supportedReplacement ||
hasOwn(opt_supportedReplacement, replacement)) {
requestedReplacements[replacement] = true;
} else {
user().warn('URL', 'Ignoring unsupported replacement', replacement);
}
});
return requestedReplacements;
}
/**
* Returns whether variable substitution is allowed for given url.
* @param {!Location} url
* @return {boolean}
*/
isAllowedOrigin_(url) {
const docInfo = Services.documentInfoForDoc(this.ampdoc);
if (url.origin == parseUrlDeprecated(docInfo.canonicalUrl).origin ||
url.origin == parseUrlDeprecated(docInfo.sourceUrl).origin) {
return true;
}
const meta = this.ampdoc.getRootNode().querySelector(
'meta[name=amp-link-variable-allowed-origin]');
if (meta && meta.hasAttribute('content')) {
const whitelist = meta.getAttribute('content').trim().split(/\s+/);
for (let i = 0; i < whitelist.length; i++) {
if (url.origin == parseUrlDeprecated(whitelist[i]).origin) {
return true;
}
}
}
return false;
}
/**
* Replaces values in the link of an anchor tag if
* - the link opts into it (via data-amp-replace argument)
* - the destination is the source or canonical origin of this doc.
* @param {!Element} element An anchor element.
* @param {?string} defaultUrlParams to expand link if caller request.
* @return {string|undefined} Replaced string for testing
*/
maybeExpandLink(element, defaultUrlParams) {
dev().assert(element.tagName == 'A');
const supportedReplacements = {
'CLIENT_ID': true,
'QUERY_PARAM': true,
'PAGE_VIEW_ID': true,
'NAV_TIMING': true,
};
const additionalUrlParameters =
element.getAttribute('data-amp-addparams') || '';
const whitelist = this.getWhitelistForElement_(
element, supportedReplacements);
if (!whitelist && !additionalUrlParameters && !defaultUrlParams) {
return;
}
// ORIGINAL_HREF_PROPERTY has the value of the href "pre-replacement".
// We set this to the original value before doing any work and use it
// on subsequent replacements, so that each run gets a fresh value.
let href = dev().assertString(
element[ORIGINAL_HREF_PROPERTY] || element.getAttribute('href'));
const url = parseUrlDeprecated(href);
if (element[ORIGINAL_HREF_PROPERTY] == null) {
element[ORIGINAL_HREF_PROPERTY] = href;
}
if (additionalUrlParameters) {
href = addParamsToUrl(
href,
parseQueryString(additionalUrlParameters));
}
const isAllowedOrigin = this.isAllowedOrigin_(url);
if (!isAllowedOrigin) {
if (whitelist) {
user().warn('URL', 'Ignoring link replacement', href,
' because the link does not go to the document\'s' +
' source, canonical, or whitelisted origin.');
}
return element.href = href;
}
// Note that defaultUrlParams is treated differently than
// additionalUrlParameters in two ways #1: If the outgoing url origin is not
// whitelisted: additionalUrlParameters are always appended by not expanded,
// defaultUrlParams will not be appended. #2: If the expansion function is
// not whitelisted: additionalUrlParamters will not be expanded,
// defaultUrlParams will by default support QUERY_PARAM, and will still be
// expanded.
if (defaultUrlParams) {
if (!whitelist || !whitelist['QUERY_PARAM']) {
// override whitelist and expand defaultUrlParams;
const overrideWhitelist = {'QUERY_PARAM': true};
defaultUrlParams = this.expandUrlSync(
defaultUrlParams,
/* opt_bindings */ undefined,
/* opt_collectVars */ undefined,
/* opt_whitelist */ overrideWhitelist);
}
href = addParamsToUrl(href, parseQueryString(defaultUrlParams));
}
if (whitelist) {
href = this.expandUrlSync(
href,
/* opt_bindings */ undefined,
/* opt_collectVars */ undefined,
/* opt_whitelist */ whitelist);
}
return element.href = href;
}
/**
* @param {string} url
* @param {!Object<string, *>=} opt_bindings
* @param {!Object<string, *>=} opt_collectVars
* @param {boolean=} opt_sync
* @param {!Object<string, boolean>=} opt_whiteList Optional white list of names
* that can be substituted.
* @return {!Promise<string>|string}
* @private
*/
expand_(url, opt_bindings, opt_collectVars, opt_sync, opt_whiteList) {
const isV2ExperimentOn = isExperimentOn(this.ampdoc.win,
'url-replacement-v2');
if (isV2ExperimentOn) {
// TODO(ccordy) support opt_collectVars && opt_whitelist
return this.expander_./*OK*/expand(url, opt_bindings, opt_collectVars,
opt_sync, opt_whiteList);
}
// existing parsing method
const expr = this.variableSource_.getExpr(opt_bindings);
let replacementPromise;
let replacement = url.replace(expr, (match, name, opt_strargs) => {
let args = [];
if (typeof opt_strargs == 'string') {
args = opt_strargs.split(/,\s*/);
}
if (opt_whiteList && !opt_whiteList[name]) {
// Do not perform substitution and just return back the original
// match, so that the string doesn't change.
return match;
}
let binding;
if (opt_bindings && (name in opt_bindings)) {
binding = opt_bindings[name];
} else if ((binding = this.variableSource_.get(name))) {
if (opt_sync) {
binding = binding.sync;
if (!binding) {
user().error(TAG, 'ignoring async replacement key: ', name);
return '';
}
} else {
binding = binding.async || binding.sync;
}
}
let val;
try {
val = (typeof binding == 'function') ?
binding.apply(null, args) : binding;
} catch (e) {
// Report error, but do not disrupt URL replacement. This will
// interpolate as the empty string.
if (opt_sync) {
val = '';
}
rethrowAsync(e);
}
// In case the produced value is a promise, we don't actually
// replace anything here, but do it again when the promise resolves.
if (val && val.then) {
if (opt_sync) {
user().error(TAG, 'ignoring promise value for key: ', name);
return '';
}
/** @const {Promise<string>} */
const p = val.catch(err => {
// Report error, but do not disrupt URL replacement. This will
// interpolate as the empty string.
rethrowAsync(err);
}).then(v => {
replacement = replacement.replace(match,
NOENCODE_WHITELIST[match] ? v : encodeValue(v));
if (opt_collectVars) {
opt_collectVars[match] = v;
}
});
if (replacementPromise) {
replacementPromise = replacementPromise.then(() => p);
} else {
replacementPromise = p;
}
return match;
}
if (opt_collectVars) {
opt_collectVars[match] = val;
}
return NOENCODE_WHITELIST[match] ? val : encodeValue(val);
});
if (replacementPromise) {
replacementPromise = replacementPromise.then(() => replacement);
}
if (opt_sync) {
return replacement;
}
return replacementPromise || Promise.resolve(replacement);
}
/**
* Collects all substitutions in the provided URL and expands them to the
* values for known variables. Optional `opt_bindings` can be used to add
* new variables or override existing ones.
* @param {string} url
* @param {!Object<string, *>=} opt_bindings
* @return {!Promise<!Object<string, *>>}
*/
collectVars(url, opt_bindings) {
const vars = Object.create(null);
return this.expand_(url, opt_bindings, vars).then(() => vars);
}
/**
* Collects substitutions in the `src` attribute of the given element
* that are _not_ whitelisted via `data-amp-replace` opt-in attribute.
* @param {!Element} element
* @return {!Array<string>}
*/
collectUnwhitelistedVarsSync(element) {
const url = element.getAttribute('src');
const vars = Object.create(null);
this.expandStringSync(url, /* opt_bindings */ undefined, vars);
const varNames = Object.keys(vars);
const whitelist = this.getWhitelistForElement_(element);
if (whitelist) {
return varNames.filter(v => !whitelist[v]);
} else {
// All vars are unwhitelisted if the element has no whitelist.
return varNames;
}
}
/**
* Ensures that the protocol of the original url matches the protocol of the
* replacement url. Returns the replacement if they do, the original if they
* do not.
* @param {string} url
* @param {string} replacement
* @return {string}
*/
ensureProtocolMatches_(url, replacement) {
const newProtocol = parseUrlDeprecated(replacement, /* opt_nocache */ true)
.protocol;
const oldProtocol = parseUrlDeprecated(url, /* opt_nocache */ true)
.protocol;
if (newProtocol != oldProtocol) {
user().error(TAG, 'Illegal replacement of the protocol: ', url);
return url;
}
user().assert(isProtocolValid(replacement),
'The replacement url has invalid protocol: %s', replacement);
return replacement;
}
/**
* @return {VariableSource}
*/
getVariableSource() {
return this.variableSource_;
}
}
/**
* Extracts client ID from a _ga cookie.
* https://developers.google.com/analytics/devguides/collection/analyticsjs/cookies-user-id
* @param {string} gaCookie
* @return {string}
*/
export function extractClientIdFromGaCookie(gaCookie) {
return gaCookie.replace(/^(GA1|1)\.[\d-]+\./, '');
}
/**
* @param {!./ampdoc-impl.AmpDoc} ampdoc
*/
export function installUrlReplacementsServiceForDoc(ampdoc) {
registerServiceBuilderForDoc(
ampdoc,
'url-replace',
function(doc) {
return new UrlReplacements(doc, new GlobalVariableSource(doc));
});
}
/**
* @param {!./ampdoc-impl.AmpDoc} ampdoc
* @param {!Window} embedWin
* @param {!VariableSource} varSource
*/
export function installUrlReplacementsForEmbed(ampdoc, embedWin, varSource) {
installServiceInEmbedScope(embedWin, 'url-replace',
new UrlReplacements(ampdoc, varSource));
}
/**
* @typedef {{incomingFragment: string, outgoingFragment: string}}
*/
let ShareTrackingFragmentsDef;
| kamtschatka/amphtml | src/service/url-replacements-impl.js | JavaScript | apache-2.0 | 42,445 |
package com.chinaweather.android;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.chinaweather.android.db.City;
import com.chinaweather.android.db.County;
import com.chinaweather.android.db.Province;
import com.chinaweather.android.util.HttpUtil;
import com.chinaweather.android.util.Utility;
import org.litepal.crud.DataSupport;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class ChooseAreaFragment extends Fragment {
public static final int LEVEL_PROVINCE = 0;
public static final int LEVEL_CITY = 1;
public static final int LEVEL_COUNTY = 2;
private ProgressDialog progressDialog;
private TextView titleText;
private Button backButton;
private ListView listView;
private ArrayAdapter<String> adapter;
private List<String> dataList = new ArrayList<>();
/**
* 省列表
*/
private List<Province> provinceList;
/**
* 市列表
*/
private List<City> cityList;
/**
* 县列表
*/
private List<County> countyList;
/**
* 选中的省
*/
private Province selectedProvince;
/**
* 选中的市
*/
private City selectedCity;
/**
* 当前的级别
*/
private int currentLevel;
public ChooseAreaFragment() {
// Required empty public constructor
}
/**
* 先获取一些控件的实例, 然后初始化ArrayAdapter, 并将它设置为ListView中适配器。
* @param inflater
* @param container
* @param savedInstanceState
* @return
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.choose_area, container,false);
titleText = (TextView) view.findViewById(R.id.title_text);
backButton = (Button) view.findViewById(R.id.back_button);
listView = (ListView)view.findViewById(R.id.list_view);
adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, dataList);
listView.setAdapter(adapter);
return view;
}
/**
* 给ListView和Button设置点击事件。
* @param savedInstanceState
*/
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
/**
* 当点击某个省的时候, 就会进入到ListView的onItemClick()方法中, 这个时候就会根据当前的级别来
* 判断是去掉用queryCityies()方法还是queryCounties()方法。
*/
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (currentLevel == LEVEL_PROVINCE) {
selectedProvince = provinceList.get(position);
queryCities();
}else if (currentLevel == LEVEL_CITY ) {
selectedCity = cityList.get(position);
queryCounties();
}else if (currentLevel == LEVEL_COUNTY ) {
String weatherId = countyList.get(position).getWeatherId();
Intent intent = new Intent(getActivity(), WeatherActivity.class);
intent.putExtra("weather_id", weatherId);
startActivity(intent);
getActivity().finish();
}
}
});
backButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (currentLevel == LEVEL_COUNTY) {
queryCities();
}else if (currentLevel == LEVEL_CITY ) {
queryProvinces();
}
}
});
queryProvinces();
}
/**
* 查询全国所有的省, 优先从数据库查询, 如果没有查询到则再去服务器查询。
*/
private void queryProvinces() {
titleText.setText("中国");
backButton.setVisibility(View.GONE); //隐藏返回按钮
//从本地数据库读取省级数据。
provinceList = DataSupport.findAll(Province.class);
if (provinceList.size() > 0 ) {
dataList.clear();;
for (Province province : provinceList ) {
dataList.add(province.getProvinceName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel = LEVEL_PROVINCE;
}else {
//发起网络请求, 读取数据。
final String address = "http://guolin.tech/api/china";
queryFromServer(address, "province");
}
}
/**
* 查询选中的省的所有城市, 优先从数据库中查找, 如果没有则再到服务器上查询。
*/
private void queryCities() {
titleText.setText(selectedProvince.getProvinceName());
backButton.setVisibility(View.VISIBLE);
cityList = DataSupport.where("provinceid = ? " , String.valueOf(selectedProvince.getId())).find(City.class);
if (cityList.size() > 0) {
dataList.clear();
for (City city : cityList) {
dataList.add(city.getCityName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel = LEVEL_CITY;
}else {
int provinceCode = selectedProvince.getProvinceCode();
String address = "http://guolin.tech/api/china/" + provinceCode;
queryFromServer(address, "city");
}
}
/**
* 查询选中市内的所有县, 优先从数据库查询, 如果没有查询到再去服务器上查询。
*/
private void queryCounties() {
titleText.setText(selectedCity.getCityName());
backButton.setVisibility(View.VISIBLE);
countyList = DataSupport.where("cityid = ?" , String.valueOf(selectedCity.getId())).find(County.class);
if (countyList.size() > 0) {
dataList.clear();
for (County county : countyList ) {
dataList.add(county.getCountyName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel = LEVEL_COUNTY;
} else {
int provinceCode = selectedProvince.getProvinceCode();
int cityCode = selectedCity.getCityCode();
String address = "http://guolin.tech/api/china/"+provinceCode+"/"+cityCode;
queryFromServer(address , "county");
}
}
/**
* 根据传入的地址和类型从服务器上查询省市县数据。
* @param address
* @param type
*/
private void queryFromServer(String address , final String type) {
showProgressDialog();
HttpUtil.sendOkHttpRequest(address, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
//通过runOnUiThread()方法回到主线程处理逻辑。
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
Toast.makeText(getContext(),"加载失败",Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseText = response.body().string();
boolean result = false;
if ("province".equals(type)) {
result = Utility.handleProvinceResponse(responseText);
}else if ("city".equals(type)) {
result = Utility.handleCityResponse(responseText, selectedProvince.getId());
}else if ("county".equals(type)) {
result = Utility.handleCountyResponse(responseText, selectedCity.getId());
}
if (result) {
/**
* 由于queryProvinces()方法涉及到UI操作, 因此必须在主线程中调用, 这里借助runOnUiThread()
* 方法, 就会实现从子线程到主线程。
*/
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
if ("province".equals(type)) {
queryProvinces();
}else if ("city".equals(type)) {
queryCities();
}else if ("county".equals(type)) {
queryCounties();
}
}
});
}
}
});
}
/**
* 显示进度对话框
*/
private void showProgressDialog() {
if (progressDialog == null) {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("正在加载中...");
progressDialog.setCanceledOnTouchOutside(false);
}
progressDialog.show();
}
/**
* 关闭进度对话框
*/
private void closeProgressDialog() {
if (progressDialog != null ) {
progressDialog.dismiss();
}
}
}
| weiguolong/wglRepository | app/src/main/java/com/chinaweather/android/ChooseAreaFragment.java | Java | apache-2.0 | 10,217 |
package org.niklas.elemental.Elemental.client.elements;
import com.google.gwt.core.client.js.JsProperty;
import com.google.gwt.core.client.js.JsType;
@JsType(
prototype = "DOMTokenList"
)
interface DOMTokenList {
@JsProperty
int getLength();
String item(int index);
boolean contains(String token);
void add(String tokens);
void remove(String tokens);
boolean toggle(String token, boolean force);
}
| Nickel671/JsInteropGenerator | target/generated-sources/gwt/org/niklas/elemental/Elemental/client/elements/DOMTokenList.java | Java | apache-2.0 | 423 |
/********************************************************
Copyright 2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*********************************************************/
var Util = require('../util/util.js');
function Player() {
// Create an audio graph.
window.AudioContext = window.AudioContext || window.webkitAudioContext;
context = new AudioContext();
var analyser = context.createAnalyser();
//analyser.fftSize = 2048 * 2 * 2
// analyser.fftSize = (window.isMobile)? 2048 : 8192;
analyser.fftSize = (window.isMobile)?1024 : 2048;
analyser.smoothingTimeConstant = 0;
// Create a mix.
var mix = context.createGain();
// Create a bandpass filter.
var bandpass = context.createBiquadFilter();
bandpass.Q.value = 10;
bandpass.type = 'bandpass';
var filterGain = context.createGain();
filterGain.gain.value = 1;
// Connect audio processing graph
mix.connect(analyser);
analyser.connect(filterGain);
filterGain.connect(context.destination);
this.context = context;
this.mix = mix;
// this.bandpass = bandpass;
this.filterGain = filterGain;
this.analyser = analyser;
this.buffers = {};
// Connect an empty source node to the mix.
Util.loadTrackSrc(this.context, 'bin/snd/empty.mp3', function(buffer) {
var source = this.createSource_(buffer, true);
source.loop = true;
source.start(0);
}.bind(this));
}
Player.prototype.playSrc = function(src) {
// Stop all of the mic stuff.
this.filterGain.gain.value = 1;
if (this.input) {
this.input.disconnect();
this.input = null;
return;
}
if (this.buffers[src]) {
$('#loadingSound').fadeIn(100).delay(1000).fadeOut(500);
this.playHelper_(src);
return;
}
$('#loadingSound').fadeIn(100);
Util.loadTrackSrc(this.context, src, function(buffer) {
this.buffers[src] = buffer;
this.playHelper_(src);
$('#loadingSound').delay(500).fadeOut(500);
}.bind(this));
};
Player.prototype.playUserAudio = function(src) {
// Stop all of the mic stuff.
this.filterGain.gain.value = 1;
if (this.input) {
this.input.disconnect();
this.input = null;
return;
}
this.buffers['user'] = src.buffer;
this.playHelper_('user');
};
Player.prototype.playHelper_ = function(src) {
var buffer = this.buffers[src];
this.source = this.createSource_(buffer, true);
this.source.start(0);
if (!this.loop) {
this.playTimer = setTimeout(function() {
this.stop();
}.bind(this), buffer.duration * 2000);
}
};
Player.prototype.live = function() {
// The AudioContext may be in a suspended state prior to the page receiving a user
// gesture. If it is, resume it.
if (this.context.state === 'suspended') {
this.context.resume();
}
if(window.isIOS){
window.parent.postMessage('error2','*');
console.log("cant use mic on ios");
}else{
if (this.input) {
this.input.disconnect();
this.input = null;
return;
}
var self = this;
navigator.mediaDevices.getUserMedia({audio: true}).then(function(stream) {
self.onStream_(stream);
}).catch(function() {
self.onStreamError(this);
});
this.filterGain.gain.value = 0;
}
};
Player.prototype.onStream_ = function(stream) {
var input = this.context.createMediaStreamSource(stream);
input.connect(this.mix);
this.input = input;
this.stream = stream;
};
Player.prototype.onStreamError_ = function(e) {
// TODO: Error handling.
};
Player.prototype.setLoop = function(loop) {
this.loop = loop;
};
Player.prototype.createSource_ = function(buffer, loop) {
var source = this.context.createBufferSource();
source.buffer = buffer;
source.loop = loop;
source.connect(this.mix);
return source;
};
Player.prototype.setMicrophoneInput = function() {
// TODO: Implement me!
};
Player.prototype.stop = function() {
if (this.source) {
this.source.stop(0);
this.source = null;
clearTimeout(this.playTimer);
this.playTimer = null;
}
if (this.input) {
this.input.disconnect();
this.input = null;
return;
}
};
Player.prototype.getAnalyserNode = function() {
return this.analyser;
};
Player.prototype.setBandpassFrequency = function(freq) {
if (freq == null) {
console.log('Removing bandpass filter');
// Remove the effect of the bandpass filter completely, connecting the mix to the analyser directly.
this.mix.disconnect();
this.mix.connect(this.analyser);
} else {
// console.log('Setting bandpass frequency to %d Hz', freq);
// Only set the frequency if it's specified, otherwise use the old one.
this.bandpass.frequency.value = freq;
this.mix.disconnect();
this.mix.connect(this.bandpass);
// bandpass is connected to filterGain.
this.filterGain.connect(this.analyser);
}
};
Player.prototype.playTone = function(freq) {
if (!this.osc) {
this.osc = this.context.createOscillator();
this.osc.connect(this.mix);
this.osc.type = 'sine';
this.osc.start(0);
}
this.osc.frequency.value = freq;
this.filterGain.gain.value = .2;
};
Player.prototype.stopTone = function() {
this.osc.stop(0);
this.osc = null;
};
module.exports = Player;
| googlecreativelab/chrome-music-lab | spectrogram/src/javascripts/UI/player.js | JavaScript | apache-2.0 | 5,514 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.dubbo.rpc.filter;
import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.beanutil.JavaBeanAccessor;
import com.alibaba.dubbo.common.beanutil.JavaBeanDescriptor;
import com.alibaba.dubbo.common.beanutil.JavaBeanSerializeUtil;
import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import com.alibaba.dubbo.common.utils.PojoUtils;
import com.alibaba.dubbo.common.utils.ReflectUtils;
import com.alibaba.dubbo.rpc.Filter;
import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.Result;
import com.alibaba.dubbo.rpc.RpcException;
import com.alibaba.dubbo.rpc.RpcInvocation;
import com.alibaba.dubbo.rpc.RpcResult;
import com.alibaba.dubbo.rpc.service.GenericException;
import com.alibaba.dubbo.rpc.support.ProtocolUtils;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* GenericImplInvokerFilter
*/
@Activate(group = Constants.CONSUMER, value = Constants.GENERIC_KEY, order = 20000)
public class GenericImplFilter implements Filter {
private static final Logger logger = LoggerFactory.getLogger(GenericImplFilter.class);
private static final Class<?>[] GENERIC_PARAMETER_TYPES = new Class<?>[]{String.class, String[].class, Object[].class};
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
String generic = invoker.getUrl().getParameter(Constants.GENERIC_KEY);
if (ProtocolUtils.isGeneric(generic)
&& !Constants.$INVOKE.equals(invocation.getMethodName())
&& invocation instanceof RpcInvocation) {
RpcInvocation invocation2 = (RpcInvocation) invocation;
String methodName = invocation2.getMethodName();
Class<?>[] parameterTypes = invocation2.getParameterTypes();
Object[] arguments = invocation2.getArguments();
String[] types = new String[parameterTypes.length];
for (int i = 0; i < parameterTypes.length; i++) {
types[i] = ReflectUtils.getName(parameterTypes[i]);
}
Object[] args;
if (ProtocolUtils.isBeanGenericSerialization(generic)) {
args = new Object[arguments.length];
for (int i = 0; i < arguments.length; i++) {
args[i] = JavaBeanSerializeUtil.serialize(arguments[i], JavaBeanAccessor.METHOD);
}
} else {
args = PojoUtils.generalize(arguments);
}
invocation2.setMethodName(Constants.$INVOKE);
invocation2.setParameterTypes(GENERIC_PARAMETER_TYPES);
invocation2.setArguments(new Object[]{methodName, types, args});
Result result = invoker.invoke(invocation2);
if (!result.hasException()) {
Object value = result.getValue();
try {
Method method = invoker.getInterface().getMethod(methodName, parameterTypes);
if (ProtocolUtils.isBeanGenericSerialization(generic)) {
if (value == null) {
return new RpcResult(value);
} else if (value instanceof JavaBeanDescriptor) {
return new RpcResult(JavaBeanSerializeUtil.deserialize((JavaBeanDescriptor) value));
} else {
throw new RpcException(
new StringBuilder(64)
.append("The type of result value is ")
.append(value.getClass().getName())
.append(" other than ")
.append(JavaBeanDescriptor.class.getName())
.append(", and the result is ")
.append(value).toString());
}
} else {
return new RpcResult(PojoUtils.realize(value, method.getReturnType(), method.getGenericReturnType()));
}
} catch (NoSuchMethodException e) {
throw new RpcException(e.getMessage(), e);
}
} else if (result.getException() instanceof GenericException) {
GenericException exception = (GenericException) result.getException();
try {
String className = exception.getExceptionClass();
Class<?> clazz = ReflectUtils.forName(className);
Throwable targetException = null;
Throwable lastException = null;
try {
targetException = (Throwable) clazz.newInstance();
} catch (Throwable e) {
lastException = e;
for (Constructor<?> constructor : clazz.getConstructors()) {
try {
targetException = (Throwable) constructor.newInstance(new Object[constructor.getParameterTypes().length]);
break;
} catch (Throwable e1) {
lastException = e1;
}
}
}
if (targetException != null) {
try {
Field field = Throwable.class.getDeclaredField("detailMessage");
if (!field.isAccessible()) {
field.setAccessible(true);
}
field.set(targetException, exception.getExceptionMessage());
} catch (Throwable e) {
logger.warn(e.getMessage(), e);
}
result = new RpcResult(targetException);
} else if (lastException != null) {
throw lastException;
}
} catch (Throwable e) {
throw new RpcException("Can not deserialize exception " + exception.getExceptionClass() + ", message: " + exception.getExceptionMessage(), e);
}
}
return result;
}
if (invocation.getMethodName().equals(Constants.$INVOKE)
&& invocation.getArguments() != null
&& invocation.getArguments().length == 3
&& ProtocolUtils.isGeneric(generic)) {
Object[] args = (Object[]) invocation.getArguments()[2];
if (ProtocolUtils.isJavaGenericSerialization(generic)) {
for (Object arg : args) {
if (!(byte[].class == arg.getClass())) {
error(byte[].class.getName(), arg.getClass().getName());
}
}
} else if (ProtocolUtils.isBeanGenericSerialization(generic)) {
for (Object arg : args) {
if (!(arg instanceof JavaBeanDescriptor)) {
error(JavaBeanDescriptor.class.getName(), arg.getClass().getName());
}
}
}
((RpcInvocation) invocation).setAttachment(
Constants.GENERIC_KEY, invoker.getUrl().getParameter(Constants.GENERIC_KEY));
}
return invoker.invoke(invocation);
}
private void error(String expected, String actual) throws RpcException {
throw new RpcException(
new StringBuilder(32)
.append("Generic serialization [")
.append(Constants.GENERIC_SERIALIZATION_NATIVE_JAVA)
.append("] only support message type ")
.append(expected)
.append(" and your message type is ")
.append(actual).toString());
}
} | dadarom/dubbo | dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/GenericImplFilter.java | Java | apache-2.0 | 9,168 |
package rpcd
import (
"github.com/Cloud-Foundations/Dominator/lib/errors"
"github.com/Cloud-Foundations/Dominator/lib/srpc"
"github.com/Cloud-Foundations/Dominator/proto/hypervisor"
)
func (t *srpcType) ChangeAddressPool(conn *srpc.Conn,
request hypervisor.ChangeAddressPoolRequest,
reply *hypervisor.ChangeAddressPoolResponse) error {
*reply = hypervisor.ChangeAddressPoolResponse{
Error: errors.ErrorToString(t.changeAddressPool(conn, request))}
return nil
}
func (t *srpcType) changeAddressPool(conn *srpc.Conn,
request hypervisor.ChangeAddressPoolRequest) error {
if len(request.AddressesToAdd) > 0 {
err := t.manager.AddAddressesToPool(request.AddressesToAdd)
if err != nil {
return err
}
}
if len(request.AddressesToRemove) > 0 {
err := t.manager.RemoveAddressesFromPool(request.AddressesToRemove)
if err != nil {
return err
}
}
if len(request.MaximumFreeAddresses) > 0 {
err := t.manager.RemoveExcessAddressesFromPool(
request.MaximumFreeAddresses)
if err != nil {
return err
}
}
return nil
}
| rgooch/Dominator | hypervisor/rpcd/changeAddressPool.go | GO | apache-2.0 | 1,050 |
/**
* Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.wfu.common.utils;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
* @author wanye
* @date Dec 14, 2008
* @version v 1.0
* @description 得到当前应用的系统路径
*/
public class SystemPath {
public static String getSysPath() {
String path = Thread.currentThread().getContextClassLoader()
.getResource("").toString();
String temp = path.replaceFirst("file:/", "").replaceFirst(
"WEB-INF/classes/", "");
String separator = System.getProperty("file.separator");
String resultPath = temp.replaceAll("/", separator + separator);
return resultPath;
}
public static String getClassPath() {
String path = Thread.currentThread().getContextClassLoader()
.getResource("").toString();
String temp = path.replaceFirst("file:/", "");
String separator = System.getProperty("file.separator");
String resultPath = temp.replaceAll("/", separator + separator);
return resultPath;
}
public static String getSystempPath() {
return System.getProperty("java.io.tmpdir");
}
public static String getSeparator() {
return System.getProperty("file.separator");
}
/**
* 获取服务器的地址
* @return
*/
public static String getServerPath(){
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
return basePath;
}
public static void main(String[] args) {
System.out.println(getSysPath());
System.out.println(System.getProperty("java.io.tmpdir"));
System.out.println(getSeparator());
System.out.println(getClassPath());
}
}
| 347184068/jybl | src/main/java/com/wfu/common/utils/SystemPath.java | Java | apache-2.0 | 1,970 |
using System;
// ReSharper disable CheckNamespace
namespace DasMulli.Win32.ServiceUtils
{
internal delegate void ServiceControlHandler(ServiceControlCommand control, uint eventType, IntPtr eventData, IntPtr eventContext);
} | tonyredondo/TWCore2 | src/TWCore.Services/DasMulli.Win32.ServiceUtils/ServiceControlHandler.cs | C# | apache-2.0 | 232 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI;
using System.Web.UI.Adapters;
using System.Web.UI.WebControls;
namespace FrameworkLibrary.Classes.ControlAdapters
{
public class TreeViewAdapter : ControlAdapter
{
protected CustomTreeView Target
{
get
{
return (this.Control as CustomTreeView);
}
}
protected override void Render(HtmlTextWriter writer)
{
writer.WriteFullBeginTag("ul");
writer.WriteLine();
foreach (CustomTreeNode node in Target.Nodes)
{
RenderNode(node, writer);
}
writer.WriteLine();
writer.WriteEndTag("ul");
}
private void RenderNode(CustomTreeNode node, HtmlTextWriter writer)
{
writer.WriteFullBeginTag("li " + node.GetLIAttributesAsString());
writer.WriteFullBeginTag("a href=\"" + node.NavigateUrl + "\"" + node.GetLinkAttributesAsString());
writer.Write(node.Text);
writer.WriteEndTag("a");
if (node.ChildNodes.Count > 0)
{
writer.WriteFullBeginTag("ul");
foreach (CustomTreeNode childNode in node.ChildNodes)
{
RenderNode(childNode, writer);
}
writer.WriteEndTag("ul");
}
writer.WriteEndTag("li");
}
}
} | MacdonaldRobinson/FlexDotnetCMS | FrameworkLibrary/Classes/ControlAdapters/TreeViewAdapter.cs | C# | apache-2.0 | 1,555 |
package redis
import (
"encoding/json"
"errors"
"fmt"
"github.com/go-redis/redis"
"github.com/mainflux/mainflux/logger"
"github.com/mainflux/mainflux/lora"
)
const (
keyType = "lora"
keyDevEUI = "dev_eui"
keyAppID = "app_id"
group = "mainflux.lora"
stream = "mainflux.things"
thingPrefix = "thing."
thingCreate = thingPrefix + "create"
thingUpdate = thingPrefix + "update"
thingRemove = thingPrefix + "remove"
channelPrefix = "channel."
channelCreate = channelPrefix + "create"
channelUpdate = channelPrefix + "update"
channelRemove = channelPrefix + "remove"
exists = "BUSYGROUP Consumer Group name already exists"
)
var (
errMetadataType = errors.New("field lora is missing in the metadata")
errMetadataFormat = errors.New("malformed metadata")
errMetadataAppID = errors.New("application ID not found in channel metadatada")
errMetadataDevEUI = errors.New("device EUI not found in thing metadatada")
)
// Subscriber represents event source for things and channels provisioning.
type Subscriber interface {
// Subscribes to geven subject and receives events.
Subscribe(string) error
}
type eventStore struct {
svc lora.Service
client *redis.Client
consumer string
logger logger.Logger
}
// NewEventStore returns new event store instance.
func NewEventStore(svc lora.Service, client *redis.Client, consumer string, log logger.Logger) Subscriber {
return eventStore{
svc: svc,
client: client,
consumer: consumer,
logger: log,
}
}
func (es eventStore) Subscribe(subject string) error {
err := es.client.XGroupCreateMkStream(stream, group, "$").Err()
if err != nil && err.Error() != exists {
return err
}
for {
streams, err := es.client.XReadGroup(&redis.XReadGroupArgs{
Group: group,
Consumer: es.consumer,
Streams: []string{stream, ">"},
Count: 100,
}).Result()
if err != nil || len(streams) == 0 {
continue
}
for _, msg := range streams[0].Messages {
event := msg.Values
var err error
switch event["operation"] {
case thingCreate:
cte, derr := decodeCreateThing(event)
if derr != nil {
err = derr
break
}
err = es.handleCreateThing(cte)
case thingUpdate:
ute, derr := decodeCreateThing(event)
if derr != nil {
err = derr
break
}
err = es.handleCreateThing(ute)
case thingRemove:
rte := decodeRemoveThing(event)
err = es.handleRemoveThing(rte)
case channelCreate:
cce, derr := decodeCreateChannel(event)
if derr != nil {
err = derr
break
}
err = es.handleCreateChannel(cce)
case channelUpdate:
uce, derr := decodeCreateChannel(event)
if derr != nil {
err = derr
break
}
err = es.handleCreateChannel(uce)
case channelRemove:
rce := decodeRemoveChannel(event)
err = es.handleRemoveChannel(rce)
}
if err != nil && err != errMetadataType {
es.logger.Warn(fmt.Sprintf("Failed to handle event sourcing: %s", err.Error()))
break
}
es.client.XAck(stream, group, msg.ID)
}
}
}
func decodeCreateThing(event map[string]interface{}) (createThingEvent, error) {
strmeta := read(event, "metadata", "{}")
var metadata map[string]interface{}
if err := json.Unmarshal([]byte(strmeta), &metadata); err != nil {
return createThingEvent{}, err
}
cte := createThingEvent{
id: read(event, "id", ""),
}
m, ok := metadata[keyType]
if !ok {
return createThingEvent{}, errMetadataType
}
lm, ok := m.(map[string]interface{})
if !ok {
return createThingEvent{}, errMetadataFormat
}
val, ok := lm[keyDevEUI].(string)
if !ok {
return createThingEvent{}, errMetadataDevEUI
}
cte.loraDevEUI = val
return cte, nil
}
func decodeRemoveThing(event map[string]interface{}) removeThingEvent {
return removeThingEvent{
id: read(event, "id", ""),
}
}
func decodeCreateChannel(event map[string]interface{}) (createChannelEvent, error) {
strmeta := read(event, "metadata", "{}")
var metadata map[string]interface{}
if err := json.Unmarshal([]byte(strmeta), &metadata); err != nil {
return createChannelEvent{}, err
}
cce := createChannelEvent{
id: read(event, "id", ""),
}
m, ok := metadata[keyType]
if !ok {
return createChannelEvent{}, errMetadataType
}
lm, ok := m.(map[string]interface{})
if !ok {
return createChannelEvent{}, errMetadataFormat
}
val, ok := lm[keyAppID].(string)
if !ok {
return createChannelEvent{}, errMetadataAppID
}
cce.loraAppID = val
return cce, nil
}
func decodeRemoveChannel(event map[string]interface{}) removeChannelEvent {
return removeChannelEvent{
id: read(event, "id", ""),
}
}
func (es eventStore) handleCreateThing(cte createThingEvent) error {
return es.svc.CreateThing(cte.id, cte.loraDevEUI)
}
func (es eventStore) handleRemoveThing(rte removeThingEvent) error {
return es.svc.RemoveThing(rte.id)
}
func (es eventStore) handleCreateChannel(cce createChannelEvent) error {
return es.svc.CreateChannel(cce.id, cce.loraAppID)
}
func (es eventStore) handleRemoveChannel(rce removeChannelEvent) error {
return es.svc.RemoveChannel(rce.id)
}
func read(event map[string]interface{}, key, def string) string {
val, ok := event[key].(string)
if !ok {
return def
}
return val
}
| Mainflux/mainflux-lite | lora/redis/streams.go | GO | apache-2.0 | 5,245 |
#!/usr/bin/python
"""usage: python stylechecker.py /path/to/the/c/code"""
import os
import sys
import string
import re
WHITE = '\033[97m'
CYAN = '\033[96m'
BLUE = '\033[94m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
ENDC = '\033[0m'
def check_file(file):
if re.search('\.[c|h]$', file) == None:
return
f = open(file)
i = 1
file_name_printed = False
for line in f:
line = line.replace('\n', '')
# check the number of columns greater than 80
if len(line) > 80:
if not file_name_printed:
print RED + file + ':' + ENDC
file_name_printed = True
print (GREEN + ' [>80]:' + BLUE + ' #%d(%d)' + WHITE + ':%s') % (i, len(line), line) + ENDC
# check the TAB key
if string.find(line, '\t') >= 0:
if not file_name_printed:
print RED + file + ':' + ENDC
file_name_printed = True
print (YELLOW + ' [TAB]:' + BLUE + ' #%d(%d)' + WHITE + ':%s') % (i, len(line), line) + ENDC
# check blank lines
if line.isspace():
if not file_name_printed:
print RED + file + ':' + ENDC
file_name_printed = True
print (CYAN + ' [BLK]:' + BLUE + ' #%d(%d)' + WHITE + ':%s') % (i, len(line), line) + ENDC
i = i + 1
f.close()
def walk_dir(dir):
for root, dirs, files in os.walk(dir):
for f in files:
s = root + '/' + f
check_file(s)
for d in dirs:
walk_dir(d)
walk_dir(sys.argv[1])
| izenecloud/nginx | tengine/contrib/stylechecker.py | Python | apache-2.0 | 1,596 |
package com.javaasc.entity.api;
import java.util.List;
public interface JascValues {
List<String> getValues();
}
| alonana/JavaAsc | entity/src/main/java/com/javaasc/entity/api/JascValues.java | Java | apache-2.0 | 119 |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
fast = slow = head
for i in range(n):
fast = fast.next
if fast is None:
return head.next
while fast.next:
slow = slow.next
fast = fast.next
# print(slow.next, fast)
slow.next = slow.next.next
return head
def test(self):
intarrToTest = [1, 2, 3, 4, 5]
head = ListNode(intarrToTest[0])
x = head
for s in intarrToTest[1:]:
temp = ListNode(s)
x.next = temp
x = x.next
head = self.removeNthFromEnd(head, 4)
x = head
while x:
print(x.val, end=' ')
x = x.next
print()
test = Solution()
print(test.test())
| rx2130/Leetcode | python/19 Remove Nth Node From End of List.py | Python | apache-2.0 | 1,039 |
import datetime
from unittest import mock
import unittest
from django.utils import timezone
from unittest.mock import Mock, PropertyMock
from django.test import TestCase
from django.contrib.sessions.models import Session
# from core.tasks import send_outcome, check_anonymous
from lti.tasks import send_outcome
class CeleryTasksTest(TestCase):
@unittest.skip("skip unless fixed")
@mock.patch('mysite.celery.UserSession.objects.filter')
@mock.patch('mysite.celery.User.objects.filter')
def test_check_anonymous_user_session_no_session(self, mock_User_filter, mock_UserSession_filter):
mock_user = Mock(id=1)
call_mock_User_filter = [mock_user]
mock_session = Mock(id=2)
# user_session.session
p = PropertyMock(return_value=3, side_effect=Session.DoesNotExist('Object Does not exist'))
type(mock_session).session = p
call_mock_UserSession_filter = [mock_session]
mock_User_filter.return_value = call_mock_User_filter
mock_UserSession_filter.return_value = call_mock_UserSession_filter
mock_user_del = Mock()
mock_user.delete = mock_user_del
# response = check_anonymous()
mock_user_del.assert_called_once_with()
mock_User_filter.assert_called_with(groups__name='Temporary')
mock_UserSession_filter.assert_called_with(user__groups__name='Temporary')
@unittest.skip("skip unless fixed")
@mock.patch('mysite.celery.UserSession.objects.filter')
@mock.patch('mysite.celery.User.objects.filter')
def test_check_anonymous_user_session_has_session(self, mock_User_filter, mock_UserSession_filter):
mock_user = Mock(id=1)
call_mock_User_filter = [mock_user]
mock_session = Mock(id=2)
# user_session.session
mock_session.session.expire_date = timezone.now() - datetime.timedelta(days=1)
sess_session_del = Mock()
sess_user_del = Mock()
mock_session.session.delete = sess_session_del
mock_session.user.delete = sess_user_del
call_mock_UserSession_filter = [mock_session]
mock_User_filter.return_value = call_mock_User_filter
mock_UserSession_filter.return_value = call_mock_UserSession_filter
mock_user_del = Mock()
mock_user.delete = mock_user_del
# response = check_anonymous()
sess_session_del.assert_called_once_with()
sess_user_del.assert_called_once_with()
mock_user_del.assert_called_once_with()
mock_User_filter.assert_called_with(groups__name='Temporary')
mock_UserSession_filter.assert_called_with(user__groups__name='Temporary')
@mock.patch('lti.tasks.GradedLaunch.objects.get')
@mock.patch('lti.tasks.send_score_update')
def test_send_outcome(self, mock_send_score_update, mock_GradedLaunch_get):
get_mock_ret_val = Mock()
mock_GradedLaunch_get.return_value = get_mock_ret_val
send_outcome('0', assignment_id=1)
mock_GradedLaunch_get.assert_called_once_with(id=1)
mock_send_score_update.assert_called_once_with(get_mock_ret_val, '0')
| cjlee112/socraticqs2 | mysite/mysite/tests/celery.py | Python | apache-2.0 | 3,119 |
package com.commit451.parcelcheck.sample.brokenModels;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.Date;
/**
* A phone model, which is missing a few parcelable calls
*/
public class Phone implements Parcelable {
private int modelNumber;
private String manufacturer;
private Date releaseDate;
public Phone() {
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.modelNumber);
//Comment this out, which makes the parcel test fail
//dest.writeString(this.manufacturer);
dest.writeLong(this.releaseDate != null ? this.releaseDate.getTime() : -1);
}
protected Phone(Parcel in) {
this.modelNumber = in.readInt();
this.manufacturer = in.readString();
long tmpReleaseDate = in.readLong();
this.releaseDate = tmpReleaseDate == -1 ? null : new Date(tmpReleaseDate);
}
public static final Parcelable.Creator<Phone> CREATOR = new Parcelable.Creator<Phone>() {
@Override
public Phone createFromParcel(Parcel source) {
return new Phone(source);
}
@Override
public Phone[] newArray(int size) {
return new Phone[size];
}
};
}
| Commit451/ParcelCheck | app/src/main/java/com/commit451/parcelcheck/sample/brokenModels/Phone.java | Java | apache-2.0 | 1,342 |
# Copyright (c) 2014 Rackspace, 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.
class ValidationFailed(ValueError):
"""User input was inconsistent with API restrictions."""
def __init__(self, msg, *args, **kwargs):
msg = msg.format(*args, **kwargs)
super(ValidationFailed, self).__init__(msg)
class ValidationProgrammingError(ValueError):
"""Caller did not map validations correctly."""
def __init__(self, msg, *args, **kwargs):
msg = msg.format(*args, **kwargs)
super(ValidationProgrammingError, self).__init__(msg)
| obulpathi/cdn1 | cdn/transport/validators/stoplight/exceptions.py | Python | apache-2.0 | 1,077 |
import {TaskQueue} from './task-queue.js';
import { Task } from './task.js';
/**
* An object that controls when tasks are executed from a queue or set of
* queues.
*/
export interface QueueScheduler<Q extends TaskQueue<T>, T extends Task<any>> {
schedule(queue: Q): void;
}
| PolymerLabs/async-demos | packages/scheduler/src/lib/queue-scheduler.ts | TypeScript | apache-2.0 | 280 |
# Be sure to restart your server when you modify this file.
IBeaconCMS::Application.config.session_store :cookie_store, key: '_iBeaconCMS_session'
| SlalomDigital/iBeaconCMS | config/initializers/session_store.rb | Ruby | apache-2.0 | 148 |
// Copyright 2016 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// These event types are shared between the Events API and used as Webhook payloads.
package github
// CommitCommentEvent is triggered when a commit comment is created.
// The Webhook event name is "commit_comment".
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#commitcommentevent
type CommitCommentEvent struct {
Comment *RepositoryComment `json:"comment,omitempty"`
// The following fields are only populated by Webhook events.
Action *string `json:"action,omitempty"`
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// CreateEvent represents a created repository, branch, or tag.
// The Webhook event name is "create".
//
// Note: webhooks will not receive this event for created repositories.
// Additionally, webhooks will not receive this event for tags if more
// than three tags are pushed at once.
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#createevent
type CreateEvent struct {
Ref *string `json:"ref,omitempty"`
// RefType is the object that was created. Possible values are: "repository", "branch", "tag".
RefType *string `json:"ref_type,omitempty"`
MasterBranch *string `json:"master_branch,omitempty"`
Description *string `json:"description,omitempty"`
// The following fields are only populated by Webhook events.
PusherType *string `json:"pusher_type,omitempty"`
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// DeleteEvent represents a deleted branch or tag.
// The Webhook event name is "delete".
//
// Note: webhooks will not receive this event for tags if more than three tags
// are deleted at once.
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#deleteevent
type DeleteEvent struct {
Ref *string `json:"ref,omitempty"`
// RefType is the object that was deleted. Possible values are: "branch", "tag".
RefType *string `json:"ref_type,omitempty"`
// The following fields are only populated by Webhook events.
PusherType *string `json:"pusher_type,omitempty"`
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// DeploymentEvent represents a deployment.
// The Webhook event name is "deployment".
//
// Events of this type are not visible in timelines, they are only used to trigger hooks.
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#deploymentevent
type DeploymentEvent struct {
Deployment *Deployment `json:"deployment,omitempty"`
Repo *Repository `json:"repository,omitempty"`
// The following fields are only populated by Webhook events.
Sender *User `json:"sender,omitempty"`
}
// DeploymentStatusEvent represents a deployment status.
// The Webhook event name is "deployment_status".
//
// Events of this type are not visible in timelines, they are only used to trigger hooks.
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#deploymentstatusevent
type DeploymentStatusEvent struct {
Deployment *Deployment `json:"deployment,omitempty"`
DeploymentStatus *DeploymentStatus `json:"deployment_status,omitempty"`
Repo *Repository `json:"repository,omitempty"`
// The following fields are only populated by Webhook events.
Sender *User `json:"sender,omitempty"`
}
// ForkEvent is triggered when a user forks a repository.
// The Webhook event name is "fork".
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#forkevent
type ForkEvent struct {
// Forkee is the created repository.
Forkee *Repository `json:"forkee,omitempty"`
// The following fields are only populated by Webhook events.
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// Page represents a single Wiki page.
type Page struct {
PageName *string `json:"page_name,omitempty"`
Title *string `json:"title,omitempty"`
Summary *string `json:"summary,omitempty"`
Action *string `json:"action,omitempty"`
SHA *string `json:"sha,omitempty"`
HTMLURL *string `json:"html_url,omitempty"`
}
// GollumEvent is triggered when a Wiki page is created or updated.
// The Webhook event name is "gollum".
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#gollumevent
type GollumEvent struct {
Pages []*Page `json:"pages,omitempty"`
// The following fields are only populated by Webhook events.
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// IssueActivityEvent represents the payload delivered by Issue webhook.
//
// Deprecated: Use IssuesEvent instead.
type IssueActivityEvent struct {
Action *string `json:"action,omitempty"`
Issue *Issue `json:"issue,omitempty"`
// The following fields are only populated by Webhook events.
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// EditChange represents the changes when an issue, pull request, or comment has
// been edited.
type EditChange struct {
Title *struct {
From *string `json:"from,omitempty"`
} `json:"title,omitempty"`
Body *struct {
From *string `json:"from,omitempty"`
} `json:"body,omitempty"`
}
// IntegrationInstallationEvent is triggered when an integration is created or deleted.
// The Webhook event name is "integration_installation".
//
// GitHub docs: https://developer.github.com/early-access/integrations/webhooks/#integrationinstallationevent
type IntegrationInstallationEvent struct {
// The action that was performed. Possible values for an "integration_installation"
// event are: "created", "deleted".
Action *string `json:"action,omitempty"`
Installation *Installation `json:"installation,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// IntegrationInstallationRepositoriesEvent is triggered when an integration repository
// is added or removed. The Webhook event name is "integration_installation_repositories".
//
// GitHub docs: https://developer.github.com/early-access/integrations/webhooks/#integrationinstallationrepositoriesevent
type IntegrationInstallationRepositoriesEvent struct {
// The action that was performed. Possible values for an "integration_installation_repositories"
// event are: "added", "removed".
Action *string `json:"action,omitempty"`
Installation *Installation `json:"installation,omitempty"`
RepositoriesAdded []*Repository `json:"repositories_added,omitempty"`
RepositoriesRemoved []*Repository `json:"repositories_removed,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// IssueCommentEvent is triggered when an issue comment is created on an issue
// or pull request.
// The Webhook event name is "issue_comment".
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#issuecommentevent
type IssueCommentEvent struct {
// Action is the action that was performed on the comment.
// Possible values are: "created", "edited", "deleted".
Action *string `json:"action,omitempty"`
Issue *Issue `json:"issue,omitempty"`
Comment *IssueComment `json:"comment,omitempty"`
// The following fields are only populated by Webhook events.
Changes *EditChange `json:"changes,omitempty"`
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// IssuesEvent is triggered when an issue is assigned, unassigned, labeled,
// unlabeled, opened, closed, or reopened.
// The Webhook event name is "issues".
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#issuesevent
type IssuesEvent struct {
// Action is the action that was performed. Possible values are: "assigned",
// "unassigned", "labeled", "unlabeled", "opened", "closed", "reopened", "edited".
Action *string `json:"action,omitempty"`
Issue *Issue `json:"issue,omitempty"`
Assignee *User `json:"assignee,omitempty"`
Label *Label `json:"label,omitempty"`
// The following fields are only populated by Webhook events.
Changes *EditChange `json:"changes,omitempty"`
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// LabelEvent is triggered when a repository's label is created, edited, or deleted.
// The Webhook event name is "label"
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#labelevent
type LabelEvent struct {
// Action is the action that was performed. Possible values are:
// "created", "edited", "deleted"
Action *string `json:"action,omitempty"`
Label *Label `json:"label,omitempty"`
// The following fields are only populated by Webhook events.
Changes *EditChange `json:"changes,omitempty"`
Repo *Repository `json:"repository,omitempty"`
Org *Organization `json:"organization,omitempty"`
}
// MemberEvent is triggered when a user is added as a collaborator to a repository.
// The Webhook event name is "member".
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#memberevent
type MemberEvent struct {
// Action is the action that was performed. Possible value is: "added".
Action *string `json:"action,omitempty"`
Member *User `json:"member,omitempty"`
// The following fields are only populated by Webhook events.
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// MembershipEvent is triggered when a user is added or removed from a team.
// The Webhook event name is "membership".
//
// Events of this type are not visible in timelines, they are only used to
// trigger organization webhooks.
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#membershipevent
type MembershipEvent struct {
// Action is the action that was performed. Possible values are: "added", "removed".
Action *string `json:"action,omitempty"`
// Scope is the scope of the membership. Possible value is: "team".
Scope *string `json:"scope,omitempty"`
Member *User `json:"member,omitempty"`
Team *Team `json:"team,omitempty"`
// The following fields are only populated by Webhook events.
Org *Organization `json:"organization,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// MilestoneEvent is triggered when a milestone is created, closed, opened, edited, or deleted.
// The Webhook event name is "milestone".
//
// Github docs: https://developer.github.com/v3/activity/events/types/#milestoneevent
type MilestoneEvent struct {
// Action is the action that was performed. Possible values are:
// "created", "closed", "opened", "edited", "deleted"
Action *string `json:"action,omitempty"`
Milestone *Milestone `json:"milestone,omitempty"`
// The following fields are only populated by Webhook events.
Changes *EditChange `json:"changes,omitempty"`
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
Org *Organization `json:"organization,omitempty"`
}
// OrganizationEvent is triggered when a user is added, removed, or invited to an organization.
// Events of this type are not visible in timelines. These events are only used to trigger organization hooks.
// Webhook event name is "organization".
//
// Github docs: https://developer.github.com/v3/activity/events/types/#organizationevent
type OrganizationEvent struct {
// Action is the action that was performed.
// Can be one of "member_added", "member_removed", or "member_invited".
Action *string `json:"action,omitempty"`
// Invitaion is the invitation for the user or email if the action is "member_invited".
Invitation *Invitation `json:"invitation,omitempty"`
// Membership is the membership between the user and the organization.
// Not present when the action is "member_invited".
Membership *Membership `json:"membership,omitempty"`
Organization *Organization `json:"organization,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// PageBuildEvent represents an attempted build of a GitHub Pages site, whether
// successful or not.
// The Webhook event name is "page_build".
//
// This event is triggered on push to a GitHub Pages enabled branch (gh-pages
// for project pages, master for user and organization pages).
//
// Events of this type are not visible in timelines, they are only used to trigger hooks.
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#pagebuildevent
type PageBuildEvent struct {
Build *PagesBuild `json:"build,omitempty"`
// The following fields are only populated by Webhook events.
ID *int `json:"id,omitempty"`
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// PingEvent is triggered when a Webhook is added to GitHub.
//
// GitHub docs: https://developer.github.com/webhooks/#ping-event
type PingEvent struct {
// Random string of GitHub zen.
Zen *string `json:"zen,omitempty"`
// The ID of the webhook that triggered the ping.
HookID *int `json:"hook_id,omitempty"`
// The webhook configuration.
Hook *Hook `json:"hook,omitempty"`
}
// PublicEvent is triggered when a private repository is open sourced.
// According to GitHub: "Without a doubt: the best GitHub event."
// The Webhook event name is "public".
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#publicevent
type PublicEvent struct {
// The following fields are only populated by Webhook events.
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// PullRequestEvent is triggered when a pull request is assigned, unassigned,
// labeled, unlabeled, opened, closed, reopened, or synchronized.
// The Webhook event name is "pull_request".
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#pullrequestevent
type PullRequestEvent struct {
// Action is the action that was performed. Possible values are: "assigned",
// "unassigned", "labeled", "unlabeled", "opened", "closed", or "reopened",
// "synchronize", "edited". If the action is "closed" and the merged key is false,
// the pull request was closed with unmerged commits. If the action is "closed"
// and the merged key is true, the pull request was merged.
Action *string `json:"action,omitempty"`
Number *int `json:"number,omitempty"`
PullRequest *PullRequest `json:"pull_request,omitempty"`
// The following fields are only populated by Webhook events.
Changes *EditChange `json:"changes,omitempty"`
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// PullRequestReviewEvent is triggered when a review is submitted on a pull
// request.
// The Webhook event name is "pull_request_review".
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#pullrequestreviewevent
type PullRequestReviewEvent struct {
// Action is always "submitted".
Action *string `json:"action,omitempty"`
Review *PullRequestReview `json:"review,omitempty"`
PullRequest *PullRequest `json:"pull_request,omitempty"`
// The following fields are only populated by Webhook events.
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
// The following field is only present when the webhook is triggered on
// a repository belonging to an organization.
Organization *Organization `json:"organization,omitempty"`
}
// PullRequestReviewCommentEvent is triggered when a comment is created on a
// portion of the unified diff of a pull request.
// The Webhook event name is "pull_request_review_comment".
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#pullrequestreviewcommentevent
type PullRequestReviewCommentEvent struct {
// Action is the action that was performed on the comment.
// Possible values are: "created", "edited", "deleted".
Action *string `json:"action,omitempty"`
PullRequest *PullRequest `json:"pull_request,omitempty"`
Comment *PullRequestComment `json:"comment,omitempty"`
// The following fields are only populated by Webhook events.
Changes *EditChange `json:"changes,omitempty"`
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// PushEvent represents a git push to a GitHub repository.
//
// GitHub API docs: http://developer.github.com/v3/activity/events/types/#pushevent
type PushEvent struct {
PushID *int `json:"push_id,omitempty"`
Head *string `json:"head,omitempty"`
Ref *string `json:"ref,omitempty"`
Size *int `json:"size,omitempty"`
Commits []PushEventCommit `json:"commits,omitempty"`
Repo *PushEventRepository `json:"repository,omitempty"`
Before *string `json:"before,omitempty"`
DistinctSize *int `json:"distinct_size,omitempty"`
// The following fields are only populated by Webhook events.
After *string `json:"after,omitempty"`
Created *bool `json:"created,omitempty"`
Deleted *bool `json:"deleted,omitempty"`
Forced *bool `json:"forced,omitempty"`
BaseRef *string `json:"base_ref,omitempty"`
Compare *string `json:"compare,omitempty"`
HeadCommit *PushEventCommit `json:"head_commit,omitempty"`
Pusher *User `json:"pusher,omitempty"`
Sender *User `json:"sender,omitempty"`
}
func (p PushEvent) String() string {
return Stringify(p)
}
// PushEventCommit represents a git commit in a GitHub PushEvent.
type PushEventCommit struct {
Message *string `json:"message,omitempty"`
Author *CommitAuthor `json:"author,omitempty"`
URL *string `json:"url,omitempty"`
Distinct *bool `json:"distinct,omitempty"`
// The following fields are only populated by Events API.
SHA *string `json:"sha,omitempty"`
// The following fields are only populated by Webhook events.
ID *string `json:"id,omitempty"`
TreeID *string `json:"tree_id,omitempty"`
Timestamp *Timestamp `json:"timestamp,omitempty"`
Committer *CommitAuthor `json:"committer,omitempty"`
Added []string `json:"added,omitempty"`
Removed []string `json:"removed,omitempty"`
Modified []string `json:"modified,omitempty"`
}
func (p PushEventCommit) String() string {
return Stringify(p)
}
// PushEventRepository represents the repo object in a PushEvent payload.
type PushEventRepository struct {
ID *int `json:"id,omitempty"`
Name *string `json:"name,omitempty"`
FullName *string `json:"full_name,omitempty"`
Owner *PushEventRepoOwner `json:"owner,omitempty"`
Private *bool `json:"private,omitempty"`
Description *string `json:"description,omitempty"`
Fork *bool `json:"fork,omitempty"`
CreatedAt *Timestamp `json:"created_at,omitempty"`
PushedAt *Timestamp `json:"pushed_at,omitempty"`
UpdatedAt *Timestamp `json:"updated_at,omitempty"`
Homepage *string `json:"homepage,omitempty"`
Size *int `json:"size,omitempty"`
StargazersCount *int `json:"stargazers_count,omitempty"`
WatchersCount *int `json:"watchers_count,omitempty"`
Language *string `json:"language,omitempty"`
HasIssues *bool `json:"has_issues,omitempty"`
HasDownloads *bool `json:"has_downloads,omitempty"`
HasWiki *bool `json:"has_wiki,omitempty"`
HasPages *bool `json:"has_pages,omitempty"`
ForksCount *int `json:"forks_count,omitempty"`
OpenIssuesCount *int `json:"open_issues_count,omitempty"`
DefaultBranch *string `json:"default_branch,omitempty"`
MasterBranch *string `json:"master_branch,omitempty"`
Organization *string `json:"organization,omitempty"`
// The following fields are only populated by Webhook events.
URL *string `json:"url,omitempty"`
HTMLURL *string `json:"html_url,omitempty"`
}
// PushEventRepoOwner is a basic representation of user/org in a PushEvent payload.
type PushEventRepoOwner struct {
Name *string `json:"name,omitempty"`
Email *string `json:"email,omitempty"`
}
// ReleaseEvent is triggered when a release is published.
// The Webhook event name is "release".
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#releaseevent
type ReleaseEvent struct {
// Action is the action that was performed. Possible value is: "published".
Action *string `json:"action,omitempty"`
Release *RepositoryRelease `json:"release,omitempty"`
// The following fields are only populated by Webhook events.
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// RepositoryEvent is triggered when a repository is created.
// The Webhook event name is "repository".
//
// Events of this type are not visible in timelines, they are only used to
// trigger organization webhooks.
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#repositoryevent
type RepositoryEvent struct {
// Action is the action that was performed. Possible values are: "created", "deleted",
// "publicized", "privatized".
Action *string `json:"action,omitempty"`
Repo *Repository `json:"repository,omitempty"`
// The following fields are only populated by Webhook events.
Org *Organization `json:"organization,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// StatusEvent is triggered when the status of a Git commit changes.
// The Webhook event name is "status".
//
// Events of this type are not visible in timelines, they are only used to
// trigger hooks.
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#statusevent
type StatusEvent struct {
SHA *string `json:"sha,omitempty"`
// State is the new state. Possible values are: "pending", "success", "failure", "error".
State *string `json:"state,omitempty"`
Description *string `json:"description,omitempty"`
TargetURL *string `json:"target_url,omitempty"`
Branches []*Branch `json:"branches,omitempty"`
// The following fields are only populated by Webhook events.
ID *int `json:"id,omitempty"`
Name *string `json:"name,omitempty"`
Context *string `json:"context,omitempty"`
Commit *RepositoryCommit `json:"commit,omitempty"`
CreatedAt *Timestamp `json:"created_at,omitempty"`
UpdatedAt *Timestamp `json:"updated_at,omitempty"`
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// TeamAddEvent is triggered when a repository is added to a team.
// The Webhook event name is "team_add".
//
// Events of this type are not visible in timelines. These events are only used
// to trigger hooks.
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#teamaddevent
type TeamAddEvent struct {
Team *Team `json:"team,omitempty"`
Repo *Repository `json:"repository,omitempty"`
// The following fields are only populated by Webhook events.
Org *Organization `json:"organization,omitempty"`
Sender *User `json:"sender,omitempty"`
}
// WatchEvent is related to starring a repository, not watching. See this API
// blog post for an explanation: https://developer.github.com/changes/2012-09-05-watcher-api/
//
// The event’s actor is the user who starred a repository, and the event’s
// repository is the repository that was starred.
//
// GitHub docs: https://developer.github.com/v3/activity/events/types/#watchevent
type WatchEvent struct {
// Action is the action that was performed. Possible value is: "started".
Action *string `json:"action,omitempty"`
// The following fields are only populated by Webhook events.
Repo *Repository `json:"repository,omitempty"`
Sender *User `json:"sender,omitempty"`
}
| pulcy/vault-monkey | deps/github.com/hashicorp/vault/vendor/github.com/google/go-github/github/event_types.go | GO | apache-2.0 | 24,483 |
'use strict';
//GetAttribute() returns "boolean" values and will return either "true" or null
describe('Report', function(){
var _ = require('lodash');
var Reports = require('../../app/reports/reports-page');
var Report = require('../../app/report/report-page');
var reports = new Reports();
var report, reportName, conceptName;
it('Should create a new empty report', function(){
reports.visitPage();
reportName = 'HelloWorld' + Math.floor((Math.random() * 10) + 1);
reports.createReport(reportName);
reports.getCurrentUrl()
.then(function(url){
var id = _.last(url.split('/'));
report = new Report(id);
expect(report.searchBox.isPresent()).toBe(true);
expect(report.label.getText()).toBe(reportName);
});
});
it('Should already contain an element', function(){
report.goToTaxonomy().concepts.goToConcept('h:ReportLineItems');
var concept = report.taxonomy.getConcept('h:ReportLineItems');
expect(concept.label.getAttribute('value')).toBe(reportName);
expect(report.taxonomy.elements.count()).toBe(1);
expect(report.taxonomy.rootElements.count()).toBe(1);
});
it('Shouldn\'t create a new concept with an invalid name', function(){
conceptName = 'hello World';
report.goToTaxonomy();
var concepts = report.taxonomy.concepts;
concepts.createConcept(conceptName);
expect(concepts.errorMessage.isDisplayed()).toBe(true);
expect(concepts.errorMessage.getText()).toBe('Invalid Concept Name');
});
it('Should create a new concept (1)', function(){
conceptName = 'h:helloWorldID';
report.goToTaxonomy();
var concepts = report.taxonomy.concepts;
concepts.createConcept(conceptName);
var concept = report.goToTaxonomy().concepts.goToConcept(conceptName);
expect(concept.label.getAttribute('value')).toBe('Hello World ID');
});
it('Taxonomy Section should be active', function(){
expect(report.getActiveSection()).toBe('Taxonomy');
report.goToFacts();
report.goToTaxonomy();
expect(report.getActiveSection()).toBe('Taxonomy');
});
it('Should create a new concept (2)', function(){
conceptName = 'h:assets';
var concepts = report.taxonomy.concepts;
report.goToTaxonomy();
concepts.createConcept(conceptName);
var concept = report.goToTaxonomy().concepts.goToConcept(conceptName);
expect(concept.label.getAttribute('value')).toBe('Assets');
});
it('Creates a new element', function(){
report.goToTaxonomy().concepts.goToConcept(conceptName);
report.taxonomy.getConcept(conceptName).createElement();
expect(report.taxonomy.elements.count()).toBe(2);
expect(report.taxonomy.rootElements.count()).toBe(1);
});
it('Renames the concept label', function(){
var overview = report.goToTaxonomy().concepts.goToConcept(conceptName).overview;
expect(overview.form.conceptLabel.getAttribute('value')).toBe('Assets');
overview.changeLabel('Assets Label');
expect(overview.form.conceptLabel.getAttribute('value')).toBe('Assets Label');
});
it('Creates a us-gaap:Assets synonym', function(){
var synonyms = report.taxonomy.getConcept(conceptName).goToSynonyms();
expect(synonyms.list.count()).toBe(0);
synonyms.addSynonym('us-gaap:Assets');
synonyms.addSynonym('us-gaap:AssetsCurrent');
synonyms.addSynonym('us-gaap:AssetsCurrent');
expect(synonyms.list.count()).toBe(2);
expect(synonyms.getName(synonyms.list.first())).toBe('us-gaap:Assets');
expect(synonyms.getName(synonyms.list.last())).toBe('us-gaap:AssetsCurrent');
});
it('Should display the fact table', function() {
report.goToFacts();
expect(report.facts.lineCount()).toBeGreaterThan(0);
});
it('Should display the preview', function() {
report.goToSpreadsheet();
expect(report.spreadsheet.getCellValueByCss('.constraints .header')).toBe('Component: (Network and Table)');
});
it('Should delete report', function() {
reports.visitPage();
reports.list.count().then(function(count){
reports.deleteReport(reportName).then(function(){
expect(reports.list.count()).toBe(count - 1);
});
});
});
});
| 28msec/nolap-report-editor | tests/e2e/basic-scenario.js | JavaScript | apache-2.0 | 4,515 |
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow_io/core/kernels/video_kernels.h"
extern "C" {
#if defined(__APPLE__)
void* VideoCaptureInitFunction(const char* device, int64_t* bytes,
int64_t* width, int64_t* height);
void VideoCaptureNextFunction(void* context, void* data, int64_t size);
void VideoCaptureFiniFunction(void* context);
#elif defined(_MSC_VER)
void* VideoCaptureInitFunction(const char* device, int64_t* bytes,
int64_t* width, int64_t* height) {
return NULL;
}
void VideoCaptureNextFunction(void* context, void* data, int64_t size) {}
void VideoCaptureFiniFunction(void* context) {}
#else
void* VideoCaptureInitFunction(const char* device, int64_t* bytes,
int64_t* width, int64_t* height) {
tensorflow::data::VideoCaptureContext* p =
new tensorflow::data::VideoCaptureContext();
if (p != nullptr) {
tensorflow::Status status = p->Init(device, bytes, width, height);
if (status.ok()) {
return p;
}
LOG(ERROR) << "unable to initialize video capture: " << status;
delete p;
}
return NULL;
}
void VideoCaptureNextFunction(void* context, void* data, int64_t size) {
tensorflow::data::VideoCaptureContext* p =
static_cast<tensorflow::data::VideoCaptureContext*>(context);
if (p != nullptr) {
tensorflow::Status status = p->Read(data, size);
if (!status.ok()) {
LOG(ERROR) << "unable to read video capture: " << status;
}
}
}
void VideoCaptureFiniFunction(void* context) {
tensorflow::data::VideoCaptureContext* p =
static_cast<tensorflow::data::VideoCaptureContext*>(context);
if (p != nullptr) {
delete p;
}
}
#endif
}
namespace tensorflow {
namespace data {
namespace {
class VideoCaptureReadableResource : public ResourceBase {
public:
VideoCaptureReadableResource(Env* env)
: env_(env), context_(nullptr, [](void* p) {
if (p != nullptr) {
VideoCaptureFiniFunction(p);
}
}) {}
~VideoCaptureReadableResource() {}
Status Init(const string& input) {
mutex_lock l(mu_);
int64_t bytes, width, height;
context_.reset(
VideoCaptureInitFunction(input.c_str(), &bytes, &width, &height));
if (context_.get() == nullptr) {
return errors::InvalidArgument("unable to open device ", input);
}
bytes_ = static_cast<int64>(bytes);
width_ = static_cast<int64>(width);
height_ = static_cast<int64>(height);
return Status::OK();
}
Status Read(
std::function<Status(const TensorShape& shape, Tensor** value_tensor)>
allocate_func) {
mutex_lock l(mu_);
Tensor* value_tensor;
TF_RETURN_IF_ERROR(allocate_func(TensorShape({1}), &value_tensor));
string buffer;
buffer.resize(bytes_);
VideoCaptureNextFunction(context_.get(), (void*)&buffer[0],
static_cast<int64_t>(bytes_));
value_tensor->flat<tstring>()(0) = buffer;
return Status::OK();
}
string DebugString() const override {
mutex_lock l(mu_);
return "VideoCaptureReadableResource";
}
protected:
mutable mutex mu_;
Env* env_ TF_GUARDED_BY(mu_);
std::unique_ptr<void, void (*)(void*)> context_;
int64 bytes_;
int64 width_;
int64 height_;
};
class VideoCaptureReadableInitOp
: public ResourceOpKernel<VideoCaptureReadableResource> {
public:
explicit VideoCaptureReadableInitOp(OpKernelConstruction* context)
: ResourceOpKernel<VideoCaptureReadableResource>(context) {
env_ = context->env();
}
private:
void Compute(OpKernelContext* context) override {
ResourceOpKernel<VideoCaptureReadableResource>::Compute(context);
const Tensor* input_tensor;
OP_REQUIRES_OK(context, context->input("input", &input_tensor));
const string& input = input_tensor->scalar<tstring>()();
OP_REQUIRES_OK(context, resource_->Init(input));
}
Status CreateResource(VideoCaptureReadableResource** resource)
TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) override {
*resource = new VideoCaptureReadableResource(env_);
return Status::OK();
}
private:
mutable mutex mu_;
Env* env_ TF_GUARDED_BY(mu_);
};
class VideoCaptureReadableReadOp : public OpKernel {
public:
explicit VideoCaptureReadableReadOp(OpKernelConstruction* context)
: OpKernel(context) {
env_ = context->env();
}
void Compute(OpKernelContext* context) override {
VideoCaptureReadableResource* resource;
OP_REQUIRES_OK(context,
GetResourceFromContext(context, "input", &resource));
core::ScopedUnref unref(resource);
OP_REQUIRES_OK(
context, resource->Read([&](const TensorShape& shape,
Tensor** value_tensor) -> Status {
TF_RETURN_IF_ERROR(context->allocate_output(0, shape, value_tensor));
return Status::OK();
}));
}
private:
mutable mutex mu_;
Env* env_ TF_GUARDED_BY(mu_);
};
REGISTER_KERNEL_BUILDER(Name("IO>VideoCaptureReadableInit").Device(DEVICE_CPU),
VideoCaptureReadableInitOp);
REGISTER_KERNEL_BUILDER(Name("IO>VideoCaptureReadableRead").Device(DEVICE_CPU),
VideoCaptureReadableReadOp);
} // namespace
} // namespace data
} // namespace tensorflow
| tensorflow/io | tensorflow_io/core/kernels/video_kernels.cc | C++ | apache-2.0 | 5,927 |
/*
* Copyright 2017-present Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.provider.lisp.mapping.util;
import org.onlab.packet.IpAddress;
import org.onlab.packet.IpPrefix;
import org.onlab.packet.MacAddress;
import org.onosproject.lisp.ctl.ExtensionMappingAddressInterpreter;
import org.onosproject.lisp.msg.types.LispAfiAddress;
import org.onosproject.lisp.msg.types.LispAsAddress;
import org.onosproject.lisp.msg.types.LispDistinguishedNameAddress;
import org.onosproject.lisp.msg.types.LispIpv4Address;
import org.onosproject.lisp.msg.types.LispIpv6Address;
import org.onosproject.lisp.msg.types.LispMacAddress;
import org.onosproject.lisp.msg.types.lcaf.LispLcafAddress;
import org.onosproject.mapping.addresses.ExtensionMappingAddress;
import org.onosproject.mapping.addresses.MappingAddress;
import org.onosproject.mapping.addresses.MappingAddresses;
import org.onosproject.net.Device;
import org.onosproject.net.DeviceId;
import org.onosproject.net.device.DeviceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.onosproject.mapping.addresses.ExtensionMappingAddressType.ExtensionMappingAddressTypes.*;
/**
* Mapping address builder class.
*/
public final class MappingAddressBuilder {
private static final Logger log =
LoggerFactory.getLogger(MappingAddressBuilder.class);
private static final int IPV4_PREFIX_LENGTH = 32;
private static final int IPV6_PREFIX_LENGTH = 128;
// prevent from instantiation
private MappingAddressBuilder() {
}
/**
* Converts LispAfiAddress into abstracted mapping address.
*
* @param deviceService device service
* @param deviceId device identifier
* @param address LispAfiAddress
* @return abstracted mapping address
*/
protected static MappingAddress getAddress(DeviceService deviceService,
DeviceId deviceId,
LispAfiAddress address) {
if (address == null) {
log.warn("Address is not specified.");
return null;
}
switch (address.getAfi()) {
case IP4:
return afi2mapping(address);
case IP6:
return afi2mapping(address);
case AS:
int asNum = ((LispAsAddress) address).getASNum();
return MappingAddresses.asMappingAddress(String.valueOf(asNum));
case DISTINGUISHED_NAME:
String dn = ((LispDistinguishedNameAddress)
address).getDistinguishedName();
return MappingAddresses.dnMappingAddress(dn);
case MAC:
MacAddress macAddress = ((LispMacAddress) address).getAddress();
return MappingAddresses.ethMappingAddress(macAddress);
case LCAF:
return deviceService == null ? null :
lcaf2extension(deviceService, deviceId, (LispLcafAddress) address);
default:
log.warn("Unsupported address type {}", address.getAfi());
break;
}
return null;
}
/**
* Converts AFI address to generalized mapping address.
*
* @param afiAddress IP typed AFI address
* @return generalized mapping address
*/
private static MappingAddress afi2mapping(LispAfiAddress afiAddress) {
switch (afiAddress.getAfi()) {
case IP4:
IpAddress ipv4Address = ((LispIpv4Address) afiAddress).getAddress();
IpPrefix ipv4Prefix = IpPrefix.valueOf(ipv4Address, IPV4_PREFIX_LENGTH);
return MappingAddresses.ipv4MappingAddress(ipv4Prefix);
case IP6:
IpAddress ipv6Address = ((LispIpv6Address) afiAddress).getAddress();
IpPrefix ipv6Prefix = IpPrefix.valueOf(ipv6Address, IPV6_PREFIX_LENGTH);
return MappingAddresses.ipv6MappingAddress(ipv6Prefix);
default:
log.warn("Only support to convert IP address type");
break;
}
return null;
}
/**
* Converts LCAF address to extension mapping address.
*
* @param deviceService device service
* @param deviceId device identifier
* @param lcaf LCAF address
* @return extension mapping address
*/
private static MappingAddress lcaf2extension(DeviceService deviceService,
DeviceId deviceId,
LispLcafAddress lcaf) {
Device device = deviceService.getDevice(deviceId);
ExtensionMappingAddressInterpreter addressInterpreter;
ExtensionMappingAddress mappingAddress = null;
if (device.is(ExtensionMappingAddressInterpreter.class)) {
addressInterpreter = device.as(ExtensionMappingAddressInterpreter.class);
} else {
addressInterpreter = null;
}
switch (lcaf.getType()) {
case LIST:
if (addressInterpreter != null &&
addressInterpreter.supported(LIST_ADDRESS.type())) {
mappingAddress = addressInterpreter.mapLcafAddress(lcaf);
}
break;
case SEGMENT:
if (addressInterpreter != null &&
addressInterpreter.supported(SEGMENT_ADDRESS.type())) {
mappingAddress = addressInterpreter.mapLcafAddress(lcaf);
}
break;
case AS:
if (addressInterpreter != null &&
addressInterpreter.supported(AS_ADDRESS.type())) {
mappingAddress = addressInterpreter.mapLcafAddress(lcaf);
}
break;
case APPLICATION_DATA:
if (addressInterpreter != null &&
addressInterpreter.supported(APPLICATION_DATA_ADDRESS.type())) {
mappingAddress = addressInterpreter.mapLcafAddress(lcaf);
}
break;
case GEO_COORDINATE:
if (addressInterpreter != null &&
addressInterpreter.supported(GEO_COORDINATE_ADDRESS.type())) {
mappingAddress = addressInterpreter.mapLcafAddress(lcaf);
}
break;
case NAT:
if (addressInterpreter != null &&
addressInterpreter.supported(NAT_ADDRESS.type())) {
mappingAddress = addressInterpreter.mapLcafAddress(lcaf);
}
break;
case NONCE:
if (addressInterpreter != null &&
addressInterpreter.supported(NONCE_ADDRESS.type())) {
mappingAddress = addressInterpreter.mapLcafAddress(lcaf);
}
break;
case MULTICAST:
if (addressInterpreter != null &&
addressInterpreter.supported(MULTICAST_ADDRESS.type())) {
mappingAddress = addressInterpreter.mapLcafAddress(lcaf);
}
break;
case TRAFFIC_ENGINEERING:
if (addressInterpreter != null &&
addressInterpreter.supported(TRAFFIC_ENGINEERING_ADDRESS.type())) {
mappingAddress = addressInterpreter.mapLcafAddress(lcaf);
}
break;
case SOURCE_DEST:
if (addressInterpreter != null &&
addressInterpreter.supported(SOURCE_DEST_ADDRESS.type())) {
mappingAddress = addressInterpreter.mapLcafAddress(lcaf);
}
break;
default:
log.warn("Unsupported extension mapping address type {}", lcaf.getType());
break;
}
return mappingAddress != null ?
MappingAddresses.extensionMappingAddressWrapper(mappingAddress, deviceId) : null;
}
}
| LorenzReinhart/ONOSnew | providers/lisp/mapping/src/main/java/org/onosproject/provider/lisp/mapping/util/MappingAddressBuilder.java | Java | apache-2.0 | 8,703 |
/*
* 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.synapse.transport.nhttp.util;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axis2.AxisFault;
import org.apache.axis2.Constants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.builder.Builder;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.description.AxisBindingOperation;
import org.apache.axis2.description.AxisEndpoint;
import org.apache.axis2.description.AxisOperation;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.description.WSDL20DefaultValueHolder;
import org.apache.axis2.description.WSDL2Constants;
import org.apache.axis2.dispatchers.HTTPLocationBasedDispatcher;
import org.apache.axis2.dispatchers.RequestURIBasedDispatcher;
import org.apache.axis2.dispatchers.RequestURIOperationDispatcher;
import org.apache.axis2.engine.AxisEngine;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.axis2.transport.http.util.URIEncoderDecoder;
import org.apache.http.Header;
import org.apache.synapse.transport.nhttp.NHttpConfiguration;
import org.apache.synapse.transport.nhttp.NhttpConstants;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
/**
* This class provides a set of utility methods to manage the REST invocation calls
* going out from the nhttp transport in the HTTP GET method
*/
public class RESTUtil {
/**
* This method will return the URI part for the GET HTTPRequest by converting
* the SOAP infoset to the URL-encoded GET format
*
* @param messageContext - from which the SOAP infoset will be extracted to encode
* @param address - address of the actual service
* @return uri - ERI of the GET request
* @throws AxisFault - if the SOAP infoset cannot be converted in to the GET URL-encoded format
*/
public static String getURI(MessageContext messageContext, String address) throws AxisFault {
OMElement firstElement;
address = address.substring(address.indexOf("//") + 2);
address = address.substring(address.indexOf("/"));
String queryParameterSeparator = (String) messageContext
.getProperty(WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR);
// In case queryParameterSeparator is null we better use the default value
if (queryParameterSeparator == null) {
queryParameterSeparator = WSDL20DefaultValueHolder
.getDefaultValue(WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR);
}
firstElement = messageContext.getEnvelope().getBody().getFirstElement();
String params = "";
if (firstElement != null) {
// first element corresponds to the operation name
address = address + "/" + firstElement.getLocalName();
} else {
firstElement = messageContext.getEnvelope().getBody();
}
Iterator iter = firstElement.getChildElements();
String legalCharacters = WSDL2Constants
.LEGAL_CHARACTERS_IN_QUERY.replaceAll(queryParameterSeparator, "");
StringBuffer buff = new StringBuffer(params);
// iterate through the child elements and find the request parameters
while (iter.hasNext()) {
OMElement element = (OMElement) iter.next();
try {
buff.append(URIEncoderDecoder.quoteIllegal(element.getLocalName(),
legalCharacters)).append("=").append(URIEncoderDecoder.quoteIllegal(element.getText(),
legalCharacters)).append(queryParameterSeparator);
} catch (UnsupportedEncodingException e) {
throw new AxisFault("URI Encoding error : " + element.getLocalName()
+ "=" + element.getText(), e);
}
}
params = buff.toString();
if (params.trim().length() != 0) {
int index = address.indexOf("?");
if (index == -1) {
address = address + "?" + params.substring(0, params.length() - 1);
} else if (index == address.length() - 1) {
address = address + params.substring(0, params.length() - 1);
} else {
address = address
+ queryParameterSeparator + params.substring(0, params.length() - 1);
}
}
return address;
}
/**
* Processes the HTTP GET / DELETE request and builds the SOAP info-set of the REST message
*
* @param msgContext The MessageContext of the Request Message
* @param out The output stream of the response
* @param requestURI The URL that the request came to
* @param contentTypeHeader The contentType header of the request
* @param httpMethod The http method of the request
* @param dispatching Weather we should do service dispatching
* @throws AxisFault - Thrown in case a fault occurs
*/
public static void processGetAndDeleteRequest(MessageContext msgContext, OutputStream out,
String requestURI, Header contentTypeHeader,
String httpMethod, boolean dispatching)
throws AxisFault {
String contentType = contentTypeHeader != null ? contentTypeHeader.getValue() : null;
prepareMessageContext(msgContext, requestURI, httpMethod, out, contentType, dispatching);
msgContext.setProperty(NhttpConstants.NO_ENTITY_BODY, Boolean.TRUE);
org.apache.axis2.transport.http.util.RESTUtil.processURLRequest(msgContext, out,
contentType);
}
/**
* Processes the HTTP GET / DELETE request and builds the SOAP info-set of the REST message
*
* @param msgContext The MessageContext of the Request Message
* @param out The output stream of the response
* @param requestURI The URL that the request came to
* @param contentTypeHeader The contentType header of the request
* @param builder The message builder to use
* @param httpMethod The http method of the request
* @param dispatching Weather we should do service dispatching
* @throws AxisFault - Thrown in case a fault occurs
*/
public static void processGetAndDeleteRequest(MessageContext msgContext, OutputStream out,
String requestURI, Header contentTypeHeader,
Builder builder, String httpMethod,
boolean dispatching)
throws AxisFault {
String contentType = contentTypeHeader != null ? contentTypeHeader.getValue() : null;
prepareMessageContext(msgContext, requestURI, httpMethod, out, contentType, dispatching);
msgContext.setProperty(NhttpConstants.NO_ENTITY_BODY, Boolean.TRUE);
org.apache.axis2.transport.http.util.RESTUtil.processURLRequest(msgContext, out,
contentType, builder);
}
/**
* Processes the HTTP GET request and builds the SOAP info-set of the REST message
*
* @param msgContext The MessageContext of the Request Message
* @param out The output stream of the response
* @param soapAction SoapAction of the request
* @param requestURI The URL that the request came to
* @throws AxisFault - Thrown in case a fault occurs
*/
public static void processURLRequest(MessageContext msgContext, OutputStream out,
String soapAction, String requestURI) throws AxisFault {
if ((soapAction != null) && soapAction.startsWith("\"") && soapAction.endsWith("\"")) {
soapAction = soapAction.substring(1, soapAction.length() - 1);
}
msgContext.setSoapAction(soapAction);
msgContext.setTo(new EndpointReference(requestURI));
msgContext.setProperty(MessageContext.TRANSPORT_OUT, out);
msgContext.setServerSide(true);
msgContext.setDoingREST(true);
msgContext.setEnvelope(OMAbstractFactory.getSOAP11Factory().getDefaultEnvelope());
msgContext.setProperty(NhttpConstants.NO_ENTITY_BODY, Boolean.TRUE);
AxisEngine.receive(msgContext);
}
/**
* Processes the HTTP POST request and builds the SOAP info-set of the REST message
*
* @param msgContext The MessageContext of the Request Message
* @param is The input stream of the request
* @param os The output stream of the response
* @param requestURI The URL that the request came to
* @param contentTypeHeader The contentType header of the request
* @param dispatching Weather we should do dispatching
* @throws AxisFault - Thrown in case a fault occurs
*/
public static void processPOSTRequest(MessageContext msgContext, InputStream is,
OutputStream os, String requestURI,
Header contentTypeHeader,
boolean dispatching) throws AxisFault {
String contentType = contentTypeHeader != null ? contentTypeHeader.getValue() : null;
prepareMessageContext(msgContext, requestURI, HTTPConstants.HTTP_METHOD_POST,
os, contentType, dispatching);
org.apache.axis2.transport.http.util.RESTUtil.processXMLRequest(msgContext, is, os,
contentType);
}
/**
* Processes the HTTP POST request and builds the SOAP info-set of the REST message
*
* @param msgContext The MessageContext of the Request Message
* @param is The input stream of the request
* @param os The output stream of the response
* @param requestURI The URL that the request came to
* @param contentTypeHeader The contentType header of the request
* @param builder The message builder to use
* @param dispatching Weather we should do dispatching
* @throws AxisFault - Thrown in case a fault occurs
*/
public static void processPOSTRequest(MessageContext msgContext, InputStream is,
OutputStream os, String requestURI,
Header contentTypeHeader, Builder builder,
boolean dispatching) throws AxisFault {
String contentType = contentTypeHeader != null ? contentTypeHeader.getValue() : null;
prepareMessageContext(msgContext, requestURI, HTTPConstants.HTTP_METHOD_POST,
os, contentType, dispatching);
org.apache.axis2.transport.http.util.RESTUtil.processXMLRequest(msgContext, is, os,
contentType, builder);
}
/**
* prepare message context prior to call axis2 RestUtils
*
* @param msgContext The MessageContext of the Request Message
* @param requestURI The URL that the request came to
* @param httpMethod The http method of the request
* @param out The output stream of the response
* @param contentType The content type of the request
* @param dispatching weather we should do dispatching
* @throws AxisFault Thrown in case a fault occurs
*/
private static void prepareMessageContext(MessageContext msgContext,
String requestURI,
String httpMethod,
OutputStream out,
String contentType,
boolean dispatching) throws AxisFault {
msgContext.setTo(new EndpointReference(requestURI));
msgContext.setProperty(HTTPConstants.HTTP_METHOD, httpMethod);
msgContext.setServerSide(true);
msgContext.setDoingREST(true);
msgContext.setProperty(MessageContext.TRANSPORT_OUT, out);
msgContext.setProperty(NhttpConstants.REST_REQUEST_CONTENT_TYPE, contentType);
// workaround to get REST working in the case of
// 1) Based on the request URI , it is possible to find a service name and operation.
// However, there is no actual service deployed in the synapse ( no i.e proxy or other)
// e.g http://localhost:8280/services/StudentService/students where there is no proxy
// service with name StudentService.This is a senario where StudentService is in an external
// server and it is needed to call it from synapse using the main sequence
// 2) request is to be injected into the main sequence .i.e. http://localhost:8280
// This method does not cause any performance issue ...
// Proper fix should be refractoring axis2 RestUtil in a proper way
if (dispatching) {
RequestURIBasedDispatcher requestDispatcher = new RequestURIBasedDispatcher();
AxisService axisService = requestDispatcher.findService(msgContext);
if (axisService == null) {
String defaultSvcName = NHttpConfiguration.getInstance().getStringProperty(
"nhttp.default.service", "__SynapseService");
axisService = msgContext.getConfigurationContext()
.getAxisConfiguration().getService(defaultSvcName);
}
msgContext.setAxisService(axisService);
}
}
public static void dispatchAndVerify(MessageContext msgContext) throws AxisFault {
RequestURIBasedDispatcher requestDispatcher = new RequestURIBasedDispatcher();
requestDispatcher.invoke(msgContext);
AxisService axisService = msgContext.getAxisService();
if (axisService != null) {
HTTPLocationBasedDispatcher httpLocationBasedDispatcher =
new HTTPLocationBasedDispatcher();
httpLocationBasedDispatcher.invoke(msgContext);
if (msgContext.getAxisOperation() == null) {
RequestURIOperationDispatcher requestURIOperationDispatcher =
new RequestURIOperationDispatcher();
requestURIOperationDispatcher.invoke(msgContext);
}
AxisOperation axisOperation;
if ((axisOperation = msgContext.getAxisOperation()) != null) {
AxisEndpoint axisEndpoint =
(AxisEndpoint) msgContext.getProperty(WSDL2Constants.ENDPOINT_LOCAL_NAME);
if (axisEndpoint != null) {
AxisBindingOperation axisBindingOperation = (AxisBindingOperation) axisEndpoint
.getBinding().getChild(axisOperation.getName());
msgContext.setProperty(Constants.AXIS_BINDING_OPERATION, axisBindingOperation);
}
msgContext.setAxisOperation(axisOperation);
}
}
}
}
| asanka88/apache-synapse | modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/nhttp/util/RESTUtil.java | Java | apache-2.0 | 16,005 |
// Copyright 2018 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
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.firebase.firestore.model.mutation;
import static com.google.firebase.firestore.model.Values.isDouble;
import static com.google.firebase.firestore.model.Values.isInteger;
import static com.google.firebase.firestore.util.Assert.fail;
import static com.google.firebase.firestore.util.Assert.hardAssert;
import androidx.annotation.Nullable;
import com.google.firebase.Timestamp;
import com.google.firebase.firestore.model.Values;
import com.google.firestore.v1.Value;
/**
* Implements the backend semantics for locally computed NUMERIC_ADD (increment) transforms.
* Converts all field values to longs or doubles and resolves overflows to
* Long.MAX_VALUE/Long.MIN_VALUE.
*/
public class NumericIncrementTransformOperation implements TransformOperation {
private Value operand;
public NumericIncrementTransformOperation(Value operand) {
hardAssert(
Values.isNumber(operand),
"NumericIncrementTransformOperation expects a NumberValue operand");
this.operand = operand;
}
@Override
public Value applyToLocalView(@Nullable Value previousValue, Timestamp localWriteTime) {
Value baseValue = computeBaseValue(previousValue);
// Return an integer value only if the previous value and the operand is an integer.
if (isInteger(baseValue) && isInteger(operand)) {
long sum = safeIncrement(baseValue.getIntegerValue(), operandAsLong());
return Value.newBuilder().setIntegerValue(sum).build();
} else if (isInteger(baseValue)) {
double sum = baseValue.getIntegerValue() + operandAsDouble();
return Value.newBuilder().setDoubleValue(sum).build();
} else {
hardAssert(
isDouble(baseValue),
"Expected NumberValue to be of type DoubleValue, but was ",
previousValue.getClass().getCanonicalName());
double sum = baseValue.getDoubleValue() + operandAsDouble();
return Value.newBuilder().setDoubleValue(sum).build();
}
}
@Override
public Value applyToRemoteDocument(@Nullable Value previousValue, Value transformResult) {
return transformResult;
}
public Value getOperand() {
return operand;
}
/**
* Inspects the provided value, returning the provided value if it is already a NumberValue,
* otherwise returning a coerced IntegerValue of 0.
*/
@Override
public Value computeBaseValue(@Nullable Value previousValue) {
return Values.isNumber(previousValue)
? previousValue
: Value.newBuilder().setIntegerValue(0).build();
}
/**
* Implementation of Java 8's `addExact()` that resolves positive and negative numeric overflows
* to Long.MAX_VALUE or Long.MIN_VALUE respectively (instead of throwing an ArithmeticException).
*/
private long safeIncrement(long x, long y) {
long r = x + y;
// See "Hacker's Delight" 2-12: Overflow if both arguments have the opposite sign of the result
if (((x ^ r) & (y ^ r)) >= 0) {
return r;
}
if (r >= 0L) {
return Long.MIN_VALUE;
} else {
return Long.MAX_VALUE;
}
}
private double operandAsDouble() {
if (isDouble(operand)) {
return operand.getDoubleValue();
} else if (isInteger(operand)) {
return operand.getIntegerValue();
} else {
throw fail(
"Expected 'operand' to be of Number type, but was "
+ operand.getClass().getCanonicalName());
}
}
private long operandAsLong() {
if (isDouble(operand)) {
return (long) operand.getDoubleValue();
} else if (isInteger(operand)) {
return operand.getIntegerValue();
} else {
throw fail(
"Expected 'operand' to be of Number type, but was "
+ operand.getClass().getCanonicalName());
}
}
}
| firebase/firebase-android-sdk | firebase-firestore/src/main/java/com/google/firebase/firestore/model/mutation/NumericIncrementTransformOperation.java | Java | apache-2.0 | 4,335 |
/*
* Copyright (C) 2013,2014 Brett Wooldridge
*
* 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.zaxxer.hikari.pool;
import static com.zaxxer.hikari.pool.HikariMBeanElf.registerMBeans;
import static com.zaxxer.hikari.pool.HikariMBeanElf.unregisterMBeans;
import static com.zaxxer.hikari.util.IConcurrentBagEntry.STATE_IN_USE;
import static com.zaxxer.hikari.util.IConcurrentBagEntry.STATE_NOT_IN_USE;
import static com.zaxxer.hikari.util.IConcurrentBagEntry.STATE_REMOVED;
import static com.zaxxer.hikari.util.UtilityElf.createInstance;
import static com.zaxxer.hikari.util.UtilityElf.createThreadPoolExecutor;
import static com.zaxxer.hikari.util.UtilityElf.elapsedTimeMs;
import static com.zaxxer.hikari.util.UtilityElf.getTransactionIsolation;
import static com.zaxxer.hikari.util.UtilityElf.setRemoveOnCancelPolicy;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.codahale.metrics.MetricRegistry;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.IConnectionCustomizer;
import com.zaxxer.hikari.metrics.CodaHaleMetricsTracker;
import com.zaxxer.hikari.metrics.MetricsTracker;
import com.zaxxer.hikari.metrics.MetricsTracker.MetricsContext;
import com.zaxxer.hikari.proxy.IHikariConnectionProxy;
import com.zaxxer.hikari.proxy.ProxyFactory;
import com.zaxxer.hikari.util.ConcurrentBag;
import com.zaxxer.hikari.util.IBagStateListener;
import com.zaxxer.hikari.util.DefaultThreadFactory;
import com.zaxxer.hikari.util.GlobalPoolLock;
import com.zaxxer.hikari.util.LeakTask;
import com.zaxxer.hikari.util.PoolUtilities;
/**
* This is the primary connection pool class that provides the basic
* pooling behavior for HikariCP.
*
* @author Brett Wooldridge
*/
public abstract class BaseHikariPool implements HikariPoolMBean, IBagStateListener
{
protected static final Logger LOGGER = LoggerFactory.getLogger("HikariPool");
private static final long ALIVE_BYPASS_WINDOW = Long.getLong("com.zaxxer.hikari.aliveBypassWindow", 1000L);
public final String catalog;
public final boolean isReadOnly;
public final boolean isAutoCommit;
public int transactionIsolation;
protected final PoolUtilities poolUtils;
protected final HikariConfig configuration;
protected final AtomicInteger totalConnections;
protected final ConcurrentBag<PoolBagEntry> connectionBag;
protected final ThreadPoolExecutor addConnectionExecutor;
protected final ThreadPoolExecutor closeConnectionExecutor;
protected final ScheduledThreadPoolExecutor houseKeepingExecutorService;
protected final boolean isUseJdbc4Validation;
protected final boolean isIsolateInternalQueries;
protected volatile boolean isShutdown;
protected volatile long connectionTimeout;
protected volatile boolean isPoolSuspended;
private final LeakTask leakTask;
private final DataSource dataSource;
private final MetricsTracker metricsTracker;
private final GlobalPoolLock suspendResumeLock;
private final IConnectionCustomizer connectionCustomizer;
private final AtomicReference<Throwable> lastConnectionFailure;
private final String username;
private final String password;
private final boolean isRecordMetrics;
/**
* Construct a HikariPool with the specified configuration.
*
* @param configuration a HikariConfig instance
*/
public BaseHikariPool(HikariConfig configuration)
{
this(configuration, configuration.getUsername(), configuration.getPassword());
}
/**
* Construct a HikariPool with the specified configuration. We cache lots of configuration
* items in class-local final members for speed.
*
* @param configuration a HikariConfig instance
* @param username authentication username
* @param password authentication password
*/
public BaseHikariPool(HikariConfig configuration, String username, String password)
{
this.username = username;
this.password = password;
this.configuration = configuration;
this.poolUtils = new PoolUtilities();
this.connectionBag = createConcurrentBag(this);
this.totalConnections = new AtomicInteger();
this.connectionTimeout = configuration.getConnectionTimeout();
this.lastConnectionFailure = new AtomicReference<Throwable>();
this.isReadOnly = configuration.isReadOnly();
this.isAutoCommit = configuration.isAutoCommit();
this.suspendResumeLock = configuration.isAllowPoolSuspension() ? GlobalPoolLock.SUSPEND_RESUME_LOCK : GlobalPoolLock.FAUX_LOCK;
this.catalog = configuration.getCatalog();
this.connectionCustomizer = initializeCustomizer();
this.transactionIsolation = getTransactionIsolation(configuration.getTransactionIsolation());
this.isIsolateInternalQueries = configuration.isIsolateInternalQueries();
this.isUseJdbc4Validation = configuration.getConnectionTestQuery() == null;
this.isRecordMetrics = configuration.getMetricRegistry() != null;
this.metricsTracker = (isRecordMetrics ? new CodaHaleMetricsTracker(this, (MetricRegistry) configuration.getMetricRegistry()) : new MetricsTracker(this));
this.dataSource = poolUtils.initializeDataSource(configuration.getDataSourceClassName(), configuration.getDataSource(), configuration.getDataSourceProperties(), configuration.getJdbcUrl(), username, password);
this.addConnectionExecutor = createThreadPoolExecutor(configuration.getMaximumPoolSize(), "HikariCP connection filler (pool " + configuration.getPoolName() + ")", configuration.getThreadFactory(), new ThreadPoolExecutor.DiscardPolicy());
this.closeConnectionExecutor = createThreadPoolExecutor(4, "HikariCP connection closer (pool " + configuration.getPoolName() + ")", configuration.getThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());
long delayPeriod = Long.getLong("com.zaxxer.hikari.housekeeping.periodMs", TimeUnit.SECONDS.toMillis(30L));
ThreadFactory threadFactory = configuration.getThreadFactory() != null ? configuration.getThreadFactory() : new DefaultThreadFactory("Hikari Housekeeping Timer (pool " + configuration.getPoolName() + ")", true);
this.houseKeepingExecutorService = new ScheduledThreadPoolExecutor(1, threadFactory, new ThreadPoolExecutor.DiscardPolicy());
this.houseKeepingExecutorService.scheduleAtFixedRate(getHouseKeeper(), delayPeriod, delayPeriod, TimeUnit.MILLISECONDS);
this.leakTask = (configuration.getLeakDetectionThreshold() == 0) ? LeakTask.NO_LEAK : new LeakTask(configuration.getLeakDetectionThreshold(), houseKeepingExecutorService);
setRemoveOnCancelPolicy(houseKeepingExecutorService);
poolUtils.setLoginTimeout(dataSource, connectionTimeout, LOGGER);
registerMBeans(configuration, this);
fillPool();
}
/**
* Get a connection from the pool, or timeout trying.
*
* @return a java.sql.Connection instance
* @throws SQLException thrown if a timeout occurs trying to obtain a connection
*/
public final Connection getConnection() throws SQLException
{
suspendResumeLock.acquire();
long timeout = connectionTimeout;
final long start = System.currentTimeMillis();
final MetricsContext metricsContext = (isRecordMetrics ? metricsTracker.recordConnectionRequest(start) : MetricsTracker.NO_CONTEXT);
try {
do {
final PoolBagEntry bagEntry = connectionBag.borrow(timeout, TimeUnit.MILLISECONDS);
if (bagEntry == null) {
break; // We timed out... break and throw exception
}
final long now = System.currentTimeMillis();
if (now - bagEntry.lastAccess > ALIVE_BYPASS_WINDOW && !isConnectionAlive(bagEntry.connection, timeout)) {
closeConnection(bagEntry); // Throw away the dead connection and try again
timeout = connectionTimeout - elapsedTimeMs(start);
}
else {
metricsContext.setConnectionLastOpen(bagEntry, now);
return ProxyFactory.getProxyConnection((HikariPool) this, bagEntry, leakTask.start());
}
}
while (timeout > 0L);
}
catch (InterruptedException e) {
throw new SQLException("Interrupted during connection acquisition", e);
}
finally {
suspendResumeLock.release();
metricsContext.stop();
}
logPoolState("Timeout failure ");
throw new SQLException(String.format("Timeout after %dms of waiting for a connection.", elapsedTimeMs(start)), lastConnectionFailure.getAndSet(null));
}
/**
* Release a connection back to the pool, or permanently close it if it is broken.
*
* @param bagEntry the PoolBagEntry to release back to the pool
*/
public final void releaseConnection(final PoolBagEntry bagEntry)
{
metricsTracker.recordConnectionUsage(bagEntry);
if (bagEntry.evicted) {
LOGGER.debug("Connection returned to pool {} is broken or evicted. Closing connection.", configuration.getPoolName());
closeConnection(bagEntry);
}
else {
bagEntry.lastAccess = System.currentTimeMillis();
connectionBag.requite(bagEntry);
}
}
/**
* Shutdown the pool, closing all idle connections and aborting or closing
* active connections.
*
* @throws InterruptedException thrown if the thread is interrupted during shutdown
*/
public final void shutdown() throws InterruptedException
{
if (!isShutdown) {
isShutdown = true;
LOGGER.info("HikariCP pool {} is shutting down.", configuration.getPoolName());
logPoolState("Before shutdown ");
connectionBag.close();
softEvictConnections();
houseKeepingExecutorService.shutdownNow();
addConnectionExecutor.shutdown();
addConnectionExecutor.awaitTermination(5L, TimeUnit.SECONDS);
final long start = System.currentTimeMillis();
do {
softEvictConnections();
abortActiveConnections();
}
while ((getIdleConnections() > 0 || getActiveConnections() > 0) && elapsedTimeMs(start) < TimeUnit.SECONDS.toMillis(5));
closeConnectionExecutor.shutdown();
closeConnectionExecutor.awaitTermination(5L, TimeUnit.SECONDS);
logPoolState("After shutdown ");
unregisterMBeans(configuration, this);
metricsTracker.close();
}
}
/**
* Evict a connection from the pool.
*
* @param proxyConnection the connection to evict
*/
public final void evictConnection(IHikariConnectionProxy proxyConnection)
{
closeConnection(proxyConnection.getPoolBagEntry());
}
/**
* Get the wrapped DataSource.
*
* @return the wrapped DataSource
*/
public final DataSource getDataSource()
{
return dataSource;
}
/**
* Get the pool configuration object.
*
* @return the {@link HikariConfig} for this pool
*/
public final HikariConfig getConfiguration()
{
return configuration;
}
@Override
public String toString()
{
return configuration.getPoolName();
}
// ***********************************************************************
// HikariPoolMBean methods
// ***********************************************************************
/** {@inheritDoc} */
@Override
public final int getActiveConnections()
{
return connectionBag.getCount(STATE_IN_USE);
}
/** {@inheritDoc} */
@Override
public final int getIdleConnections()
{
return connectionBag.getCount(STATE_NOT_IN_USE);
}
/** {@inheritDoc} */
@Override
public final int getTotalConnections()
{
return connectionBag.size() - connectionBag.getCount(STATE_REMOVED);
}
/** {@inheritDoc} */
@Override
public final int getThreadsAwaitingConnection()
{
return connectionBag.getPendingQueue();
}
/** {@inheritDoc} */
@Override
public final void suspendPool()
{
if (!isPoolSuspended) {
suspendResumeLock.suspend();
isPoolSuspended = true;
}
}
/** {@inheritDoc} */
@Override
public final void resumePool()
{
if (isPoolSuspended) {
isPoolSuspended = false;
addBagItem(); // re-populate the pool
suspendResumeLock.resume();
}
}
// ***********************************************************************
// Protected methods
// ***********************************************************************
/**
* Create and add a single connection to the pool.
*/
protected final boolean addConnection()
{
// Speculative increment of totalConnections with expectation of success
if (totalConnections.incrementAndGet() > configuration.getMaximumPoolSize()) {
totalConnections.decrementAndGet();
return true;
}
Connection connection = null;
try {
connection = (username == null && password == null) ? dataSource.getConnection() : dataSource.getConnection(username, password);
if (isUseJdbc4Validation && !poolUtils.isJdbc40Compliant(connection)) {
throw new SQLException("JDBC4 Connection.isValid() method not supported, connection test query must be configured");
}
final boolean timeoutEnabled = (connectionTimeout != Integer.MAX_VALUE);
final long timeoutMs = timeoutEnabled ? Math.max(250L, connectionTimeout) : 0L;
final int originalTimeout = poolUtils.setNetworkTimeout(houseKeepingExecutorService, connection, timeoutMs, timeoutEnabled);
transactionIsolation = (transactionIsolation < 0 ? connection.getTransactionIsolation() : transactionIsolation);
poolUtils.setupConnection(connection, isAutoCommit, isReadOnly, transactionIsolation, catalog);
connectionCustomizer.customize(connection);
poolUtils.executeSql(connection, configuration.getConnectionInitSql(), isAutoCommit);
poolUtils.setNetworkTimeout(houseKeepingExecutorService, connection, originalTimeout, timeoutEnabled);
connectionBag.add(new PoolBagEntry(connection, this));
lastConnectionFailure.set(null);
return true;
}
catch (Exception e) {
totalConnections.decrementAndGet(); // We failed, so undo speculative increment of totalConnections
lastConnectionFailure.set(e);
poolUtils.quietlyCloseConnection(connection);
LOGGER.debug("Connection attempt to database {} failed: {}", configuration.getPoolName(), e.getMessage(), e);
return false;
}
}
// ***********************************************************************
// Abstract methods
// ***********************************************************************
/**
* Permanently close the real (underlying) connection (eat any exception).
*
* @param connectionProxy the connection to actually close
*/
protected abstract void closeConnection(final PoolBagEntry bagEntry);
/**
* Check whether the connection is alive or not.
*
* @param connection the connection to test
* @param timeoutMs the timeout before we consider the test a failure
* @return true if the connection is alive, false if it is not alive or we timed out
*/
protected abstract boolean isConnectionAlive(final Connection connection, final long timeoutMs);
/**
* Attempt to abort() active connections on Java7+, or close() them on Java6.
*
* @throws InterruptedException
*/
protected abstract void abortActiveConnections() throws InterruptedException;
/**
* Create the JVM version-specific ConcurrentBag instance used by the pool.
*
* @param listener the IBagStateListener instance
* @return a ConcurrentBag instance
*/
protected abstract ConcurrentBag<PoolBagEntry> createConcurrentBag(IBagStateListener listener);
/**
* Create the JVM version-specific Housekeeping runnable instance used by the pool.
* @return the HouseKeeper instance
*/
protected abstract Runnable getHouseKeeper();
// ***********************************************************************
// Private methods
// ***********************************************************************
/**
* Fill the pool up to the minimum size.
*/
private void fillPool()
{
if (configuration.getMinimumIdle() > 0) {
if (configuration.isInitializationFailFast() && !addConnection()) {
throw new RuntimeException("Fail-fast during pool initialization", lastConnectionFailure.getAndSet(null));
}
addBagItem();
}
}
/**
* Construct the user's connection customizer, if specified.
*
* @return an IConnectionCustomizer instance
*/
private IConnectionCustomizer initializeCustomizer()
{
if (configuration.getConnectionCustomizerClassName() != null) {
return createInstance(configuration.getConnectionCustomizerClassName(), IConnectionCustomizer.class);
}
return configuration.getConnectionCustomizer();
}
public final void logPoolState(String... prefix)
{
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("{}pool stats {} (total={}, inUse={}, avail={}, waiting={})",
(prefix.length > 0 ? prefix[0] : ""), configuration.getPoolName(),
getTotalConnections(), getActiveConnections(), getIdleConnections(), getThreadsAwaitingConnection());
}
}
}
| bobwenx/HikariCP | hikaricp-common/src/main/java/com/zaxxer/hikari/pool/BaseHikariPool.java | Java | apache-2.0 | 18,562 |
/*
Copyright 2020 The Kubernetes 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.
*/
// Code generated by client-gen. DO NOT EDIT.
package fake
import (
rest "k8s.io/client-go/rest"
testing "k8s.io/client-go/testing"
v1beta1 "k8s.io/ingress-gce/pkg/svcneg/client/clientset/versioned/typed/svcneg/v1beta1"
)
type FakeNetworkingV1beta1 struct {
*testing.Fake
}
func (c *FakeNetworkingV1beta1) ServiceNetworkEndpointGroups(namespace string) v1beta1.ServiceNetworkEndpointGroupInterface {
return &FakeServiceNetworkEndpointGroups{c, namespace}
}
// RESTClient returns a RESTClient that is used to communicate
// with API server by this client implementation.
func (c *FakeNetworkingV1beta1) RESTClient() rest.Interface {
var ret *rest.RESTClient
return ret
}
| kubernetes/ingress-gce | pkg/svcneg/client/clientset/versioned/typed/svcneg/v1beta1/fake/fake_svcneg_client.go | GO | apache-2.0 | 1,253 |
/*
* Copyright 2020 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 by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/domains/v1beta1/domains.proto
package com.google.cloud.domains.v1beta1;
/**
*
*
* <pre>
* Request for the `RetrieveRegisterParameters` method.
* </pre>
*
* Protobuf type {@code google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest}
*/
public final class RetrieveRegisterParametersRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest)
RetrieveRegisterParametersRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use RetrieveRegisterParametersRequest.newBuilder() to construct.
private RetrieveRegisterParametersRequest(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private RetrieveRegisterParametersRequest() {
domainName_ = "";
location_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new RetrieveRegisterParametersRequest();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private RetrieveRegisterParametersRequest(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
java.lang.String s = input.readStringRequireUtf8();
domainName_ = s;
break;
}
case 18:
{
java.lang.String s = input.readStringRequireUtf8();
location_ = s;
break;
}
default:
{
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.domains.v1beta1.DomainsProto
.internal_static_google_cloud_domains_v1beta1_RetrieveRegisterParametersRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.domains.v1beta1.DomainsProto
.internal_static_google_cloud_domains_v1beta1_RetrieveRegisterParametersRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest.class,
com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest.Builder.class);
}
public static final int DOMAIN_NAME_FIELD_NUMBER = 1;
private volatile java.lang.Object domainName_;
/**
*
*
* <pre>
* Required. The domain name. Unicode domain names must be expressed in Punycode format.
* </pre>
*
* <code>string domain_name = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The domainName.
*/
@java.lang.Override
public java.lang.String getDomainName() {
java.lang.Object ref = domainName_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
domainName_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The domain name. Unicode domain names must be expressed in Punycode format.
* </pre>
*
* <code>string domain_name = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for domainName.
*/
@java.lang.Override
public com.google.protobuf.ByteString getDomainNameBytes() {
java.lang.Object ref = domainName_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
domainName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int LOCATION_FIELD_NUMBER = 2;
private volatile java.lang.Object location_;
/**
*
*
* <pre>
* Required. The location. Must be in the format `projects/*/locations/*`.
* </pre>
*
* <code>
* string location = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The location.
*/
@java.lang.Override
public java.lang.String getLocation() {
java.lang.Object ref = location_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
location_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The location. Must be in the format `projects/*/locations/*`.
* </pre>
*
* <code>
* string location = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for location.
*/
@java.lang.Override
public com.google.protobuf.ByteString getLocationBytes() {
java.lang.Object ref = location_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
location_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(domainName_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, domainName_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(location_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, location_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(domainName_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, domainName_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(location_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, location_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest)) {
return super.equals(obj);
}
com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest other =
(com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest) obj;
if (!getDomainName().equals(other.getDomainName())) return false;
if (!getLocation().equals(other.getLocation())) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + DOMAIN_NAME_FIELD_NUMBER;
hash = (53 * hash) + getDomainName().hashCode();
hash = (37 * hash) + LOCATION_FIELD_NUMBER;
hash = (53 * hash) + getLocation().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest
parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Request for the `RetrieveRegisterParameters` method.
* </pre>
*
* Protobuf type {@code google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest)
com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.domains.v1beta1.DomainsProto
.internal_static_google_cloud_domains_v1beta1_RetrieveRegisterParametersRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.domains.v1beta1.DomainsProto
.internal_static_google_cloud_domains_v1beta1_RetrieveRegisterParametersRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest.class,
com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest.Builder.class);
}
// Construct using
// com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}
}
@java.lang.Override
public Builder clear() {
super.clear();
domainName_ = "";
location_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.domains.v1beta1.DomainsProto
.internal_static_google_cloud_domains_v1beta1_RetrieveRegisterParametersRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest
getDefaultInstanceForType() {
return com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest
.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest build() {
com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest buildPartial() {
com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest result =
new com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest(this);
result.domainName_ = domainName_;
result.location_ = location_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest) {
return mergeFrom(
(com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest other) {
if (other
== com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest
.getDefaultInstance()) return this;
if (!other.getDomainName().isEmpty()) {
domainName_ = other.domainName_;
onChanged();
}
if (!other.getLocation().isEmpty()) {
location_ = other.location_;
onChanged();
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage =
(com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest)
e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object domainName_ = "";
/**
*
*
* <pre>
* Required. The domain name. Unicode domain names must be expressed in Punycode format.
* </pre>
*
* <code>string domain_name = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The domainName.
*/
public java.lang.String getDomainName() {
java.lang.Object ref = domainName_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
domainName_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The domain name. Unicode domain names must be expressed in Punycode format.
* </pre>
*
* <code>string domain_name = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for domainName.
*/
public com.google.protobuf.ByteString getDomainNameBytes() {
java.lang.Object ref = domainName_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
domainName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The domain name. Unicode domain names must be expressed in Punycode format.
* </pre>
*
* <code>string domain_name = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The domainName to set.
* @return This builder for chaining.
*/
public Builder setDomainName(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
domainName_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The domain name. Unicode domain names must be expressed in Punycode format.
* </pre>
*
* <code>string domain_name = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearDomainName() {
domainName_ = getDefaultInstance().getDomainName();
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The domain name. Unicode domain names must be expressed in Punycode format.
* </pre>
*
* <code>string domain_name = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for domainName to set.
* @return This builder for chaining.
*/
public Builder setDomainNameBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
domainName_ = value;
onChanged();
return this;
}
private java.lang.Object location_ = "";
/**
*
*
* <pre>
* Required. The location. Must be in the format `projects/*/locations/*`.
* </pre>
*
* <code>
* string location = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The location.
*/
public java.lang.String getLocation() {
java.lang.Object ref = location_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
location_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The location. Must be in the format `projects/*/locations/*`.
* </pre>
*
* <code>
* string location = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for location.
*/
public com.google.protobuf.ByteString getLocationBytes() {
java.lang.Object ref = location_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
location_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The location. Must be in the format `projects/*/locations/*`.
* </pre>
*
* <code>
* string location = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The location to set.
* @return This builder for chaining.
*/
public Builder setLocation(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
location_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The location. Must be in the format `projects/*/locations/*`.
* </pre>
*
* <code>
* string location = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearLocation() {
location_ = getDefaultInstance().getLocation();
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The location. Must be in the format `projects/*/locations/*`.
* </pre>
*
* <code>
* string location = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for location to set.
* @return This builder for chaining.
*/
public Builder setLocationBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
location_ = value;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest)
private static final com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest();
}
public static com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<RetrieveRegisterParametersRequest> PARSER =
new com.google.protobuf.AbstractParser<RetrieveRegisterParametersRequest>() {
@java.lang.Override
public RetrieveRegisterParametersRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new RetrieveRegisterParametersRequest(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<RetrieveRegisterParametersRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<RetrieveRegisterParametersRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.domains.v1beta1.RetrieveRegisterParametersRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| googleapis/java-domains | proto-google-cloud-domains-v1beta1/src/main/java/com/google/cloud/domains/v1beta1/RetrieveRegisterParametersRequest.java | Java | apache-2.0 | 27,978 |
package com.sequenceiq.datalake.flow.diagnostics.event;
import static com.sequenceiq.datalake.flow.diagnostics.SdxCmDiagnosticsEvent.SDX_CM_DIAGNOSTICS_COLLECTION_FAILED_EVENT;
import java.util.Map;
import com.sequenceiq.datalake.flow.SdxFailedEvent;
public class SdxCmDiagnosticsFailedEvent extends SdxFailedEvent {
private final Map<String, Object> properties;
public SdxCmDiagnosticsFailedEvent(Long sdxId, String userId, Map<String, Object> properties, Exception exception) {
super(sdxId, userId, exception);
this.properties = properties;
}
public static SdxDiagnosticsFailedEvent from(BaseSdxCmDiagnosticsEvent event, Exception exception) {
return new SdxDiagnosticsFailedEvent(event.getResourceId(), event.getUserId(), event.getProperties(), exception);
}
@Override
public String selector() {
return SDX_CM_DIAGNOSTICS_COLLECTION_FAILED_EVENT.event();
}
}
| hortonworks/cloudbreak | datalake/src/main/java/com/sequenceiq/datalake/flow/diagnostics/event/SdxCmDiagnosticsFailedEvent.java | Java | apache-2.0 | 934 |
package com.vint.iblog.web.servlet;
import com.vint.iblog.datastore.define.SequenceManagerDAO;
import com.vint.iblog.datastore.define.StaticDataDAO;
import org.apache.commons.lang3.StringUtils;
import org.vintsie.jcobweb.proxy.ServiceFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
*
* Created by Vin on 14-2-17.
*/
public class ConfigurationServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String cfgType = req.getParameter("cfgType");
PrintWriter pw = resp.getWriter();
// 配置静态数据
if (StringUtils.equals(cfgType, "sd")) {
String operation = req.getParameter("operation");
// 新增配置数据
if (StringUtils.equals("add", operation)) {
String dataType = req.getParameter("dataType");
String dataValue = req.getParameter("dataValue");
String sort = req.getParameter("sort");
if (StringUtils.isEmpty(dataType) || StringUtils.isEmpty(dataValue)) {
pw.write("When creating new static data, neither dataType or dataValue can not be null.");
} else {
try {
StaticDataDAO sdd = ServiceFactory.getService(StaticDataDAO.class);
sdd.newStaticData(dataType, dataValue, Integer.parseInt(sort));
pw.write("success");
} catch (Exception e) {
pw.write(e.getMessage());
e.printStackTrace();
}
}
}
} else if (StringUtils.equals(cfgType, "seq")) {
/**
* 序列的操作分为两种,read和write.如果传入的operation是read,则只查询
* 对应Type的序列值。当传入的操作时write时,则会清理对应Type的序列数据,
* 并使用新的16进制字符串代替。
*
* Url实例:
* http://localhost:8080/cfg?cfgType=seq&operation=read&type=BLOG&hex=101c0701
* http://localhost:8080/cfg?cfgType=seq&operation=wirte&type=BLOG&hex=101c0701
*/
String type = req.getParameter("type");
String hex = req.getParameter("hex");
String operation = req.getParameter("operation");
try {
SequenceManagerDAO sequenceManagerDAO = ServiceFactory.getService(SequenceManagerDAO.class);
if (StringUtils.equals("read", operation)) {
pw.write(type + "'s current Sequence is " + sequenceManagerDAO.getCurrentSeq(type));
} else if (StringUtils.equals("write", operation)) {
sequenceManagerDAO.createSequence(type, hex);
pw.write("Success!!");
}
} catch (Exception e) {
pw.write(e.getMessage());
e.printStackTrace();
}
} else {
pw.write("No mapping operation found according to " + cfgType);
}
pw.flush();
pw.close();
}
}
| vintsie/iblog | src/main/java/com/vint/iblog/web/servlet/ConfigurationServlet.java | Java | apache-2.0 | 3,565 |
package rest
import (
"bytes"
"encoding/base64"
"fmt"
"io"
"net/url"
"path"
"reflect"
"strconv"
"strings"
"time"
"github.com/datacratic/aws-sdk-go/aws"
)
// RFC822 returns an RFC822 formatted timestamp for AWS protocols
const RFC822 = "Mon, 2 Jan 2006 15:04:05 GMT"
func Build(r *aws.Request) {
if r.ParamsFilled() {
v := reflect.ValueOf(r.Params).Elem()
buildLocationElements(r, v)
buildBody(r, v)
}
}
func buildLocationElements(r *aws.Request, v reflect.Value) {
query := r.HTTPRequest.URL.Query()
for i := 0; i < v.NumField(); i++ {
m := v.Field(i)
if n := v.Type().Field(i).Name; n[0:1] == strings.ToLower(n[0:1]) {
continue
}
if m.IsValid() {
field := v.Type().Field(i)
name := field.Tag.Get("locationName")
if name == "" {
name = field.Name
}
if m.Kind() == reflect.Ptr {
m = m.Elem()
}
if !m.IsValid() {
continue
}
switch field.Tag.Get("location") {
case "headers": // header maps
buildHeaderMap(r, m, field.Tag.Get("locationName"))
case "header":
buildHeader(r, m, name)
case "uri":
buildURI(r, m, name)
case "querystring":
buildQueryString(r, m, name, query)
}
}
if r.Error != nil {
return
}
}
r.HTTPRequest.URL.RawQuery = query.Encode()
updatePath(r.HTTPRequest.URL, r.HTTPRequest.URL.Path)
}
func buildBody(r *aws.Request, v reflect.Value) {
if field, ok := v.Type().FieldByName("SDKShapeTraits"); ok {
if payloadName := field.Tag.Get("payload"); payloadName != "" {
pfield, _ := v.Type().FieldByName(payloadName)
if ptag := pfield.Tag.Get("type"); ptag != "" && ptag != "structure" {
payload := reflect.Indirect(v.FieldByName(payloadName))
if payload.IsValid() && payload.Interface() != nil {
switch reader := payload.Interface().(type) {
case io.ReadSeeker:
r.SetReaderBody(reader)
case []byte:
r.SetBufferBody(reader)
case string:
r.SetBufferBody([]byte(reader))
default:
r.Error = fmt.Errorf("unknown payload type %s", payload.Type())
}
}
}
}
}
}
func buildHeader(r *aws.Request, v reflect.Value, name string) {
str, err := convertType(v)
if err != nil {
r.Error = err
} else if str != nil {
r.HTTPRequest.Header.Add(name, *str)
}
}
func buildHeaderMap(r *aws.Request, v reflect.Value, prefix string) {
for _, key := range v.MapKeys() {
str, err := convertType(v.MapIndex(key))
if err != nil {
r.Error = err
} else if str != nil {
r.HTTPRequest.Header.Add(prefix+key.String(), *str)
}
}
}
func buildURI(r *aws.Request, v reflect.Value, name string) {
value, err := convertType(v)
if err != nil {
r.Error = err
} else if value != nil {
uri := r.HTTPRequest.URL.Path
uri = strings.Replace(uri, "{"+name+"}", escapePath(*value, true), -1)
uri = strings.Replace(uri, "{"+name+"+}", escapePath(*value, false), -1)
r.HTTPRequest.URL.Path = uri
}
}
func buildQueryString(r *aws.Request, v reflect.Value, name string, query url.Values) {
str, err := convertType(v)
if err != nil {
r.Error = err
} else if str != nil {
query.Set(name, *str)
}
}
func updatePath(url *url.URL, urlPath string) {
scheme, query := url.Scheme, url.RawQuery
// clean up path
urlPath = path.Clean(urlPath)
// get formatted URL minus scheme so we can build this into Opaque
url.Scheme, url.Path, url.RawQuery = "", "", ""
s := url.String()
url.Scheme = scheme
url.RawQuery = query
// build opaque URI
url.Opaque = s + urlPath
}
// Whether the byte value can be sent without escaping in AWS URLs
var noEscape [256]bool
var noEscapeInitialized = false
// initialise noEscape
func initNoEscape() {
for i := range noEscape {
// Amazon expects every character except these escaped
noEscape[i] = (i >= 'A' && i <= 'Z') ||
(i >= 'a' && i <= 'z') ||
(i >= '0' && i <= '9') ||
i == '-' ||
i == '.' ||
i == '_' ||
i == '~'
}
}
// escapePath escapes part of a URL path in Amazon style
func escapePath(path string, encodeSep bool) string {
if !noEscapeInitialized {
initNoEscape()
noEscapeInitialized = true
}
var buf bytes.Buffer
for i := 0; i < len(path); i++ {
c := path[i]
if noEscape[c] || (c == '/' && !encodeSep) {
buf.WriteByte(c)
} else {
buf.WriteByte('%')
buf.WriteString(strings.ToUpper(strconv.FormatUint(uint64(c), 16)))
}
}
return buf.String()
}
func convertType(v reflect.Value) (*string, error) {
v = reflect.Indirect(v)
if !v.IsValid() {
return nil, nil
}
var str string
switch value := v.Interface().(type) {
case string:
str = value
case []byte:
str = base64.StdEncoding.EncodeToString(value)
case bool:
str = strconv.FormatBool(value)
case int64:
str = strconv.FormatInt(value, 10)
case float64:
str = strconv.FormatFloat(value, 'f', -1, 64)
case time.Time:
str = value.UTC().Format(RFC822)
default:
err := fmt.Errorf("Unsupported value for param %v (%s)", v.Interface(), v.Type())
return nil, err
}
return &str, nil
}
| datacratic/aws-sdk-go | internal/protocol/rest/build.go | GO | apache-2.0 | 4,968 |
/**
* Copyright 2010-2016 the original author or authors.
*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.yunmel.db.utils;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import com.yunmel.db.common.DatasourceConfig;
public class PropertyHolderUtil {
private final static String CONFIG_FILE_PATH = "app.properties";
private static Properties props = null;
static {
props = new Properties();
try {
InputStream input = PropertyHolderUtil.class.getResourceAsStream("/" + CONFIG_FILE_PATH);
if (input == null) {
ClassLoader classLoader = PropertyHolderUtil.class.getClassLoader();
input = PropertyHolderUtil.class.getResourceAsStream("" + classLoader.getResource(CONFIG_FILE_PATH));
}
if (input == null) {
String path = System.getProperty("user.dir") + "/" + CONFIG_FILE_PATH;
input = new FileInputStream(path);
}
props.load(input);
} catch (Exception e) {
e.printStackTrace();
}
}
private PropertyHolderUtil() {
super();
}
public static String getProperty(String propName) {
return props.getProperty(propName);
}
public static DatasourceConfig getDsConfig() {
DatasourceConfig config = new DatasourceConfig();
String driverClass = props.getProperty("jdbc.driverClass");
String jdbcUrl = props.getProperty("jdbc.url");
String username = props.getProperty("jdbc.user");
String password = props.getProperty("jdbc.password");
config.setDriverClass(driverClass);
config.setJdbcUrl(jdbcUrl);
config.setUsername(username);
config.setPassword(password);
String poolType = props.getProperty("jdbc.pool.type");
if (StringUtils.isNotBlank(poolType)) {
Map<String, String> poolPerperties = new HashMap<>();
poolPerperties.put(DatasourceConfig._POOL_TYPE, poolType);
config.setPoolPerperties(poolPerperties);
}
return config;
}
}
| yunmel/rps | src/main/java/com/yunmel/db/utils/PropertyHolderUtil.java | Java | apache-2.0 | 2,765 |
/**
Copyright 2010 OpenEngSB Division, Vienna University of Technology
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.openengsb.drools;
import org.openengsb.drools.model.Notification;
public interface NotificationDomain extends Domain {
void notify(Notification notification);
}
| tobster/openengsb | core/workflow/domains/src/main/java/org/openengsb/drools/NotificationDomain.java | Java | apache-2.0 | 784 |
package io.quarkus.resteasy.reactive.jackson.deployment.test;
import java.util.function.Supplier;
import org.hamcrest.Matchers;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import io.quarkus.test.QuarkusUnitTest;
import io.restassured.RestAssured;
public class VertxJsonTest {
@RegisterExtension
static QuarkusUnitTest test = new QuarkusUnitTest()
.setArchiveProducer(new Supplier<JavaArchive>() {
@Override
public JavaArchive get() {
return ShrinkWrap.create(JavaArchive.class)
.addClasses(VertxJsonEndpoint.class);
}
});
@Test
public void testJsonObject() {
RestAssured.with()
.body("{\"name\": \"Bob\"}")
.contentType("application/json")
.post("/vertx/jsonObject")
.then()
.statusCode(200)
.contentType("application/json")
.body("name", Matchers.equalTo("Bob"))
.body("age", Matchers.equalTo(50))
.body("nested.foo", Matchers.equalTo("bar"))
.body("bools[0]", Matchers.equalTo(true));
}
@Test
public void testJsonArray() {
RestAssured.with()
.body("[\"first\"]")
.contentType("application/json")
.post("/vertx/jsonArray")
.then()
.statusCode(200)
.contentType("application/json")
.body("[0]", Matchers.equalTo("first"))
.body("[1]", Matchers.equalTo("last"));
}
}
| quarkusio/quarkus | extensions/resteasy-reactive/quarkus-resteasy-reactive-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/VertxJsonTest.java | Java | apache-2.0 | 1,773 |
/*
* 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.hadoop.hive.ql.txn.compactor;
import org.apache.commons.io.FileUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.common.ServerUtils;
import org.apache.hadoop.hive.common.ValidCompactorWriteIdList;
import org.apache.hadoop.hive.common.ValidTxnList;
import org.apache.hadoop.hive.common.ValidWriteIdList;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.HiveMetaStoreClient;
import org.apache.hadoop.hive.metastore.IMetaStoreClient;
import org.apache.hadoop.hive.metastore.TableType;
import org.apache.hadoop.hive.metastore.TransactionalValidationListener;
import org.apache.hadoop.hive.metastore.api.AbortTxnRequest;
import org.apache.hadoop.hive.metastore.api.AllocateTableWriteIdsRequest;
import org.apache.hadoop.hive.metastore.api.AllocateTableWriteIdsResponse;
import org.apache.hadoop.hive.metastore.api.CommitTxnRequest;
import org.apache.hadoop.hive.metastore.api.CompactionRequest;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.GetValidWriteIdsRequest;
import org.apache.hadoop.hive.metastore.api.LockRequest;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.metastore.api.NoSuchTxnException;
import org.apache.hadoop.hive.metastore.api.OpenTxnRequest;
import org.apache.hadoop.hive.metastore.api.OpenTxnsResponse;
import org.apache.hadoop.hive.metastore.api.Order;
import org.apache.hadoop.hive.metastore.api.Partition;
import org.apache.hadoop.hive.metastore.api.SerDeInfo;
import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
import org.apache.hadoop.hive.metastore.api.Table;
import org.apache.hadoop.hive.metastore.api.TxnAbortedException;
import org.apache.hadoop.hive.metastore.api.TxnType;
import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants;
import org.apache.hadoop.hive.metastore.conf.MetastoreConf;
import org.apache.hadoop.hive.metastore.metrics.AcidMetricService;
import org.apache.hadoop.hive.metastore.txn.CompactionInfo;
import org.apache.hadoop.hive.metastore.txn.TxnCommonUtils;
import org.apache.hadoop.hive.metastore.utils.TestTxnDbUtil;
import org.apache.hadoop.hive.metastore.txn.TxnStore;
import org.apache.hadoop.hive.metastore.txn.TxnUtils;
import org.apache.hadoop.hive.ql.io.AcidInputFormat;
import org.apache.hadoop.hive.ql.io.AcidOutputFormat;
import org.apache.hadoop.hive.ql.io.AcidUtils;
import org.apache.hadoop.hive.ql.io.RecordIdentifier;
import org.apache.hadoop.hive.ql.io.RecordUpdater;
import org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.mapred.InputSplit;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.RecordReader;
import org.apache.hadoop.mapred.RecordWriter;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.util.Progressable;
import org.apache.thrift.TException;
import org.junit.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Stack;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.hadoop.hive.ql.txn.compactor.CompactorTestUtilities.CompactorThreadType;
/**
* Super class for all of the compactor test modules.
*/
public abstract class CompactorTest {
static final private String CLASS_NAME = CompactorTest.class.getName();
static final private Logger LOG = LoggerFactory.getLogger(CLASS_NAME);
public static final String WORKER_VERSION = "4.0.0";
protected TxnStore txnHandler;
protected IMetaStoreClient ms;
protected HiveConf conf;
private final AtomicBoolean stop = new AtomicBoolean();
protected File tmpdir;
@Before
public void setup() throws Exception {
conf = new HiveConf();
TestTxnDbUtil.setConfValues(conf);
TestTxnDbUtil.cleanDb(conf);
TestTxnDbUtil.prepDb(conf);
ms = new HiveMetaStoreClient(conf);
txnHandler = TxnUtils.getTxnStore(conf);
tmpdir = new File(Files.createTempDirectory("compactor_test_table_").toString());
}
protected void compactorTestCleanup() throws IOException {
FileUtils.deleteDirectory(tmpdir);
}
protected void startInitiator() throws Exception {
startThread(CompactorThreadType.INITIATOR, true);
}
protected void startWorker() throws Exception {
startThread(CompactorThreadType.WORKER, true);
}
protected void startCleaner() throws Exception {
startThread(CompactorThreadType.CLEANER, true);
}
protected void runAcidMetricService() throws Exception {
TestTxnDbUtil.setConfValues(conf);
AcidMetricService t = new AcidMetricService();
t.setConf(conf);
t.run();
}
protected Table newTable(String dbName, String tableName, boolean partitioned) throws TException {
return newTable(dbName, tableName, partitioned, new HashMap<String, String>(), null, false);
}
protected Table newTable(String dbName, String tableName, boolean partitioned,
Map<String, String> parameters) throws TException {
return newTable(dbName, tableName, partitioned, parameters, null, false);
}
protected Table newTable(String dbName, String tableName, boolean partitioned,
Map<String, String> parameters, List<Order> sortCols,
boolean isTemporary)
throws TException {
Table table = new Table();
table.setTableType(TableType.MANAGED_TABLE.name());
table.setTableName(tableName);
table.setDbName(dbName);
table.setOwner("me");
table.setSd(newStorageDescriptor(getLocation(tableName, null), sortCols));
List<FieldSchema> partKeys = new ArrayList<FieldSchema>(1);
if (partitioned) {
partKeys.add(new FieldSchema("ds", "string", "no comment"));
table.setPartitionKeys(partKeys);
}
// Set the table as transactional for compaction to work
if (parameters == null) {
parameters = new HashMap<>();
}
parameters.put(hive_metastoreConstants.TABLE_IS_TRANSACTIONAL, "true");
if (sortCols != null) {
// Sort columns are not allowed for full ACID table. So, change it to insert-only table
parameters.put(hive_metastoreConstants.TABLE_TRANSACTIONAL_PROPERTIES,
TransactionalValidationListener.INSERTONLY_TRANSACTIONAL_PROPERTY);
}
table.setParameters(parameters);
if (isTemporary) table.setTemporary(true);
// drop the table first, in case some previous test created it
ms.dropTable(dbName, tableName);
ms.createTable(table);
return table;
}
protected Partition newPartition(Table t, String value) throws Exception {
return newPartition(t, value, null);
}
protected Partition newPartition(Table t, String value, List<Order> sortCols) throws Exception {
Partition part = new Partition();
part.addToValues(value);
part.setDbName(t.getDbName());
part.setTableName(t.getTableName());
part.setSd(newStorageDescriptor(getLocation(t.getTableName(), value), sortCols));
part.setParameters(new HashMap<String, String>());
ms.add_partition(part);
return part;
}
protected long openTxn() throws MetaException {
return openTxn(TxnType.DEFAULT);
}
protected long openTxn(TxnType txnType) throws MetaException {
OpenTxnRequest rqst = new OpenTxnRequest(1, System.getProperty("user.name"), ServerUtils.hostname());
rqst.setTxn_type(txnType);
if (txnType == TxnType.REPL_CREATED) {
rqst.setReplPolicy("default.*");
rqst.setReplSrcTxnIds(Arrays.asList(1L));
}
List<Long> txns = txnHandler.openTxns(rqst).getTxn_ids();
return txns.get(0);
}
protected long allocateWriteId(String dbName, String tblName, long txnid)
throws MetaException, TxnAbortedException, NoSuchTxnException {
AllocateTableWriteIdsRequest awiRqst
= new AllocateTableWriteIdsRequest(dbName, tblName);
awiRqst.setTxnIds(Collections.singletonList(txnid));
AllocateTableWriteIdsResponse awiResp = txnHandler.allocateTableWriteIds(awiRqst);
return awiResp.getTxnToWriteIds().get(0).getWriteId();
}
protected void addDeltaFile(Table t, Partition p, long minTxn, long maxTxn, int numRecords)
throws Exception {
addFile(t, p, minTxn, maxTxn, numRecords, FileType.DELTA, 2, true);
}
protected void addLengthFile(Table t, Partition p, long minTxn, long maxTxn, int numRecords)
throws Exception {
addFile(t, p, minTxn, maxTxn, numRecords, FileType.LENGTH_FILE, 2, true);
}
protected void addBaseFile(Table t, Partition p, long maxTxn, int numRecords) throws Exception {
addFile(t, p, 0, maxTxn, numRecords, FileType.BASE, 2, true);
}
protected void addBaseFile(Table t, Partition p, long maxTxn, int numRecords, long visibilityId) throws Exception {
addFile(t, p, 0, maxTxn, numRecords, FileType.BASE, 2, true, visibilityId);
}
protected void addLegacyFile(Table t, Partition p, int numRecords) throws Exception {
addFile(t, p, 0, 0, numRecords, FileType.LEGACY, 2, true);
}
protected void addDeltaFile(Table t, Partition p, long minTxn, long maxTxn, int numRecords,
int numBuckets, boolean allBucketsPresent) throws Exception {
addFile(t, p, minTxn, maxTxn, numRecords, FileType.DELTA, numBuckets, allBucketsPresent);
}
protected void addBaseFile(Table t, Partition p, long maxTxn, int numRecords, int numBuckets,
boolean allBucketsPresent) throws Exception {
addFile(t, p, 0, maxTxn, numRecords, FileType.BASE, numBuckets, allBucketsPresent);
}
protected List<Path> getDirectories(HiveConf conf, Table t, Partition p) throws Exception {
String partValue = (p == null) ? null : p.getValues().get(0);
String location = getLocation(t.getTableName(), partValue);
Path dir = new Path(location);
FileSystem fs = FileSystem.get(conf);
FileStatus[] stats = fs.listStatus(dir);
List<Path> paths = new ArrayList<Path>(stats.length);
for (int i = 0; i < stats.length; i++) paths.add(stats[i].getPath());
return paths;
}
protected void burnThroughTransactions(String dbName, String tblName, int num)
throws MetaException, NoSuchTxnException, TxnAbortedException {
burnThroughTransactions(dbName, tblName, num, null, null);
}
protected void burnThroughTransactions(String dbName, String tblName, int num, Set<Long> open, Set<Long> aborted)
throws NoSuchTxnException, TxnAbortedException, MetaException {
burnThroughTransactions(dbName, tblName, num, open, aborted, null);
}
protected void burnThroughTransactions(String dbName, String tblName, int num, Set<Long> open, Set<Long> aborted, LockRequest lockReq)
throws MetaException, NoSuchTxnException, TxnAbortedException {
OpenTxnsResponse rsp = txnHandler.openTxns(new OpenTxnRequest(num, "me", "localhost"));
AllocateTableWriteIdsRequest awiRqst = new AllocateTableWriteIdsRequest(dbName, tblName);
awiRqst.setTxnIds(rsp.getTxn_ids());
AllocateTableWriteIdsResponse awiResp = txnHandler.allocateTableWriteIds(awiRqst);
int i = 0;
for (long tid : rsp.getTxn_ids()) {
assert(awiResp.getTxnToWriteIds().get(i++).getTxnId() == tid);
if(lockReq != null) {
lockReq.setTxnid(tid);
txnHandler.lock(lockReq);
}
if (aborted != null && aborted.contains(tid)) {
txnHandler.abortTxn(new AbortTxnRequest(tid));
} else if (open == null || (open != null && !open.contains(tid))) {
txnHandler.commitTxn(new CommitTxnRequest(tid));
}
}
}
protected void stopThread() {
stop.set(true);
}
private StorageDescriptor newStorageDescriptor(String location, List<Order> sortCols) {
StorageDescriptor sd = new StorageDescriptor();
List<FieldSchema> cols = new ArrayList<FieldSchema>(2);
cols.add(new FieldSchema("a", "varchar(25)", "still no comment"));
cols.add(new FieldSchema("b", "int", "comment"));
sd.setCols(cols);
sd.setLocation(location);
sd.setInputFormat(MockInputFormat.class.getName());
sd.setOutputFormat(MockOutputFormat.class.getName());
sd.setNumBuckets(1);
SerDeInfo serde = new SerDeInfo();
serde.setSerializationLib(LazySimpleSerDe.class.getName());
sd.setSerdeInfo(serde);
List<String> bucketCols = new ArrayList<String>(1);
bucketCols.add("a");
sd.setBucketCols(bucketCols);
if (sortCols != null) {
sd.setSortCols(sortCols);
}
return sd;
}
// I can't do this with @Before because I want to be able to control when the thread starts
private void startThread(CompactorThreadType type, boolean stopAfterOne) throws Exception {
TestTxnDbUtil.setConfValues(conf);
CompactorThread t;
switch (type) {
case INITIATOR: t = new Initiator(); break;
case WORKER: t = new Worker(); break;
case CLEANER: t = new Cleaner(); break;
default: throw new RuntimeException("Huh? Unknown thread type.");
}
t.setThreadId((int) t.getId());
t.setConf(conf);
stop.set(stopAfterOne);
t.init(stop);
if (stopAfterOne) t.run();
else t.start();
}
private String getLocation(String tableName, String partValue) {
String location = tmpdir.getAbsolutePath() +
System.getProperty("file.separator") + tableName;
if (partValue != null) {
location += System.getProperty("file.separator") + "ds=" + partValue;
}
return location;
}
private enum FileType {BASE, DELTA, LEGACY, LENGTH_FILE}
private void addFile(Table t, Partition p, long minTxn, long maxTxn, int numRecords, FileType type, int numBuckets,
boolean allBucketsPresent) throws Exception {
addFile(t, p, minTxn, maxTxn, numRecords, type, numBuckets, allBucketsPresent, 0);
}
private void addFile(Table t, Partition p, long minTxn, long maxTxn, int numRecords, FileType type, int numBuckets,
boolean allBucketsPresent, long visibilityId) throws Exception {
String partValue = (p == null) ? null : p.getValues().get(0);
Path location = new Path(getLocation(t.getTableName(), partValue));
String filename = null;
switch (type) {
case BASE: filename = AcidUtils.BASE_PREFIX + maxTxn + (visibilityId > 0 ? AcidUtils.VISIBILITY_PREFIX + visibilityId : ""); break;
case LENGTH_FILE: // Fall through to delta
case DELTA: filename = makeDeltaDirName(minTxn, maxTxn); break;
case LEGACY: break; // handled below
}
FileSystem fs = FileSystem.get(conf);
for (int bucket = 0; bucket < numBuckets; bucket++) {
if (bucket == 0 && !allBucketsPresent) continue; // skip one
Path partFile = null;
if (type == FileType.LEGACY) {
partFile = new Path(location, String.format(AcidUtils.LEGACY_FILE_BUCKET_DIGITS, bucket) + "_0");
} else {
Path dir = new Path(location, filename);
fs.mkdirs(dir);
partFile = AcidUtils.createBucketFile(dir, bucket);
if (type == FileType.LENGTH_FILE) {
partFile = new Path(partFile.toString() + AcidUtils.DELTA_SIDE_FILE_SUFFIX);
}
}
FSDataOutputStream out = fs.create(partFile);
if (type == FileType.LENGTH_FILE) {
out.writeInt(numRecords);//hmm - length files should store length in bytes...
} else {
for (int i = 0; i < numRecords; i++) {
RecordIdentifier ri = new RecordIdentifier(maxTxn - 1, bucket, i);
ri.write(out);
out.writeBytes("mary had a little lamb its fleece was white as snow\n");
}
}
out.close();
}
}
static class MockInputFormat implements AcidInputFormat<WritableComparable,Text> {
@Override
public AcidInputFormat.RowReader<Text> getReader(InputSplit split,
Options options) throws
IOException {
return null;
}
@Override
public RawReader<Text> getRawReader(Configuration conf, boolean collapseEvents, int bucket,
ValidWriteIdList validWriteIdList,
Path baseDirectory, Path[] deltaDirectory, Map<String, Integer> deltaToAttemptId) throws IOException {
List<Path> filesToRead = new ArrayList<Path>();
if (baseDirectory != null) {
if (baseDirectory.getName().startsWith(AcidUtils.BASE_PREFIX)) {
Path p = AcidUtils.createBucketFile(baseDirectory, bucket);
FileSystem fs = p.getFileSystem(conf);
if (fs.exists(p)) filesToRead.add(p);
} else {
filesToRead.add(new Path(baseDirectory, "000000_0"));
}
}
for (int i = 0; i < deltaDirectory.length; i++) {
Path p = AcidUtils.createBucketFile(deltaDirectory[i], bucket);
FileSystem fs = p.getFileSystem(conf);
if (fs.exists(p)) filesToRead.add(p);
}
return new MockRawReader(conf, filesToRead);
}
@Override
public InputSplit[] getSplits(JobConf entries, int i) throws IOException {
return new InputSplit[0];
}
@Override
public RecordReader<WritableComparable, Text> getRecordReader(InputSplit inputSplit, JobConf entries,
Reporter reporter) throws IOException {
return null;
}
@Override
public boolean validateInput(FileSystem fs, HiveConf conf, List<FileStatus> files) throws
IOException {
return false;
}
}
static class MockRawReader implements AcidInputFormat.RawReader<Text> {
private final Stack<Path> filesToRead;
private final Configuration conf;
private FSDataInputStream is = null;
private final FileSystem fs;
private boolean lastWasDelete = true;
MockRawReader(Configuration conf, List<Path> files) throws IOException {
filesToRead = new Stack<Path>();
for (Path file : files) filesToRead.push(file);
this.conf = conf;
fs = FileSystem.get(conf);
}
@Override
public ObjectInspector getObjectInspector() {
return null;
}
/**
* This is bogus especially with split update acid tables. This causes compaction to create
* delete_delta_x_y where none existed before. Makes the data layout such as would never be
* created by 'real' code path.
*/
@Override
public boolean isDelete(Text value) {
// Alternate between returning deleted and not. This is easier than actually
// tracking operations. We test that this is getting properly called by checking that only
// half the records show up in base files after major compactions.
lastWasDelete = !lastWasDelete;
return lastWasDelete;
}
@Override
public boolean next(RecordIdentifier identifier, Text text) throws IOException {
if (is == null) {
// Open the next file
if (filesToRead.empty()) return false;
Path p = filesToRead.pop();
LOG.debug("Reading records from " + p.toString());
is = fs.open(p);
}
String line = null;
try {
identifier.readFields(is);
line = is.readLine();
} catch (EOFException e) {
}
if (line == null) {
// Set our current entry to null (since it's done) and try again.
is = null;
return next(identifier, text);
}
text.set(line);
return true;
}
@Override
public RecordIdentifier createKey() {
return new RecordIdentifier();
}
@Override
public Text createValue() {
return new Text();
}
@Override
public long getPos() throws IOException {
return 0;
}
@Override
public void close() throws IOException {
}
@Override
public float getProgress() throws IOException {
return 0;
}
}
// This class isn't used and I suspect does totally the wrong thing. It's only here so that I
// can provide some output format to the tables and partitions I create. I actually write to
// those tables directory.
static class MockOutputFormat implements AcidOutputFormat<WritableComparable, Text> {
@Override
public RecordUpdater getRecordUpdater(Path path, Options options) throws
IOException {
return null;
}
@Override
public org.apache.hadoop.hive.ql.exec.FileSinkOperator.RecordWriter getRawRecordWriter(Path path, Options options) throws IOException {
return new MockRecordWriter(path, options);
}
@Override
public org.apache.hadoop.hive.ql.exec.FileSinkOperator.RecordWriter getHiveRecordWriter(JobConf jc, Path finalOutPath,
Class<? extends Writable> valueClass,
boolean isCompressed, Properties tableProperties,
Progressable progress) throws IOException {
return null;
}
@Override
public RecordWriter<WritableComparable, Text> getRecordWriter(FileSystem fileSystem, JobConf entries,
String s,
Progressable progressable) throws
IOException {
return null;
}
@Override
public void checkOutputSpecs(FileSystem fileSystem, JobConf entries) throws IOException {
}
}
// This class isn't used and I suspect does totally the wrong thing. It's only here so that I
// can provide some output format to the tables and partitions I create. I actually write to
// those tables directory.
static class MockRecordWriter implements org.apache.hadoop.hive.ql.exec.FileSinkOperator.RecordWriter {
private final FSDataOutputStream os;
MockRecordWriter(Path basedir, AcidOutputFormat.Options options) throws IOException {
FileSystem fs = FileSystem.get(options.getConfiguration());
Path p = AcidUtils.createFilename(basedir, options);
os = fs.create(p);
}
@Override
public void write(Writable w) throws IOException {
Text t = (Text)w;
os.writeBytes(t.toString());
os.writeBytes("\n");
}
@Override
public void close(boolean abort) throws IOException {
os.close();
}
}
/**
* in Hive 1.3.0 delta file names changed to delta_xxxx_yyyy_zzzz; prior to that
* the name was delta_xxxx_yyyy. We want to run compaction tests such that both formats
* are used since new (1.3) code has to be able to read old files.
*/
abstract boolean useHive130DeltaDirName();
String makeDeltaDirName(long minTxnId, long maxTxnId) {
if(minTxnId != maxTxnId) {
//covers both streaming api and post compaction style.
return makeDeltaDirNameCompacted(minTxnId, maxTxnId);
}
return useHive130DeltaDirName() ?
AcidUtils.deltaSubdir(minTxnId, maxTxnId, 0) : AcidUtils.deltaSubdir(minTxnId, maxTxnId);
}
/**
* delta dir name after compaction
*/
String makeDeltaDirNameCompacted(long minTxnId, long maxTxnId) {
return AcidUtils.deltaSubdir(minTxnId, maxTxnId);
}
String makeDeleteDeltaDirNameCompacted(long minTxnId, long maxTxnId) {
return AcidUtils.deleteDeltaSubdir(minTxnId, maxTxnId);
}
protected long compactInTxn(CompactionRequest rqst) throws Exception {
txnHandler.compact(rqst);
CompactionInfo ci = txnHandler.findNextToCompact("fred", WORKER_VERSION);
ci.runAs = System.getProperty("user.name");
long compactorTxnId = openTxn(TxnType.COMPACTION);
// Need to create a valid writeIdList to set the highestWriteId in ci
ValidTxnList validTxnList = TxnCommonUtils.createValidReadTxnList(txnHandler.getOpenTxns(), compactorTxnId);
GetValidWriteIdsRequest writeIdsRequest = new GetValidWriteIdsRequest();
writeIdsRequest.setValidTxnList(validTxnList.writeToString());
writeIdsRequest
.setFullTableNames(Collections.singletonList(TxnUtils.getFullTableName(rqst.getDbname(), rqst.getTablename())));
// with this ValidWriteIdList is capped at whatever HWM validTxnList has
ValidCompactorWriteIdList tblValidWriteIds = TxnUtils
.createValidCompactWriteIdList(txnHandler.getValidWriteIds(writeIdsRequest).getTblValidWriteIds().get(0));
ci.highestWriteId = tblValidWriteIds.getHighWatermark();
txnHandler.updateCompactorState(ci, compactorTxnId);
txnHandler.markCompacted(ci);
txnHandler.commitTxn(new CommitTxnRequest(compactorTxnId));
Thread.sleep(MetastoreConf.getTimeVar(conf, MetastoreConf.ConfVars.TXN_OPENTXN_TIMEOUT, TimeUnit.MILLISECONDS));
return compactorTxnId;
}
}
| jcamachor/hive | ql/src/test/org/apache/hadoop/hive/ql/txn/compactor/CompactorTest.java | Java | apache-2.0 | 26,009 |
'use strict';
var app = angular.module('app', [
'ngAnimate',
'ngCookies',
'ui.router',
'ui.bootstrap'
]);
app.config(['$stateProvider', '$httpProvider',
function ($stateProvider, $httpProvider) {
$stateProvider.state('home', {
url: '',
templateUrl: 'App/partials/home.html',
controller: 'HomeCtrl',
data: {
requireLogin: false
}
});
$stateProvider.state('play', {
url: '/play',
templateUrl: 'App/partials/play.html',
controller: 'PlayCtrl',
data: {
requireLogin: true
}
});
$stateProvider.state('match', {
url: '/match',
templateUrl: 'App/partials/match.html',
controller: 'MatchCtrl',
data: {
requireLogin: false
}
});
$stateProvider.state('team', {
url: '/team',
templateUrl: 'App/partials/team.html',
controller: 'TeamCtrl',
data: {
requireLogin: false
}
});
$stateProvider.state('player', {
url: '/player',
templateUrl: 'App/partials/player.html',
controller: 'PlayerCtrl',
data: {
requireLogin: false
}
});
$stateProvider.state('about', {
url: '/about',
templateUrl: 'App/partials/about.html',
data: {
requireLogin: false
}
});
$stateProvider.state('preferences', {
url: '/preferences',
templateUrl: 'App/partials/preferences.html',
controller: 'PreferencesCtrl',
data: {
requireLogin: true
}
});
$httpProvider.interceptors.push(function ($timeout, $q, $injector) {
var authModal, $http, $state;
// this trick must be done so that we don't receive
// `Uncaught Error: [$injector:cdep] Circular dependency found`
$timeout(function () {
authModal = $injector.get('authModal');
$http = $injector.get('$http');
$state = $injector.get('$state');
});
return {
responseError: function (rejection) {
return rejection;//may want to force modal on 401 auth failure, but not at this time
if (rejection.status !== 401) {
return rejection;
}
var deferred = $q.defer();
authModal()
.then(function () {
deferred.resolve($http(rejection.config));
})
.catch(function () {
$state.go('home');
deferred.reject(rejection);
});
return deferred.promise;
}
};
});
}
]);
app.run(['$rootScope', '$state', 'authModal', 'authService', 'versionService',
function ($rootScope, $state, authModal, authService, versionService) {
$rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
versionService.getVersionInfo(
function (version) {
if (version.isOutOfDate) {
$rootScope.$broadcast('alert', { type: 'warning', msg: 'Client version is out of date. Please refresh your browser.' });
}
},
function () {
$rootScope.$broadcast({ type: 'danger', msg: 'Server could not be reached. Please try again later.' });
});
if (toState.data.requireLogin && !authService.user.isAuthenticated) {
event.preventDefault();
authModal()
.then(function(data) {
return $state.go(toState.name, toParams);
})
.catch(function() {
return $state.go('home');
});
}
});
}]); | trentdm/Foos | src/Foos/App/app.js | JavaScript | apache-2.0 | 4,265 |
/*
* Copyright 2019 VMware, 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
*
* 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 io.micrometer.binder.jetty;
import io.micrometer.core.instrument.MockClock;
import io.micrometer.core.instrument.simple.SimpleConfig;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.client.util.StringContentProvider;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.util.component.LifeCycle;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import java.util.concurrent.CountDownLatch;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;
class JettyConnectionMetricsTest {
private SimpleMeterRegistry registry = new SimpleMeterRegistry(SimpleConfig.DEFAULT, new MockClock());
private Server server = new Server(0);
private ServerConnector connector = new ServerConnector(server);
private CloseableHttpClient client = HttpClients.createDefault();
void setup() throws Exception {
connector.addBean(new JettyConnectionMetrics(registry));
server.setConnectors(new Connector[]{connector});
server.start();
}
@AfterEach
void teardown() throws Exception {
if (server.isRunning()) {
server.stop();
}
}
@Test
void contributesServerConnectorMetrics() throws Exception {
setup();
HttpPost post = new HttpPost("http://localhost:" + connector.getLocalPort());
post.setEntity(new StringEntity("123456"));
try (CloseableHttpResponse ignored = client.execute(post)) {
try (CloseableHttpResponse ignored2 = client.execute(post)) {
assertThat(registry.get("jetty.connections.current").gauge().value()).isEqualTo(2.0);
assertThat(registry.get("jetty.connections.max").gauge().value()).isEqualTo(2.0);
}
}
CountDownLatch latch = new CountDownLatch(1);
connector.addLifeCycleListener(new LifeCycle.Listener() {
@Override
public void lifeCycleStopped(LifeCycle event) {
latch.countDown();
}
});
// Convenient way to get Jetty to flush its connections, which is required to update the sent/received bytes metrics
server.stop();
assertTrue(latch.await(10, SECONDS));
assertThat(registry.get("jetty.connections.max").gauge().value()).isEqualTo(2.0);
assertThat(registry.get("jetty.connections.request").tag("type", "server").timer().count())
.isEqualTo(2);
assertThat(registry.get("jetty.connections.bytes.in").summary().totalAmount()).isGreaterThan(1);
}
@Test
void contributesClientConnectorMetrics() throws Exception {
setup();
HttpClient httpClient = new HttpClient();
httpClient.setFollowRedirects(false);
httpClient.addBean(new JettyConnectionMetrics(registry));
CountDownLatch latch = new CountDownLatch(1);
httpClient.addLifeCycleListener(new LifeCycle.Listener() {
@Override
public void lifeCycleStopped(LifeCycle event) {
latch.countDown();
}
});
httpClient.start();
Request post = httpClient.POST("http://localhost:" + connector.getLocalPort());
post.content(new StringContentProvider("123456"));
post.send();
httpClient.stop();
assertTrue(latch.await(10, SECONDS));
assertThat(registry.get("jetty.connections.max").gauge().value()).isEqualTo(1.0);
assertThat(registry.get("jetty.connections.request").tag("type", "client").timer().count())
.isEqualTo(1);
assertThat(registry.get("jetty.connections.bytes.out").summary().totalAmount()).isGreaterThan(1);
}
@Test
void passingConnectorAddsConnectorNameTag() {
new JettyConnectionMetrics(registry, connector);
assertThat(registry.get("jetty.connections.messages.in").counter().getId().getTag("connector.name"))
.isEqualTo("unnamed");
}
@Test
void namedConnectorsGetTaggedWithName() {
connector.setName("super-fast-connector");
new JettyConnectionMetrics(registry, connector);
assertThat(registry.get("jetty.connections.messages.in").counter().getId().getTag("connector.name"))
.isEqualTo("super-fast-connector");
}
}
| micrometer-metrics/micrometer | micrometer-binders/src/test/java/io/micrometer/binder/jetty/JettyConnectionMetricsTest.java | Java | apache-2.0 | 5,449 |
/*
* Copyright 2016-present Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.store.resource.impl;
import org.onosproject.net.resource.DiscreteResource;
import org.onosproject.net.resource.DiscreteResourceId;
import java.util.List;
import java.util.Optional;
import java.util.Set;
interface DiscreteResources {
static DiscreteResources empty() {
return NonEncodableDiscreteResources.empty();
}
Optional<DiscreteResource> lookup(DiscreteResourceId id);
DiscreteResources difference(DiscreteResources other);
boolean isEmpty();
boolean containsAny(List<DiscreteResource> other);
// returns a new instance, not mutate the current instance
DiscreteResources add(DiscreteResources other);
// returns a new instance, not mutate the current instance
DiscreteResources remove(List<DiscreteResource> removed);
Set<DiscreteResource> values();
}
| lsinfo3/onos | core/store/dist/src/main/java/org/onosproject/store/resource/impl/DiscreteResources.java | Java | apache-2.0 | 1,461 |
package io.leopard.jdbc;
import io.leopard.jdbc.JdbcDaoSupport;
import java.sql.Connection;
import javax.sql.DataSource;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.jdbc.core.JdbcTemplate;
public class JdbcDaoSupportTest {
JdbcDaoSupport jdbcDao = new JdbcDaoSupport();
@Test
public void JdbcDaoSupport() {
}
@Test
public void setDataSource() {
DataSource dataSource = Mockito.mock(DataSource.class);
jdbcDao.setDataSource(dataSource);
Assert.assertNotNull(jdbcDao.getDataSource());
}
@Test
public void setJdbcTemplate() {
JdbcTemplate jdbcTemplate = Mockito.mock(JdbcTemplate.class);
jdbcDao.setJdbcTemplate(jdbcTemplate);
Assert.assertNotNull(jdbcDao.getJdbcTemplate());
jdbcDao.getExceptionTranslator();
}
@Test
public void getConnection() {
DataSource dataSource = Mockito.mock(DataSource.class);
jdbcDao.setDataSource(dataSource);
jdbcDao.getConnection();
}
@Test
public void releaseConnection() {
DataSource dataSource = Mockito.mock(DataSource.class);
jdbcDao.setDataSource(dataSource);
Connection conn = Mockito.mock(Connection.class);
jdbcDao.releaseConnection(conn);
}
} | tanhaichao/leopard-data | leopard-jdbc/src/test/java/io/leopard/jdbc/JdbcDaoSupportTest.java | Java | apache-2.0 | 1,196 |