repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
viewreka/viewreka
projects/viewreka-fxui/src/main/java/org/beryx/viewreka/fxui/settings/package-info.java
710
/** * Copyright 2015-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Provides support for GUI settings. */ package org.beryx.viewreka.fxui.settings;
apache-2.0
sigitm/musichub
src/main/java/it/musichub/server/ex/ServiceDestroyException.java
411
package it.musichub.server.ex; public class ServiceDestroyException extends MusicHubException { public ServiceDestroyException() { super(); } public ServiceDestroyException(String message) { super(message); } public ServiceDestroyException(Throwable cause) { super(cause); } public ServiceDestroyException(String message, Throwable cause) { super(message, cause); } }
apache-2.0
Shenker93/playframework
framework/src/play/src/main/scala/play/core/parsers/FormUrlEncodedParser.scala
3676
/* * Copyright (C) 2009-2018 Lightbend Inc. <https://www.lightbend.com> */ package play.core.parsers import java.net.URLDecoder /** An object for parsing application/x-www-form-urlencoded data */ object FormUrlEncodedParser { /** * Parse the content type "application/x-www-form-urlencoded" which consists of a bunch of & separated key=value * pairs, both of which are URL encoded. * @param data The body content of the request, or whatever needs to be so parsed * @param encoding The character encoding of data * @return A ListMap of keys to the sequence of values for that key */ def parseNotPreservingOrder(data: String, encoding: String = "utf-8"): Map[String, Seq[String]] = { // Generate the pairs of values from the string. parseToPairs(data, encoding).groupBy(_._1). map(param => param._1 -> param._2.map(_._2))(scala.collection.breakOut) } /** * Parse the content type "application/x-www-form-urlencoded" which consists of a bunch of & separated key=value * pairs, both of which are URL encoded. We are careful in this parser to maintain the original order of the * keys by using OrderPreserving.groupBy as some applications depend on the original browser ordering. * @param data The body content of the request, or whatever needs to be so parsed * @param encoding The character encoding of data * @return A ListMap of keys to the sequence of values for that key */ def parse(data: String, encoding: String = "utf-8"): Map[String, Seq[String]] = { // Generate the pairs of values from the string. val pairs: Seq[(String, String)] = parseToPairs(data, encoding) // Group the pairs by the key (first item of the pair) being sure to preserve insertion order play.utils.OrderPreserving.groupBy(pairs)(_._1) } /** * Parse the content type "application/x-www-form-urlencoded", mapping to a Java compatible format. * @param data The body content of the request, or whatever needs to be so parsed * @param encoding The character encoding of data * @return A Map of keys to the sequence of values for that key */ def parseAsJava(data: String, encoding: String): java.util.Map[String, java.util.List[String]] = { import scala.collection.JavaConverters._ parse(data, encoding).map { case (key, values) => key -> values.asJava }.asJava } /** * Parse the content type "application/x-www-form-urlencoded", mapping to a Java compatible format. * @param data The body content of the request, or whatever needs to be so parsed * @param encoding The character encoding of data * @return A Map of keys to the sequence of array values for that key */ def parseAsJavaArrayValues(data: String, encoding: String): java.util.Map[String, Array[String]] = { import scala.collection.JavaConverters._ parse(data, encoding).map { case (key, values) => key -> values.toArray }.asJava } private[this] val parameterDelimiter = "[&;]".r /** * Do the basic parsing into a sequence of key/value pairs * @param data The data to parse * @param encoding The encoding to use for interpreting the data * @return The sequence of key/value pairs */ private def parseToPairs(data: String, encoding: String): Seq[(String, String)] = { val split = parameterDelimiter.split(data) if (split.length == 1 && split(0).isEmpty) { Seq.empty } else { split.map { param => val parts = param.split("=", -1) val key = URLDecoder.decode(parts(0), encoding) val value = URLDecoder.decode(parts.lift(1).getOrElse(""), encoding) key -> value } } } }
apache-2.0
NunoGodinho/test
TestApi/TestApi/Areas/HelpPage/Controllers/HelpController.cs
1209
using System; using System.Web.Http; using System.Web.Mvc; using TestApi.Areas.HelpPage.Models; namespace TestApi.Areas.HelpPage.Controllers { /// <summary> /// The controller that will handle requests for the help page. /// </summary> public class HelpController : Controller { public HelpController() : this(GlobalConfiguration.Configuration) { } public HelpController(HttpConfiguration config) { Configuration = config; } public HttpConfiguration Configuration { get; private set; } public ActionResult Index() { ViewBag.DocumentationProvider = Configuration.Services.GetDocumentationProvider(); return View(Configuration.Services.GetApiExplorer().ApiDescriptions); } public ActionResult Api(string apiId) { if (!String.IsNullOrEmpty(apiId)) { HelpPageApiModel apiModel = Configuration.GetHelpPageApiModel(apiId); if (apiModel != null) { return View(apiModel); } } return View("Error"); } } }
apache-2.0
mutsinghua/DownloadSDK
app/src/main/java/com/tcl/mie/downloader/core/TaskThread.java
2670
package com.tcl.mie.downloader.core; import com.tcl.mie.downloader.DownloadException; import com.tcl.mie.downloader.DownloadStatus; import com.tcl.mie.downloader.DownloadTask; import java.util.concurrent.BlockingQueue; /** * 下载线程 * Created by difei.zou on 2015/6/13. */ public class TaskThread extends Thread { private BlockingQueue<DownloadTask> mWaitTasks; private INetworkDownloader mNetworkDownloader; public volatile boolean mCancel = false; public TaskThread(BlockingQueue<DownloadTask> waitTasks, INetworkDownloader networkDownloader) { super("TaskThread" + System.nanoTime()); this.mWaitTasks = waitTasks; this.mNetworkDownloader = networkDownloader; } @Override public void run() { while(!mCancel) { try { DownloadTask task = mWaitTasks.take(); if( mCancel) { break; } if (task != null) { try { task.getDownloader().onTaskGoing(task); mNetworkDownloader.download(task); } catch (DownloadException e) { e.printStackTrace(); if (e.mErrorCode == e.ECODE_PAUSE) { if (task.mPriority == DownloadTask.PRORITY_LOW) { //自动下载的。重新加入 task.getDownloader().startDownloadInLow(task); } task.mStatus = DownloadStatus.STOP; task.getDownloader().getEventCenter().onDownloadStatusChange(task); continue; } else if (e.mErrorCode == e.ECODE_NETWORK) { //如果是网络下载失败的,缓存到任务队列中,等有网络的时候再继续下载 task.getDownloader().retry(task); } task.mStatus = DownloadStatus.ERROR; task.getDownloader().getEventCenter().onDownloadStatusChange(task); } catch (Throwable e) { e.printStackTrace(); task.mStatus = DownloadStatus.ERROR; task.getDownloader().getEventCenter().onDownloadStatusChange(task); } finally { task.getDownloader().onTaskStop(task); } } } catch (Throwable e) { e.printStackTrace(); } } } }
apache-2.0
exomodal/insight
client/components/single_graphs/single_graphs.js
6030
// Variable declarations var SINGLEGRAPH_FORM; var SINGLEGRAPH_IGNORE_TAGS; var START_MONTH = 1; var START_YEAR = 2008; /***************************************************************************** * General function *****************************************************************************/ function setVariables(parent) { // Check if the data is available if (parent.data && parent.data.form && parent.data.ignore) { SINGLEGRAPH_FORM = parent.data.form; SINGLEGRAPH_IGNORE_TAGS = parent.data.ignore; // If the data is not available we throw an error } else { SINGLEGRAPH_FORM = undefined; SINGLEGRAPH_IGNORE_TAGS = undefined; throwError("The graphs are not correctly initialized! Please contact the administrator."); } } /***************************************************************************** * General Template function *****************************************************************************/ /* * This function will initialize the default variables * which should be located in the 'this.data' variable. */ Template.singleGraphs.initialize = function() { setVariables(this); } /* * Get the list of locations */ Template.singleGraphs.location = function () { return config_locations(); } /* * Returns whether the form is location bound. * If so the location field should be added. */ Template.singleGraphs.isLocationBound = function () { return form_isLocationBound(SINGLEGRAPH_FORM); } /* * Returns whether the user does have a location */ Template.singleGraphs.isLocalUser = function () { return user_isLocal(); } /* * Get the user location */ Template.singleGraphs.userlocation = function () { return user_location(); } /***************************************************************************** * General function *****************************************************************************/ /* * This function calculates the amount of months between * two given timestamps. */ function monthDifference(d1, d2) { var months; months = (moment(d2).year() - moment(d1).year()) * 12; months -= moment(d1).month(); months += moment(d2).month() + 1; return months <= 0 ? 0 : months; } /* * Convert timestamp into year */ function toYear(timestamp) { if (timestamp && timestamp !== 0) return moment.unix(timestamp/1000).year(); return ""; } /* * Convert timestamp into month */ function toMonth(timestamp) { if (timestamp && timestamp !== 0) return GLOBAL_MONTHS[moment.unix(timestamp/1000).month()]; return ""; } /* * Convert timestamp into month */ function toMonthNumber(timestamp) { if (timestamp && timestamp !== 0) return moment.unix(timestamp/1000).month() + 1; return ""; } /* * This function build the datasets. */ function buildSeries(tags, line_data) { var datasets = new Array(); // Build the datasets for line and bar graphs for (var i=0;i<tags.length;i++) { if (SINGLEGRAPH_IGNORE_TAGS.indexOf(tags[i]) === -1) { datasets.push( { name:tags[i], data:line_data[tags[i]], tooltip:{valueDecimals:2}, }); } } return datasets; } /* * This function handles the complete constuction and displaying of the charts. */ function renderGraph() { // Initialize arrays var line_data = new Object(); var tags = form_tags(SINGLEGRAPH_FORM); for (var i=0;i<tags.length;i++) { if (SINGLEGRAPH_IGNORE_TAGS.indexOf(tags[i]) === -1) { line_data[tags[i]] = new Array(); } } // Calculate timestamps var start_timestamp = Number(moment(START_MONTH+"-"+START_YEAR, "MM-YYYY").unix() * 1000); var end_timestamp = Number(moment()); // Parse each month var month_count = monthDifference(start_timestamp, end_timestamp); var month = Number(START_MONTH); var year = Number(START_YEAR); for (var i=0;i<month_count;i++) { // Append data var ts1 = Number(moment(month+"-"+year, "MM-YYYY").unix() * 1000); var ts2 = Number(moment((month+1)+"-"+year, "MM-YYYY").unix() * 1000); if (form_isLocationBound(SINGLEGRAPH_FORM)) { var loc = document.getElementById('static_location').value; if (loc !== "") { var doc = collection_findOne(form_name(SINGLEGRAPH_FORM), {location:Number(loc), timestamp:{$gt:ts1,$lt:ts2}}); } } else { var doc = collection_findOne(form_name(SINGLEGRAPH_FORM), {timestamp:{$gt:ts1,$lt:ts2}}); } for (var j=0;j<tags.length;j++) { if (SINGLEGRAPH_IGNORE_TAGS.indexOf(tags[j]) === -1) { if (doc && doc[tags[j]]) { line_data[tags[j]].push([ts1 + 86400000, Number(doc[tags[j]])]); } else { line_data[tags[j]].push([ts1 + 86400000, 0]); } } } // update the counter month++; if (month > GLOBAL_MONTHS.length) { month = 1; year++; } } // Now we have all data and labels so we can display the chart $('.chartContainer2').highcharts('StockChart', { rangeSelector: {selected:4,inputDateFormat:'%b %Y',inputEditDateFormat:'%b %Y'}, xAxis:{gridLineWidth:1,type:'datetime',tickInterval:30*24*3600000,labels:{formatter:function() {return Highcharts.dateFormat("%b %Y", this.value);}}}, title: {text:''}, legend: {enabled:true}, chart: {type: 'spline'}, tooltip: { headerFormat: '<span style="font-size:10px">{point.key}</span><table>', pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' + '<td style="padding:0"><b>{point.y:.1f} EUR</b></td></tr>', footerFormat: '</table>', shared: true, useHTML: true }, series:buildSeries(tags, line_data) }); } /***************************************************************************** * Template rendered function *****************************************************************************/ Template.singleGraphs.rendered = function () { setVariables(this.data); renderGraph(); $('#static_location').on('change', function() { renderGraph(); }); }
apache-2.0
Ensembl/ensj-healthcheck
src/org/ensembl/healthcheck/DatabaseRegistryEntry.java
19485
/* * Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute * Copyright [2016-2019] EMBL-European Bioinformatics Institute * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright (C) 2003 EBI, GRL * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.ensembl.healthcheck; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.List; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ReflectionToStringBuilder; import org.ensembl.healthcheck.util.CollectionUtils; import org.ensembl.healthcheck.util.ConnectionBasedSqlTemplateImpl; import org.ensembl.healthcheck.util.ConnectionPool; import org.ensembl.healthcheck.util.DBUtils; import org.ensembl.healthcheck.util.RowMapper; import org.ensembl.healthcheck.util.SqlTemplate; import org.ensembl.healthcheck.util.SqlUncheckedException; import org.ensembl.healthcheck.util.UtilUncheckedException; /** * Container for information about a database that can be stored in a * DatabaseRegistry. */ public class DatabaseRegistryEntry implements Comparable<DatabaseRegistryEntry> { public final static String UNKNOWN = "unknown"; public final static String ANCESTRAL_SEQUENCES = "ancestral"; @Deprecated public final static String HOMO_SAPIENS = "homo_sapiens"; @Deprecated public static final String PAN_TROGLODYTES = "pan_troglodytes"; @Deprecated public static final String MUS_MUSCULUS = "mus_musculus"; @Deprecated public static final String EQUUS_CABALLUS = "equus_caballus"; @Deprecated public static final String BOS_TAURUS = "bos_taurus"; @Deprecated public static final String PONGO_ABELII = "pongo_abelii"; @Deprecated public static final String ORNITHORHYNCHUS_ANATINUS = "ornithorhynchus_anatinus"; @Deprecated public static final String TETRAODON_NIGROVIRIDIS = "tetraodon_nigroviridis"; @Deprecated public static final String MACACA_MULATTA = "macaca_mulatta"; @Deprecated public static final String DANIO_RERIO = "danio_rerio"; @Deprecated public static final String OVIS_ARIES = "ovis_aries"; @Deprecated public static final String ANOPHELES_GAMBIAE = "anopheles_gambiae"; @Deprecated public static final String RATTUS_NORVEGICUS = "rattus_norvegicus"; @Deprecated public static final String GALLUS_GALLUS = "gallus_gallus"; @Deprecated public static final String CANIS_FAMILIARIS = "canis_familiaris"; @Deprecated public static final String SUS_SCROFA = "sus_scrofa"; @Deprecated public static final String DROSOPHILA_MELANOGASTER = "drosophila_melangaster"; @Deprecated public static final String ORYZIAS_LATIPES = "oryzias_latipes"; @Deprecated public static final String CAENORHABDITIS_ELEGANS = "caenorhabditis_elegans"; @Deprecated public static final String SACCHAROMYCES_CEREVISIAE = "saccharomyces_cerevisae"; @Deprecated public static final String CIONA_INTESTINALIS = "ciona_intestinalis"; @Deprecated public static final String CIONA_SAVIGNYI = "ciona_savignyi"; private static final String COLLECTION_CLAUSE = "_collection"; private static Pattern p = Pattern.compile("([a-z])[a-z]+_([a-z][a-z]).+"); public static String getStableIDPrefixForSpecies(String species) { Matcher m = p.matcher(species); if(m.matches()) { return "ENS"+m.group(1).toUpperCase()+m.group(2).toUpperCase(); } else { return null; } } /** * Simple read-only bean to store pertinent information about a database. * Objects of this type are held by the {@link DatabaseRegistryEntry} and * attached to {@link ReportLine} objects to improve reporting * @author dstaines */ public static class DatabaseInfo { private final String name; private final String alias; private final String species; private final DatabaseType type; private final String schemaVersion; private final String genebuildVersion; /** * Constructor to set up key properties of {@link DatabaseInfo} * * @param name * @param species * @param type * @param schemaVersion */ public DatabaseInfo(String name, String alias, String species, DatabaseType type, String schemaVersion, String genebuildVersion) { this.name = name; this.alias = alias; this.species = species; this.type = type; this.schemaVersion = schemaVersion; this.genebuildVersion = genebuildVersion; } public String getName() { return name; } public String getAlias() { return alias; } public String getSpecies() { return species; } public DatabaseType getType() { return type; } public String getSchemaVersion() { return schemaVersion; } public String getGenebuildVersion() { return genebuildVersion; } public String toString() { return ReflectionToStringBuilder.toString(this); } } // e.g. username_species_type protected final static Pattern GB_DB = Pattern .compile("^[a-z0-9]+_([_A-Za-z]+)_(core|otherfeatures|rnaseq|cdna)_([0-9]+)"); // e.g. neurospora_crassa_core_4_56_1a protected final static Pattern EG_DB = Pattern .compile("^([a-zA-Z0-9_]+)_([a-z]+)_([0-9]+_[0-9]+)_([0-9A-Za-z]+)"); // e.g. homo_sapiens_core_56_37a protected final static Pattern E_DB = Pattern .compile("^([a-z]+_[a-z0-9]+(?:_[a-z0-9]+)?)_([a-z]+)_([0-9]+)_([0-9A-Za-z]+)"); // e.g. prefix_homo_sapiens_funcgen_60_37e protected final static Pattern PE_DB = Pattern .compile("^[^_]+_([^_]+_[^_]+)_([a-z]+)_([0-9]+)_([0-9A-Za-z]+)"); // human_core_20, hsapiens_XXX protected final static Pattern EEL_DB = Pattern .compile("^([^_]+)_([a-z]+)_([0-9]+)"); // ensembl_compara_bacteria_3_56 protected final static Pattern EGC_DB = Pattern .compile("^(ensembl)_(compara)_[a-z_]+_[0-9]+_([0-9]+)"); // ensembl_compara_56 protected final static Pattern EC_DB = Pattern .compile("^(ensembl)_(compara)_([0-9]+)"); // username_ensembl_compara_57 protected final static Pattern UC_DB = Pattern .compile("^[^_]+_(ensembl)_(compara)_([0-9]+)"); // username_ensembl_compara_master protected final static Pattern UCM_DB = Pattern .compile("^[^_]+_(ensembl)_(compara)_master"); // ensembl_ancestral_57 protected final static Pattern EA_DB = Pattern .compile("^(ensembl)_(ancestral)_([0-9]+)"); // username_ensembl_ancestral_57 protected final static Pattern UA_DB = Pattern .compile("^[^_]+_(ensembl)_(ancestral)_([0-9]+)"); // ensembl_mart_56 protected final static Pattern EM_DB = Pattern .compile("^([a-z_]+)_(mart)_([0-9])+"); // username_species_type_version_release protected final static Pattern V_DB = Pattern .compile("vega_([^_]+_[^_]+)_[^_]+_([^_]+)_([^_]+)"); protected final static Pattern EE_DB = Pattern .compile("^([^_]+_[^_]+)_[a-z]+_([a-z]+)_[a-z]+_([0-9]+)_([0-9A-Za-z]+)"); // username_species_type_version_release protected final static Pattern U_DB = Pattern .compile("^[^_]+_([^_]+_[^_]+)_([a-z]+)_([0-9]+)_([0-9A-Za-z]+)"); protected final static Pattern HELP_DB = Pattern .compile("^(ensembl)_(help)_([0-9]+)"); protected final static Pattern EW_DB = Pattern .compile("^(ensembl)_(website)_([0-9]+)"); protected final static Pattern TAX_DB = Pattern .compile("^(ncbi)_(taxonomy)_([0-9]+)"); protected final static Pattern UD_DB = Pattern .compile("^([a-z_]+)_(userdata)"); protected final static Pattern BLAST_DB = Pattern .compile("^([a-z_]+)_(blast)"); protected final static Pattern MASTER_DB = Pattern .compile("^(master_schema)_([a-z]+)?_([0-9]+)"); protected final static Pattern MYSQL_DB = Pattern .compile("^(mysql|information_schema)"); protected final static Pattern[] patterns = { EC_DB, UA_DB, UC_DB, UCM_DB, EA_DB, EGC_DB, EG_DB, E_DB, PE_DB, EM_DB, EE_DB, EEL_DB, U_DB, V_DB, MYSQL_DB, BLAST_DB, UD_DB, TAX_DB, EW_DB, HELP_DB, GB_DB, MASTER_DB }; /** * Utility for building a {@link DatabaseInfo} object given a name * * @param name * @return object containing information about a database */ public static DatabaseInfo getInfoFromName(String name) { return getInfoFromName(name, null, null); } /** * <p> * Returns information about a database. Queries the meta table to determine * the type and schema version of the database. * </p> * * @param server * @param name * @return DatabaseInfo */ public static DatabaseInfo getInfoFromDatabase(DatabaseServer server, final String name) throws SQLException { SqlTemplate template = null; try { template = new ConnectionBasedSqlTemplateImpl( server.getDatabaseConnection(name)); } catch (NullPointerException e) { // This exception can be thrown, if a database name has hashes in // it like this one: // // #mysql50#jhv_gadus_morhua_57_merged_projection_build.bak // or // #mysql50#jhv_gadus_morhua_57_ref_1.3_asm_buggy // // A database like this can exist on a MySql server, but // connecting to it will cause a NullPointerException to be // thrown. // logger.warning("Unable to connect to " + name + " on " + server); // No info will be available for this database. // return null; } DatabaseInfo info = null; boolean dbHasAMetaTable = template.queryForDefaultObjectList( "show tables like 'meta'", String.class).size() == 1; if (dbHasAMetaTable) { try { List<DatabaseInfo> dbInfos = template .queryForList( // Will return something like ("core", 63) // "select m1.meta_value, m2.meta_value from meta m1 join meta m2 where m1.meta_key='schema_type' and m2.meta_key='schema_version'", new RowMapper<DatabaseInfo>() { public DatabaseInfo mapRow( ResultSet resultSet, int position) throws SQLException { String schemaType = resultSet .getString(1); String schemaVersion = resultSet .getString(2); return new DatabaseInfo( name, null, UNKNOWN, DatabaseType .resolveAlias(schemaType), schemaVersion, null); } }); info = CollectionUtils.getFirstElement(dbInfos, info); } catch (SqlUncheckedException e) { logger.warning("Can't determine database type and version from " + name + " on " + server+": "+e.getMessage()); // No info will be available for this database. // return null; } finally { } } return info; } /** * Utility for building a {@link DatabaseInfo} object given a name plus * optional {@link Species} and {@link DatabaseType} to use explicitly * * @param name * @param species * (optional) * @param type * (optional) * @return object containing information about a database */ public static DatabaseInfo getInfoFromName(String name, String species, DatabaseType type) { String schemaVersion = null; String genebuildVersion = null; String alias = null; String typeStr = null; Matcher m; for (Pattern p : patterns) { m = p.matcher(name); if (m.matches()) { // group 1 = alias alias = m.group(1); if (m.groupCount() > 1) { // group 2 = type typeStr = m.group(2); if (m.groupCount() > 2) { // group 3 = schema_version schemaVersion = m.group(3); if (m.groupCount() > 3) { // group 4 = gb_version genebuildVersion = m.group(4); } } } if (alias.endsWith(COLLECTION_CLAUSE)) { alias = alias.replaceAll(COLLECTION_CLAUSE, StringUtils.EMPTY); } break; } } if (species == null) { if (!StringUtils.isEmpty(alias)) { species = alias; } else { species = UNKNOWN; } } if (type == null) { if (!StringUtils.isEmpty(typeStr)) { type = DatabaseType.resolveAlias(typeStr); if (typeStr.equals("ancestral") && species.equals("ensembl")) { species = ANCESTRAL_SEQUENCES; } } else { type = DatabaseType.UNKNOWN; } } return new DatabaseInfo(name, alias, species, type, schemaVersion, genebuildVersion); } private final DatabaseInfo info; private List<Integer> speciesIds; private final DatabaseServer server; private DatabaseRegistry databaseRegistry; private Connection connection; /** The logger to use */ private static Logger logger = Logger.getLogger("HealthCheckLogger"); // ----------------------------------------------------------------- /** * Create a new DatabaseRegistryEntry. * * @param server * The database server where this database resides. * @param name * The name of the database. * @param species * The species that this database represents. If null, derive it * from name. * @param type * The type of this database. If null, derive it from name. */ public DatabaseRegistryEntry(DatabaseServer server, String name, String species, DatabaseType type) { this.server = server; DatabaseInfo info = getInfoFromName(name, species, type); if (info.getType() == DatabaseType.UNKNOWN) { // try and get the info from the database DatabaseInfo dbInfo = null; try { dbInfo = getInfoFromDatabase(server, name); } catch (SQLException e) { logger.warning(e.getMessage()); } if (dbInfo != null) { info = dbInfo; } } this.info = info; } public DatabaseRegistryEntry(DatabaseInfo info, Connection con) { this.info = info; this.server = null; this.connection = con; } // ----------------------------------------------------------------- /** * @return Database name. */ public final String getName() { return info.getName(); } /** * @return Species. */ public final String getSpecies() { return info.getSpecies(); } /** * @return Database type (core, est etc) */ public final DatabaseType getType() { return info.getType(); } // ----------------------------------------------------------------- /** * Compares two databases by comparing the names of the species. If they are * the same, then the schema version is used as a secondary sorting * criterion. * * The schema version is converted to an integer so there is numerical * sorting on the schema version. Otherwise 9 would come after 10. * * This is important, because the comparing is used in * ComparePreviousVersionBase from which all the ComparePreviousVersion* * inherit. */ public int compareTo(DatabaseRegistryEntry dbre) { int speciesOrdering = getSpecies().compareTo(dbre.getSpecies()); if (speciesOrdering != 0) { return speciesOrdering; } String sv = getSchemaVersion().replaceAll("[0-9]+_",""); String sv2 = dbre .getSchemaVersion().replaceAll("[0-9]+_",""); return new Integer(sv).compareTo(new Integer(sv2)); // return getName().compareTo(dbre.getName()); } public String getSchemaVersion() { return info.getSchemaVersion(); } public String getGeneBuildVersion() { return info.getGenebuildVersion(); } // ----------------------------------------------------------------- // Return the numeric genebuild version, or -1 if this cannot be deduced // (e.g. from a non-standard database name) public int getNumericGeneBuildVersion() { if (getGeneBuildVersion() == null) { return -1; } String[] bits = getGeneBuildVersion().split("[a-zA-Z]"); return Integer.parseInt(bits[0]); } public DatabaseRegistry getDatabaseRegistry() { return databaseRegistry; } public void setDatabaseRegistry(DatabaseRegistry databaseRegistry) { this.databaseRegistry = databaseRegistry; } /** * Check if the database has multiple species * * @return true if the database contains more than one species */ public boolean isMultiSpecies() { return this.getName().matches(".*_collection_.*"); } /** * Utility method to determine list of species IDs found within a core * database * * @param con * @param species * @param type * @return list of numeric IDs */ public static List<Integer> getSpeciesIds(Connection con, String species, DatabaseType type) { List<Integer> speciesId = CollectionUtils.createArrayList(); // only generic databases have a coord_system table if (type == null || !type.isGeneric()) { return speciesId; } Statement stmt = null; ResultSet rs = null; try { stmt = con.createStatement(); rs = stmt .executeQuery("SELECT DISTINCT(species_id) FROM meta where species_id is not null"); if (rs != null) { while (rs.next()) { speciesId.add(rs.getInt(1)); } } } catch (SQLException e) { throw new UtilUncheckedException( "Problem obtaining list of species IDs", e); } finally { DBUtils.closeQuietly(rs); DBUtils.closeQuietly(stmt); } return speciesId; } /** * @return information about the server that this database is found on */ public DatabaseServer getDatabaseServer() { return server; } public Connection getConnection() { if ( (connection == null) || !(ConnectionPool.isValidConnection(connection)) ) { try { connection = server.getDatabaseConnection(getName()); } catch (SQLException e) { logger.warning(e.getMessage()); } } return connection; } /** * Test if this entry is equal to another. Comparison is currently only on * database name. * * @param dbre * @return true if names are the same. */ public boolean equals(DatabaseRegistryEntry dbre) { return (dbre.getName().equals(getName())); } public boolean equals(Object o) { if (o == null) { return false; } return (((DatabaseRegistryEntry) o).getName().equals(getName())); } public String getAlias() { return info.getAlias(); } /** * Utility method to determine list of species IDs found within the attached * database * * @return list of numeric IDs */ public List<Integer> getSpeciesIds() { if (speciesIds == null) { speciesIds = getSpeciesIds(getConnection(), getSpecies(), getType()); } return speciesIds; } public String toString() { return getName(); } // ----------------------------------------------------------------- } // DatabaseRegistryEntry
apache-2.0
googleapis/google-cloud-go
vision/apiv1/image_annotator_client.go
23205
// 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. // Code generated by protoc-gen-go_gapic. DO NOT EDIT. package vision import ( "context" "fmt" "math" "net/url" "time" "cloud.google.com/go/longrunning" lroauto "cloud.google.com/go/longrunning/autogen" gax "github.com/googleapis/gax-go/v2" "google.golang.org/api/option" "google.golang.org/api/option/internaloption" gtransport "google.golang.org/api/transport/grpc" visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1" longrunningpb "google.golang.org/genproto/googleapis/longrunning" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" ) var newImageAnnotatorClientHook clientHook // ImageAnnotatorCallOptions contains the retry settings for each method of ImageAnnotatorClient. type ImageAnnotatorCallOptions struct { BatchAnnotateImages []gax.CallOption BatchAnnotateFiles []gax.CallOption AsyncBatchAnnotateImages []gax.CallOption AsyncBatchAnnotateFiles []gax.CallOption } func defaultImageAnnotatorGRPCClientOptions() []option.ClientOption { return []option.ClientOption{ internaloption.WithDefaultEndpoint("vision.googleapis.com:443"), internaloption.WithDefaultMTLSEndpoint("vision.mtls.googleapis.com:443"), internaloption.WithDefaultAudience("https://vision.googleapis.com/"), internaloption.WithDefaultScopes(DefaultAuthScopes()...), internaloption.EnableJwtWithScope(), option.WithGRPCDialOption(grpc.WithDefaultCallOptions( grpc.MaxCallRecvMsgSize(math.MaxInt32))), } } func defaultImageAnnotatorCallOptions() *ImageAnnotatorCallOptions { return &ImageAnnotatorCallOptions{ BatchAnnotateImages: []gax.CallOption{ gax.WithRetry(func() gax.Retryer { return gax.OnCodes([]codes.Code{ codes.DeadlineExceeded, codes.Unavailable, }, gax.Backoff{ Initial: 100 * time.Millisecond, Max: 60000 * time.Millisecond, Multiplier: 1.30, }) }), }, BatchAnnotateFiles: []gax.CallOption{ gax.WithRetry(func() gax.Retryer { return gax.OnCodes([]codes.Code{ codes.DeadlineExceeded, codes.Unavailable, }, gax.Backoff{ Initial: 100 * time.Millisecond, Max: 60000 * time.Millisecond, Multiplier: 1.30, }) }), }, AsyncBatchAnnotateImages: []gax.CallOption{ gax.WithRetry(func() gax.Retryer { return gax.OnCodes([]codes.Code{ codes.DeadlineExceeded, codes.Unavailable, }, gax.Backoff{ Initial: 100 * time.Millisecond, Max: 60000 * time.Millisecond, Multiplier: 1.30, }) }), }, AsyncBatchAnnotateFiles: []gax.CallOption{ gax.WithRetry(func() gax.Retryer { return gax.OnCodes([]codes.Code{ codes.DeadlineExceeded, codes.Unavailable, }, gax.Backoff{ Initial: 100 * time.Millisecond, Max: 60000 * time.Millisecond, Multiplier: 1.30, }) }), }, } } // internalImageAnnotatorClient is an interface that defines the methods availaible from Cloud Vision API. type internalImageAnnotatorClient interface { Close() error setGoogleClientInfo(...string) Connection() *grpc.ClientConn BatchAnnotateImages(context.Context, *visionpb.BatchAnnotateImagesRequest, ...gax.CallOption) (*visionpb.BatchAnnotateImagesResponse, error) BatchAnnotateFiles(context.Context, *visionpb.BatchAnnotateFilesRequest, ...gax.CallOption) (*visionpb.BatchAnnotateFilesResponse, error) AsyncBatchAnnotateImages(context.Context, *visionpb.AsyncBatchAnnotateImagesRequest, ...gax.CallOption) (*AsyncBatchAnnotateImagesOperation, error) AsyncBatchAnnotateImagesOperation(name string) *AsyncBatchAnnotateImagesOperation AsyncBatchAnnotateFiles(context.Context, *visionpb.AsyncBatchAnnotateFilesRequest, ...gax.CallOption) (*AsyncBatchAnnotateFilesOperation, error) AsyncBatchAnnotateFilesOperation(name string) *AsyncBatchAnnotateFilesOperation } // ImageAnnotatorClient is a client for interacting with Cloud Vision API. // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. // // Service that performs Google Cloud Vision API detection tasks over client // images, such as face, landmark, logo, label, and text detection. The // ImageAnnotator service returns detected entities from the images. type ImageAnnotatorClient struct { // The internal transport-dependent client. internalClient internalImageAnnotatorClient // The call options for this service. CallOptions *ImageAnnotatorCallOptions // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. LROClient *lroauto.OperationsClient } // Wrapper methods routed to the internal client. // Close closes the connection to the API service. The user should invoke this when // the client is no longer required. func (c *ImageAnnotatorClient) Close() error { return c.internalClient.Close() } // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. func (c *ImageAnnotatorClient) setGoogleClientInfo(keyval ...string) { c.internalClient.setGoogleClientInfo(keyval...) } // Connection returns a connection to the API service. // // Deprecated. func (c *ImageAnnotatorClient) Connection() *grpc.ClientConn { return c.internalClient.Connection() } // BatchAnnotateImages run image detection and annotation for a batch of images. func (c *ImageAnnotatorClient) BatchAnnotateImages(ctx context.Context, req *visionpb.BatchAnnotateImagesRequest, opts ...gax.CallOption) (*visionpb.BatchAnnotateImagesResponse, error) { return c.internalClient.BatchAnnotateImages(ctx, req, opts...) } // BatchAnnotateFiles service that performs image detection and annotation for a batch of files. // Now only “application/pdf”, “image/tiff” and “image/gif” are supported. // // This service will extract at most 5 (customers can specify which 5 in // AnnotateFileRequest.pages) frames (gif) or pages (pdf or tiff) from each // file provided and perform detection and annotation for each image // extracted. func (c *ImageAnnotatorClient) BatchAnnotateFiles(ctx context.Context, req *visionpb.BatchAnnotateFilesRequest, opts ...gax.CallOption) (*visionpb.BatchAnnotateFilesResponse, error) { return c.internalClient.BatchAnnotateFiles(ctx, req, opts...) } // AsyncBatchAnnotateImages run asynchronous image detection and annotation for a list of images. // // Progress and results can be retrieved through the // google.longrunning.Operations interface. // Operation.metadata contains OperationMetadata (metadata). // Operation.response contains AsyncBatchAnnotateImagesResponse (results). // // This service will write image annotation outputs to json files in customer // GCS bucket, each json file containing BatchAnnotateImagesResponse proto. func (c *ImageAnnotatorClient) AsyncBatchAnnotateImages(ctx context.Context, req *visionpb.AsyncBatchAnnotateImagesRequest, opts ...gax.CallOption) (*AsyncBatchAnnotateImagesOperation, error) { return c.internalClient.AsyncBatchAnnotateImages(ctx, req, opts...) } // AsyncBatchAnnotateImagesOperation returns a new AsyncBatchAnnotateImagesOperation from a given name. // The name must be that of a previously created AsyncBatchAnnotateImagesOperation, possibly from a different process. func (c *ImageAnnotatorClient) AsyncBatchAnnotateImagesOperation(name string) *AsyncBatchAnnotateImagesOperation { return c.internalClient.AsyncBatchAnnotateImagesOperation(name) } // AsyncBatchAnnotateFiles run asynchronous image detection and annotation for a list of generic // files, such as PDF files, which may contain multiple pages and multiple // images per page. Progress and results can be retrieved through the // google.longrunning.Operations interface. // Operation.metadata contains OperationMetadata (metadata). // Operation.response contains AsyncBatchAnnotateFilesResponse (results). func (c *ImageAnnotatorClient) AsyncBatchAnnotateFiles(ctx context.Context, req *visionpb.AsyncBatchAnnotateFilesRequest, opts ...gax.CallOption) (*AsyncBatchAnnotateFilesOperation, error) { return c.internalClient.AsyncBatchAnnotateFiles(ctx, req, opts...) } // AsyncBatchAnnotateFilesOperation returns a new AsyncBatchAnnotateFilesOperation from a given name. // The name must be that of a previously created AsyncBatchAnnotateFilesOperation, possibly from a different process. func (c *ImageAnnotatorClient) AsyncBatchAnnotateFilesOperation(name string) *AsyncBatchAnnotateFilesOperation { return c.internalClient.AsyncBatchAnnotateFilesOperation(name) } // imageAnnotatorGRPCClient is a client for interacting with Cloud Vision API over gRPC transport. // // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. type imageAnnotatorGRPCClient struct { // Connection pool of gRPC connections to the service. connPool gtransport.ConnPool // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE disableDeadlines bool // Points back to the CallOptions field of the containing ImageAnnotatorClient CallOptions **ImageAnnotatorCallOptions // The gRPC API client. imageAnnotatorClient visionpb.ImageAnnotatorClient // LROClient is used internally to handle long-running operations. // It is exposed so that its CallOptions can be modified if required. // Users should not Close this client. LROClient **lroauto.OperationsClient // The x-goog-* metadata to be sent with each request. xGoogMetadata metadata.MD } // NewImageAnnotatorClient creates a new image annotator client based on gRPC. // The returned client must be Closed when it is done being used to clean up its underlying connections. // // Service that performs Google Cloud Vision API detection tasks over client // images, such as face, landmark, logo, label, and text detection. The // ImageAnnotator service returns detected entities from the images. func NewImageAnnotatorClient(ctx context.Context, opts ...option.ClientOption) (*ImageAnnotatorClient, error) { clientOpts := defaultImageAnnotatorGRPCClientOptions() if newImageAnnotatorClientHook != nil { hookOpts, err := newImageAnnotatorClientHook(ctx, clientHookParams{}) if err != nil { return nil, err } clientOpts = append(clientOpts, hookOpts...) } disableDeadlines, err := checkDisableDeadlines() if err != nil { return nil, err } connPool, err := gtransport.DialPool(ctx, append(clientOpts, opts...)...) if err != nil { return nil, err } client := ImageAnnotatorClient{CallOptions: defaultImageAnnotatorCallOptions()} c := &imageAnnotatorGRPCClient{ connPool: connPool, disableDeadlines: disableDeadlines, imageAnnotatorClient: visionpb.NewImageAnnotatorClient(connPool), CallOptions: &client.CallOptions, } c.setGoogleClientInfo() client.internalClient = c client.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool)) if err != nil { // This error "should not happen", since we are just reusing old connection pool // and never actually need to dial. // If this does happen, we could leak connp. However, we cannot close conn: // If the user invoked the constructor with option.WithGRPCConn, // we would close a connection that's still in use. // TODO: investigate error conditions. return nil, err } c.LROClient = &client.LROClient return &client, nil } // Connection returns a connection to the API service. // // Deprecated. func (c *imageAnnotatorGRPCClient) Connection() *grpc.ClientConn { return c.connPool.Conn() } // setGoogleClientInfo sets the name and version of the application in // the `x-goog-api-client` header passed on each request. Intended for // use by Google-written clients. func (c *imageAnnotatorGRPCClient) setGoogleClientInfo(keyval ...string) { kv := append([]string{"gl-go", versionGo()}, keyval...) kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) } // Close closes the connection to the API service. The user should invoke this when // the client is no longer required. func (c *imageAnnotatorGRPCClient) Close() error { return c.connPool.Close() } func (c *imageAnnotatorGRPCClient) BatchAnnotateImages(ctx context.Context, req *visionpb.BatchAnnotateImagesRequest, opts ...gax.CallOption) (*visionpb.BatchAnnotateImagesResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() ctx = cctx } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) opts = append((*c.CallOptions).BatchAnnotateImages[0:len((*c.CallOptions).BatchAnnotateImages):len((*c.CallOptions).BatchAnnotateImages)], opts...) var resp *visionpb.BatchAnnotateImagesResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error resp, err = c.imageAnnotatorClient.BatchAnnotateImages(ctx, req, settings.GRPC...) return err }, opts...) if err != nil { return nil, err } return resp, nil } func (c *imageAnnotatorGRPCClient) BatchAnnotateFiles(ctx context.Context, req *visionpb.BatchAnnotateFilesRequest, opts ...gax.CallOption) (*visionpb.BatchAnnotateFilesResponse, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() ctx = cctx } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) opts = append((*c.CallOptions).BatchAnnotateFiles[0:len((*c.CallOptions).BatchAnnotateFiles):len((*c.CallOptions).BatchAnnotateFiles)], opts...) var resp *visionpb.BatchAnnotateFilesResponse err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error resp, err = c.imageAnnotatorClient.BatchAnnotateFiles(ctx, req, settings.GRPC...) return err }, opts...) if err != nil { return nil, err } return resp, nil } func (c *imageAnnotatorGRPCClient) AsyncBatchAnnotateImages(ctx context.Context, req *visionpb.AsyncBatchAnnotateImagesRequest, opts ...gax.CallOption) (*AsyncBatchAnnotateImagesOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() ctx = cctx } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) opts = append((*c.CallOptions).AsyncBatchAnnotateImages[0:len((*c.CallOptions).AsyncBatchAnnotateImages):len((*c.CallOptions).AsyncBatchAnnotateImages)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error resp, err = c.imageAnnotatorClient.AsyncBatchAnnotateImages(ctx, req, settings.GRPC...) return err }, opts...) if err != nil { return nil, err } return &AsyncBatchAnnotateImagesOperation{ lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } func (c *imageAnnotatorGRPCClient) AsyncBatchAnnotateFiles(ctx context.Context, req *visionpb.AsyncBatchAnnotateFilesRequest, opts ...gax.CallOption) (*AsyncBatchAnnotateFilesOperation, error) { if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { cctx, cancel := context.WithTimeout(ctx, 600000*time.Millisecond) defer cancel() ctx = cctx } md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) ctx = insertMetadata(ctx, c.xGoogMetadata, md) opts = append((*c.CallOptions).AsyncBatchAnnotateFiles[0:len((*c.CallOptions).AsyncBatchAnnotateFiles):len((*c.CallOptions).AsyncBatchAnnotateFiles)], opts...) var resp *longrunningpb.Operation err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { var err error resp, err = c.imageAnnotatorClient.AsyncBatchAnnotateFiles(ctx, req, settings.GRPC...) return err }, opts...) if err != nil { return nil, err } return &AsyncBatchAnnotateFilesOperation{ lro: longrunning.InternalNewOperation(*c.LROClient, resp), }, nil } // AsyncBatchAnnotateFilesOperation manages a long-running operation from AsyncBatchAnnotateFiles. type AsyncBatchAnnotateFilesOperation struct { lro *longrunning.Operation } // AsyncBatchAnnotateFilesOperation returns a new AsyncBatchAnnotateFilesOperation from a given name. // The name must be that of a previously created AsyncBatchAnnotateFilesOperation, possibly from a different process. func (c *imageAnnotatorGRPCClient) AsyncBatchAnnotateFilesOperation(name string) *AsyncBatchAnnotateFilesOperation { return &AsyncBatchAnnotateFilesOperation{ lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *AsyncBatchAnnotateFilesOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*visionpb.AsyncBatchAnnotateFilesResponse, error) { var resp visionpb.AsyncBatchAnnotateFilesResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err } return &resp, nil } // Poll fetches the latest state of the long-running operation. // // Poll also fetches the latest metadata, which can be retrieved by Metadata. // // If Poll fails, the error is returned and op is unmodified. If Poll succeeds and // the operation has completed with failure, the error is returned and op.Done will return true. // If Poll succeeds and the operation has completed successfully, // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *AsyncBatchAnnotateFilesOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*visionpb.AsyncBatchAnnotateFilesResponse, error) { var resp visionpb.AsyncBatchAnnotateFilesResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err } if !op.Done() { return nil, nil } return &resp, nil } // Metadata returns metadata associated with the long-running operation. // Metadata itself does not contact the server, but Poll does. // To get the latest metadata, call this method after a successful call to Poll. // If the metadata is not available, the returned metadata and error are both nil. func (op *AsyncBatchAnnotateFilesOperation) Metadata() (*visionpb.OperationMetadata, error) { var meta visionpb.OperationMetadata if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { return nil, nil } else if err != nil { return nil, err } return &meta, nil } // Done reports whether the long-running operation has completed. func (op *AsyncBatchAnnotateFilesOperation) Done() bool { return op.lro.Done() } // Name returns the name of the long-running operation. // The name is assigned by the server and is unique within the service from which the operation is created. func (op *AsyncBatchAnnotateFilesOperation) Name() string { return op.lro.Name() } // AsyncBatchAnnotateImagesOperation manages a long-running operation from AsyncBatchAnnotateImages. type AsyncBatchAnnotateImagesOperation struct { lro *longrunning.Operation } // AsyncBatchAnnotateImagesOperation returns a new AsyncBatchAnnotateImagesOperation from a given name. // The name must be that of a previously created AsyncBatchAnnotateImagesOperation, possibly from a different process. func (c *imageAnnotatorGRPCClient) AsyncBatchAnnotateImagesOperation(name string) *AsyncBatchAnnotateImagesOperation { return &AsyncBatchAnnotateImagesOperation{ lro: longrunning.InternalNewOperation(*c.LROClient, &longrunningpb.Operation{Name: name}), } } // Wait blocks until the long-running operation is completed, returning the response and any errors encountered. // // See documentation of Poll for error-handling information. func (op *AsyncBatchAnnotateImagesOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*visionpb.AsyncBatchAnnotateImagesResponse, error) { var resp visionpb.AsyncBatchAnnotateImagesResponse if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil { return nil, err } return &resp, nil } // Poll fetches the latest state of the long-running operation. // // Poll also fetches the latest metadata, which can be retrieved by Metadata. // // If Poll fails, the error is returned and op is unmodified. If Poll succeeds and // the operation has completed with failure, the error is returned and op.Done will return true. // If Poll succeeds and the operation has completed successfully, // op.Done will return true, and the response of the operation is returned. // If Poll succeeds and the operation has not completed, the returned response and error are both nil. func (op *AsyncBatchAnnotateImagesOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*visionpb.AsyncBatchAnnotateImagesResponse, error) { var resp visionpb.AsyncBatchAnnotateImagesResponse if err := op.lro.Poll(ctx, &resp, opts...); err != nil { return nil, err } if !op.Done() { return nil, nil } return &resp, nil } // Metadata returns metadata associated with the long-running operation. // Metadata itself does not contact the server, but Poll does. // To get the latest metadata, call this method after a successful call to Poll. // If the metadata is not available, the returned metadata and error are both nil. func (op *AsyncBatchAnnotateImagesOperation) Metadata() (*visionpb.OperationMetadata, error) { var meta visionpb.OperationMetadata if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata { return nil, nil } else if err != nil { return nil, err } return &meta, nil } // Done reports whether the long-running operation has completed. func (op *AsyncBatchAnnotateImagesOperation) Done() bool { return op.lro.Done() } // Name returns the name of the long-running operation. // The name is assigned by the server and is unique within the service from which the operation is created. func (op *AsyncBatchAnnotateImagesOperation) Name() string { return op.lro.Name() }
apache-2.0
Ruzzie/Ruzzie.Mtg.Core
src/RuzzieMtgCore/Ruzzie.Mtg.Core/Synergy/ConstrainedValue.cs
4901
using System; namespace Ruzzie.Mtg.Core.Synergy { /// <summary>Represents a specific constrained value type</summary> /// <typeparam name="T">The type that is constraint</typeparam> /// <typeparam name="TConstraint">The constraint that should be applied to the type</typeparam> public struct ConstrainedValue<T,TConstraint> : IEquatable<ConstrainedValue<T, TConstraint>>, IComparable<ConstrainedValue<T, TConstraint>>, IValueConstrainable<T> where T : struct, IEquatable<T>, IComparable<T> where TConstraint : IValueConstraint<T>, new() { /// <summary>Gets the value.</summary> /// <value>The value.</value> public T Value { get; } /// <summary>Performs an implicit conversion from <see cref="ConstrainedValue{T, TConstraint}"/> to <see cref="T"/>.</summary> /// <param name="value">The value.</param> /// <returns>The result of the conversion.</returns> public static implicit operator T(ConstrainedValue<T, TConstraint> value) { return value.Value; } /// <summary>Performs an implicit conversion from <see cref="T"/> to <see cref="ConstrainedValue{T, TConstraint}"/>.</summary> /// <param name="value">The value.</param> /// <returns>The result of the conversion.</returns> public static implicit operator ConstrainedValue<T, TConstraint> (T value) { return new ConstrainedValue<T, TConstraint>(value); } /// <summary>Initializes a new instance of the <see cref="ConstrainedValue{T, TConstraint}"/> struct.</summary> /// <param name="value">The value.</param> /// <exception cref="ArgumentOutOfRangeException">value - Value is out of constrained range.</exception> public ConstrainedValue(T value) { if (!TypeConstraints<T, TConstraint>.Constraint.IsWithinConstraint(value)) { throw new ArgumentOutOfRangeException(nameof(value), "Value is out of constrained range."); } Value = value; } /// <summary>Indicates whether the current value is equal to another object of the same type.</summary> /// <param name="other">An object to compare with this object.</param> /// <returns>true if the current value is equal to the <paramref name="other" /> parameter; otherwise, false.</returns> public bool Equals(ConstrainedValue<T, TConstraint> other) { return Value.Equals(other.Value); } /// <summary> /// Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object. /// </summary> /// <param name="other">An object to compare with this instance.</param> /// <returns> /// A value that indicates the relative order of the objects being compared. The return value has these meanings: Value Meaning Less than zero This instance precedes <paramref name="other" /> in the sort order. Zero This instance occurs in the same position in the sort order as <paramref name="other" />. Greater than zero This instance follows <paramref name="other" /> in the sort order. /// </returns> public int CompareTo(ConstrainedValue<T, TConstraint> other) { return Value.CompareTo(other.Value); } /// <summary>Gets the value constraint.</summary> /// <returns></returns> public IValueConstraint<T> GetValueConstraint() { return TypeConstraints<T, TConstraint>.Constraint; } /// <inheritdoc /> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is ConstrainedValue<T, TConstraint> other && Equals(other); } /// <inheritdoc /> public override int GetHashCode() { return Value.GetHashCode(); } /// <summary>Implements the operator ==.</summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns>The result of the operator.</returns> public static bool operator ==(ConstrainedValue<T, TConstraint> left, ConstrainedValue<T, TConstraint> right) { return left.Equals(right); } /// <summary>Implements the operator !=.</summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns>The result of the operator.</returns> public static bool operator !=(ConstrainedValue<T, TConstraint> left, ConstrainedValue<T, TConstraint> right) { return !left.Equals(right); } } }
apache-2.0
sholtebeck/knarflog
lib/bs4/tests/test_soup.py
23402
# -*- coding: utf-8 -*- """Tests of Beautiful Soup as a whole.""" from pdb import set_trace import logging import unittest import sys import tempfile from bs4 import ( BeautifulSoup, BeautifulStoneSoup, ) from bs4.element import ( CharsetMetaAttributeValue, ContentMetaAttributeValue, SoupStrainer, NamespacedAttribute, ) import bs4.dammit from bs4.dammit import ( EntitySubstitution, UnicodeDammit, EncodingDetector, ) from bs4.testing import ( default_builder, SoupTest, skipIf, ) import warnings try: from bs4.builder import LXMLTreeBuilder, LXMLTreeBuilderForXML LXML_PRESENT = True except ImportError, e: LXML_PRESENT = False PYTHON_3_PRE_3_2 = (sys.version_info[0] == 3 and sys.version_info < (3,2)) class TestConstructor(SoupTest): def test_short_unicode_input(self): data = u"<h1>éé</h1>" soup = self.soup(data) self.assertEqual(u"éé", soup.h1.string) def test_embedded_null(self): data = u"<h1>foo\0bar</h1>" soup = self.soup(data) self.assertEqual(u"foo\0bar", soup.h1.string) def test_exclude_encodings(self): utf8_data = u"Räksmörgås".encode("utf-8") soup = self.soup(utf8_data, exclude_encodings=["utf-8"]) self.assertEqual("windows-1252", soup.original_encoding) def test_custom_builder_class(self): # Verify that you can pass in a custom Builder class and # it'll be instantiated with the appropriate keyword arguments. class Mock(object): def __init__(self, **kwargs): self.called_with = kwargs self.is_xml = True def initialize_soup(self, soup): pass def prepare_markup(self, *args, **kwargs): return '' kwargs = dict( var="value", # This is a deprecated BS3-era keyword argument, which # will be stripped out. convertEntities=True, ) with warnings.catch_warnings(record=True): soup = BeautifulSoup('', builder=Mock, **kwargs) assert isinstance(soup.builder, Mock) self.assertEqual(dict(var="value"), soup.builder.called_with) # You can also instantiate the TreeBuilder yourself. In this # case, that specific object is used and any keyword arguments # to the BeautifulSoup constructor are ignored. builder = Mock(**kwargs) with warnings.catch_warnings(record=True) as w: soup = BeautifulSoup( '', builder=builder, ignored_value=True, ) msg = str(w[0].message) assert msg.startswith("Keyword arguments to the BeautifulSoup constructor will be ignored.") self.assertEqual(builder, soup.builder) self.assertEqual(kwargs, builder.called_with) def test_cdata_list_attributes(self): # Most attribute values are represented as scalars, but the # HTML standard says that some attributes, like 'class' have # space-separated lists as values. markup = '<a id=" an id " class=" a class "></a>' soup = self.soup(markup) # Note that the spaces are stripped for 'class' but not for 'id'. a = soup.a self.assertEqual(" an id ", a['id']) self.assertEqual(["a", "class"], a['class']) # TreeBuilder takes an argument called 'mutli_valued_attributes' which lets # you customize or disable this. As always, you can customize the TreeBuilder # by passing in a keyword argument to the BeautifulSoup constructor. soup = self.soup(markup, builder=default_builder, multi_valued_attributes=None) self.assertEqual(" a class ", soup.a['class']) # Here are two ways of saying that `id` is a multi-valued # attribute in this context, but 'class' is not. for switcheroo in ({'*': 'id'}, {'a': 'id'}): with warnings.catch_warnings(record=True) as w: # This will create a warning about not explicitly # specifying a parser, but we'll ignore it. soup = self.soup(markup, builder=None, multi_valued_attributes=switcheroo) a = soup.a self.assertEqual(["an", "id"], a['id']) self.assertEqual(" a class ", a['class']) class TestWarnings(SoupTest): def _no_parser_specified(self, s, is_there=True): v = s.startswith(BeautifulSoup.NO_PARSER_SPECIFIED_WARNING[:80]) self.assertTrue(v) def test_warning_if_no_parser_specified(self): with warnings.catch_warnings(record=True) as w: soup = self.soup("<a><b></b></a>") msg = str(w[0].message) self._assert_no_parser_specified(msg) def test_warning_if_parser_specified_too_vague(self): with warnings.catch_warnings(record=True) as w: soup = self.soup("<a><b></b></a>", "html") msg = str(w[0].message) self._assert_no_parser_specified(msg) def test_no_warning_if_explicit_parser_specified(self): with warnings.catch_warnings(record=True) as w: soup = self.soup("<a><b></b></a>", "html.parser") self.assertEqual([], w) def test_parseOnlyThese_renamed_to_parse_only(self): with warnings.catch_warnings(record=True) as w: soup = self.soup("<a><b></b></a>", parseOnlyThese=SoupStrainer("b")) msg = str(w[0].message) self.assertTrue("parseOnlyThese" in msg) self.assertTrue("parse_only" in msg) self.assertEqual(b"<b></b>", soup.encode()) def test_fromEncoding_renamed_to_from_encoding(self): with warnings.catch_warnings(record=True) as w: utf8 = b"\xc3\xa9" soup = self.soup(utf8, fromEncoding="utf8") msg = str(w[0].message) self.assertTrue("fromEncoding" in msg) self.assertTrue("from_encoding" in msg) self.assertEqual("utf8", soup.original_encoding) def test_unrecognized_keyword_argument(self): self.assertRaises( TypeError, self.soup, "<a>", no_such_argument=True) class TestWarnings(SoupTest): def test_disk_file_warning(self): filehandle = tempfile.NamedTemporaryFile() filename = filehandle.name try: with warnings.catch_warnings(record=True) as w: soup = self.soup(filename) msg = str(w[0].message) self.assertTrue("looks like a filename" in msg) finally: filehandle.close() # The file no longer exists, so Beautiful Soup will no longer issue the warning. with warnings.catch_warnings(record=True) as w: soup = self.soup(filename) self.assertEqual(0, len(w)) def test_url_warning_with_bytes_url(self): with warnings.catch_warnings(record=True) as warning_list: soup = self.soup(b"http://www.crummybytes.com/") # Be aware this isn't the only warning that can be raised during # execution.. self.assertTrue(any("looks like a URL" in str(w.message) for w in warning_list)) def test_url_warning_with_unicode_url(self): with warnings.catch_warnings(record=True) as warning_list: # note - this url must differ from the bytes one otherwise # python's warnings system swallows the second warning soup = self.soup(u"http://www.crummyunicode.com/") self.assertTrue(any("looks like a URL" in str(w.message) for w in warning_list)) def test_url_warning_with_bytes_and_space(self): with warnings.catch_warnings(record=True) as warning_list: soup = self.soup(b"http://www.crummybytes.com/ is great") self.assertFalse(any("looks like a URL" in str(w.message) for w in warning_list)) def test_url_warning_with_unicode_and_space(self): with warnings.catch_warnings(record=True) as warning_list: soup = self.soup(u"http://www.crummyuncode.com/ is great") self.assertFalse(any("looks like a URL" in str(w.message) for w in warning_list)) class TestSelectiveParsing(SoupTest): def test_parse_with_soupstrainer(self): markup = "No<b>Yes</b><a>No<b>Yes <c>Yes</c></b>" strainer = SoupStrainer("b") soup = self.soup(markup, parse_only=strainer) self.assertEqual(soup.encode(), b"<b>Yes</b><b>Yes <c>Yes</c></b>") class TestEntitySubstitution(unittest.TestCase): """Standalone tests of the EntitySubstitution class.""" def setUp(self): self.sub = EntitySubstitution def test_simple_html_substitution(self): # Unicode characters corresponding to named HTML entites # are substituted, and no others. s = u"foo\u2200\N{SNOWMAN}\u00f5bar" self.assertEqual(self.sub.substitute_html(s), u"foo&forall;\N{SNOWMAN}&otilde;bar") def test_smart_quote_substitution(self): # MS smart quotes are a common source of frustration, so we # give them a special test. quotes = b"\x91\x92foo\x93\x94" dammit = UnicodeDammit(quotes) self.assertEqual(self.sub.substitute_html(dammit.markup), "&lsquo;&rsquo;foo&ldquo;&rdquo;") def test_xml_converstion_includes_no_quotes_if_make_quoted_attribute_is_false(self): s = 'Welcome to "my bar"' self.assertEqual(self.sub.substitute_xml(s, False), s) def test_xml_attribute_quoting_normally_uses_double_quotes(self): self.assertEqual(self.sub.substitute_xml("Welcome", True), '"Welcome"') self.assertEqual(self.sub.substitute_xml("Bob's Bar", True), '"Bob\'s Bar"') def test_xml_attribute_quoting_uses_single_quotes_when_value_contains_double_quotes(self): s = 'Welcome to "my bar"' self.assertEqual(self.sub.substitute_xml(s, True), "'Welcome to \"my bar\"'") def test_xml_attribute_quoting_escapes_single_quotes_when_value_contains_both_single_and_double_quotes(self): s = 'Welcome to "Bob\'s Bar"' self.assertEqual( self.sub.substitute_xml(s, True), '"Welcome to &quot;Bob\'s Bar&quot;"') def test_xml_quotes_arent_escaped_when_value_is_not_being_quoted(self): quoted = 'Welcome to "Bob\'s Bar"' self.assertEqual(self.sub.substitute_xml(quoted), quoted) def test_xml_quoting_handles_angle_brackets(self): self.assertEqual( self.sub.substitute_xml("foo<bar>"), "foo&lt;bar&gt;") def test_xml_quoting_handles_ampersands(self): self.assertEqual(self.sub.substitute_xml("AT&T"), "AT&amp;T") def test_xml_quoting_including_ampersands_when_they_are_part_of_an_entity(self): self.assertEqual( self.sub.substitute_xml("&Aacute;T&T"), "&amp;Aacute;T&amp;T") def test_xml_quoting_ignoring_ampersands_when_they_are_part_of_an_entity(self): self.assertEqual( self.sub.substitute_xml_containing_entities("&Aacute;T&T"), "&Aacute;T&amp;T") def test_quotes_not_html_substituted(self): """There's no need to do this except inside attribute values.""" text = 'Bob\'s "bar"' self.assertEqual(self.sub.substitute_html(text), text) class TestEncodingConversion(SoupTest): # Test Beautiful Soup's ability to decode and encode from various # encodings. def setUp(self): super(TestEncodingConversion, self).setUp() self.unicode_data = u'<html><head><meta charset="utf-8"/></head><body><foo>Sacr\N{LATIN SMALL LETTER E WITH ACUTE} bleu!</foo></body></html>' self.utf8_data = self.unicode_data.encode("utf-8") # Just so you know what it looks like. self.assertEqual( self.utf8_data, b'<html><head><meta charset="utf-8"/></head><body><foo>Sacr\xc3\xa9 bleu!</foo></body></html>') def test_ascii_in_unicode_out(self): # ASCII input is converted to Unicode. The original_encoding # attribute is set to 'utf-8', a superset of ASCII. chardet = bs4.dammit.chardet_dammit logging.disable(logging.WARNING) try: def noop(str): return None # Disable chardet, which will realize that the ASCII is ASCII. bs4.dammit.chardet_dammit = noop ascii = b"<foo>a</foo>" soup_from_ascii = self.soup(ascii) unicode_output = soup_from_ascii.decode() self.assertTrue(isinstance(unicode_output, unicode)) self.assertEqual(unicode_output, self.document_for(ascii.decode())) self.assertEqual(soup_from_ascii.original_encoding.lower(), "utf-8") finally: logging.disable(logging.NOTSET) bs4.dammit.chardet_dammit = chardet def test_unicode_in_unicode_out(self): # Unicode input is left alone. The original_encoding attribute # is not set. soup_from_unicode = self.soup(self.unicode_data) self.assertEqual(soup_from_unicode.decode(), self.unicode_data) self.assertEqual(soup_from_unicode.foo.string, u'Sacr\xe9 bleu!') self.assertEqual(soup_from_unicode.original_encoding, None) def test_utf8_in_unicode_out(self): # UTF-8 input is converted to Unicode. The original_encoding # attribute is set. soup_from_utf8 = self.soup(self.utf8_data) self.assertEqual(soup_from_utf8.decode(), self.unicode_data) self.assertEqual(soup_from_utf8.foo.string, u'Sacr\xe9 bleu!') def test_utf8_out(self): # The internal data structures can be encoded as UTF-8. soup_from_unicode = self.soup(self.unicode_data) self.assertEqual(soup_from_unicode.encode('utf-8'), self.utf8_data) @skipIf( PYTHON_3_PRE_3_2, "Bad HTMLParser detected; skipping test of non-ASCII characters in attribute name.") def test_attribute_name_containing_unicode_characters(self): markup = u'<div><a \N{SNOWMAN}="snowman"></a></div>' self.assertEqual(self.soup(markup).div.encode("utf8"), markup.encode("utf8")) class TestUnicodeDammit(unittest.TestCase): """Standalone tests of UnicodeDammit.""" def test_unicode_input(self): markup = u"I'm already Unicode! \N{SNOWMAN}" dammit = UnicodeDammit(markup) self.assertEqual(dammit.unicode_markup, markup) def test_smart_quotes_to_unicode(self): markup = b"<foo>\x91\x92\x93\x94</foo>" dammit = UnicodeDammit(markup) self.assertEqual( dammit.unicode_markup, u"<foo>\u2018\u2019\u201c\u201d</foo>") def test_smart_quotes_to_xml_entities(self): markup = b"<foo>\x91\x92\x93\x94</foo>" dammit = UnicodeDammit(markup, smart_quotes_to="xml") self.assertEqual( dammit.unicode_markup, "<foo>&#x2018;&#x2019;&#x201C;&#x201D;</foo>") def test_smart_quotes_to_html_entities(self): markup = b"<foo>\x91\x92\x93\x94</foo>" dammit = UnicodeDammit(markup, smart_quotes_to="html") self.assertEqual( dammit.unicode_markup, "<foo>&lsquo;&rsquo;&ldquo;&rdquo;</foo>") def test_smart_quotes_to_ascii(self): markup = b"<foo>\x91\x92\x93\x94</foo>" dammit = UnicodeDammit(markup, smart_quotes_to="ascii") self.assertEqual( dammit.unicode_markup, """<foo>''""</foo>""") def test_detect_utf8(self): utf8 = b"Sacr\xc3\xa9 bleu! \xe2\x98\x83" dammit = UnicodeDammit(utf8) self.assertEqual(dammit.original_encoding.lower(), 'utf-8') self.assertEqual(dammit.unicode_markup, u'Sacr\xe9 bleu! \N{SNOWMAN}') def test_convert_hebrew(self): hebrew = b"\xed\xe5\xec\xf9" dammit = UnicodeDammit(hebrew, ["iso-8859-8"]) self.assertEqual(dammit.original_encoding.lower(), 'iso-8859-8') self.assertEqual(dammit.unicode_markup, u'\u05dd\u05d5\u05dc\u05e9') def test_dont_see_smart_quotes_where_there_are_none(self): utf_8 = b"\343\202\261\343\203\274\343\202\277\343\202\244 Watch" dammit = UnicodeDammit(utf_8) self.assertEqual(dammit.original_encoding.lower(), 'utf-8') self.assertEqual(dammit.unicode_markup.encode("utf-8"), utf_8) def test_ignore_inappropriate_codecs(self): utf8_data = u"Räksmörgås".encode("utf-8") dammit = UnicodeDammit(utf8_data, ["iso-8859-8"]) self.assertEqual(dammit.original_encoding.lower(), 'utf-8') def test_ignore_invalid_codecs(self): utf8_data = u"Räksmörgås".encode("utf-8") for bad_encoding in ['.utf8', '...', 'utF---16.!']: dammit = UnicodeDammit(utf8_data, [bad_encoding]) self.assertEqual(dammit.original_encoding.lower(), 'utf-8') def test_exclude_encodings(self): # This is UTF-8. utf8_data = u"Räksmörgås".encode("utf-8") # But if we exclude UTF-8 from consideration, the guess is # Windows-1252. dammit = UnicodeDammit(utf8_data, exclude_encodings=["utf-8"]) self.assertEqual(dammit.original_encoding.lower(), 'windows-1252') # And if we exclude that, there is no valid guess at all. dammit = UnicodeDammit( utf8_data, exclude_encodings=["utf-8", "windows-1252"]) self.assertEqual(dammit.original_encoding, None) def test_encoding_detector_replaces_junk_in_encoding_name_with_replacement_character(self): detected = EncodingDetector( b'<?xml version="1.0" encoding="UTF-\xdb" ?>') encodings = list(detected.encodings) assert u'utf-\N{REPLACEMENT CHARACTER}' in encodings def test_detect_html5_style_meta_tag(self): for data in ( b'<html><meta charset="euc-jp" /></html>', b"<html><meta charset='euc-jp' /></html>", b"<html><meta charset=euc-jp /></html>", b"<html><meta charset=euc-jp/></html>"): dammit = UnicodeDammit(data, is_html=True) self.assertEqual( "euc-jp", dammit.original_encoding) def test_last_ditch_entity_replacement(self): # This is a UTF-8 document that contains bytestrings # completely incompatible with UTF-8 (ie. encoded with some other # encoding). # # Since there is no consistent encoding for the document, # Unicode, Dammit will eventually encode the document as UTF-8 # and encode the incompatible characters as REPLACEMENT # CHARACTER. # # If chardet is installed, it will detect that the document # can be converted into ISO-8859-1 without errors. This happens # to be the wrong encoding, but it is a consistent encoding, so the # code we're testing here won't run. # # So we temporarily disable chardet if it's present. doc = b"""\357\273\277<?xml version="1.0" encoding="UTF-8"?> <html><b>\330\250\330\252\330\261</b> <i>\310\322\321\220\312\321\355\344</i></html>""" chardet = bs4.dammit.chardet_dammit logging.disable(logging.WARNING) try: def noop(str): return None bs4.dammit.chardet_dammit = noop dammit = UnicodeDammit(doc) self.assertEqual(True, dammit.contains_replacement_characters) self.assertTrue(u"\ufffd" in dammit.unicode_markup) soup = BeautifulSoup(doc, "html.parser") self.assertTrue(soup.contains_replacement_characters) finally: logging.disable(logging.NOTSET) bs4.dammit.chardet_dammit = chardet def test_byte_order_mark_removed(self): # A document written in UTF-16LE will have its byte order marker stripped. data = b'\xff\xfe<\x00a\x00>\x00\xe1\x00\xe9\x00<\x00/\x00a\x00>\x00' dammit = UnicodeDammit(data) self.assertEqual(u"<a>áé</a>", dammit.unicode_markup) self.assertEqual("utf-16le", dammit.original_encoding) def test_detwingle(self): # Here's a UTF8 document. utf8 = (u"\N{SNOWMAN}" * 3).encode("utf8") # Here's a Windows-1252 document. windows_1252 = ( u"\N{LEFT DOUBLE QUOTATION MARK}Hi, I like Windows!" u"\N{RIGHT DOUBLE QUOTATION MARK}").encode("windows_1252") # Through some unholy alchemy, they've been stuck together. doc = utf8 + windows_1252 + utf8 # The document can't be turned into UTF-8: self.assertRaises(UnicodeDecodeError, doc.decode, "utf8") # Unicode, Dammit thinks the whole document is Windows-1252, # and decodes it into "☃☃☃“Hi, I like Windows!”☃☃☃" # But if we run it through fix_embedded_windows_1252, it's fixed: fixed = UnicodeDammit.detwingle(doc) self.assertEqual( u"☃☃☃“Hi, I like Windows!”☃☃☃", fixed.decode("utf8")) def test_detwingle_ignores_multibyte_characters(self): # Each of these characters has a UTF-8 representation ending # in \x93. \x93 is a smart quote if interpreted as # Windows-1252. But our code knows to skip over multibyte # UTF-8 characters, so they'll survive the process unscathed. for tricky_unicode_char in ( u"\N{LATIN SMALL LIGATURE OE}", # 2-byte char '\xc5\x93' u"\N{LATIN SUBSCRIPT SMALL LETTER X}", # 3-byte char '\xe2\x82\x93' u"\xf0\x90\x90\x93", # This is a CJK character, not sure which one. ): input = tricky_unicode_char.encode("utf8") self.assertTrue(input.endswith(b'\x93')) output = UnicodeDammit.detwingle(input) self.assertEqual(output, input) class TestNamedspacedAttribute(SoupTest): def test_name_may_be_none(self): a = NamespacedAttribute("xmlns", None) self.assertEqual(a, "xmlns") def test_attribute_is_equivalent_to_colon_separated_string(self): a = NamespacedAttribute("a", "b") self.assertEqual("a:b", a) def test_attributes_are_equivalent_if_prefix_and_name_identical(self): a = NamespacedAttribute("a", "b", "c") b = NamespacedAttribute("a", "b", "c") self.assertEqual(a, b) # The actual namespace is not considered. c = NamespacedAttribute("a", "b", None) self.assertEqual(a, c) # But name and prefix are important. d = NamespacedAttribute("a", "z", "c") self.assertNotEqual(a, d) e = NamespacedAttribute("z", "b", "c") self.assertNotEqual(a, e) class TestAttributeValueWithCharsetSubstitution(unittest.TestCase): def test_content_meta_attribute_value(self): value = CharsetMetaAttributeValue("euc-jp") self.assertEqual("euc-jp", value) self.assertEqual("euc-jp", value.original_value) self.assertEqual("utf8", value.encode("utf8")) def test_content_meta_attribute_value(self): value = ContentMetaAttributeValue("text/html; charset=euc-jp") self.assertEqual("text/html; charset=euc-jp", value) self.assertEqual("text/html; charset=euc-jp", value.original_value) self.assertEqual("text/html; charset=utf8", value.encode("utf8"))
apache-2.0
jsiebens/tenorite
tenorite-api/src/main/java/net/tenorite/badges/validators/NrOfBlocks.java
1884
/* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.tenorite.badges.validators; import net.tenorite.badges.Badge; import net.tenorite.badges.BadgeRepository; import net.tenorite.badges.BadgeValidator; import net.tenorite.badges.events.BadgeEarned; import net.tenorite.game.Game; import net.tenorite.game.PlayingStats; import net.tenorite.game.events.GameFinished; import java.util.function.Consumer; /** * @author Johan Siebens */ public final class NrOfBlocks extends BadgeValidator { private final int target; public NrOfBlocks(Badge badge, int target) { super(badge); this.target = target; } @Override protected void doProcess(GameFinished gameFinished, BadgeRepository.BadgeOps badgeOps, Consumer<BadgeEarned> onBadgeEarned) { gameFinished.getRanking().forEach(p -> validateBadge(gameFinished.getGame(), p, badgeOps, onBadgeEarned)); } private void validateBadge(Game game, PlayingStats playingStats, BadgeRepository.BadgeOps badgeOps, Consumer<BadgeEarned> onBadgeEarned) { String name = playingStats.getPlayer().getName(); long count = badgeOps.getProgress(badge, name) + playingStats.getNrOfBlocks(); updateBadgeLevelAndProgressWhenTargetIsReached(game, name, badge, count, target, badgeOps, onBadgeEarned); } }
apache-2.0
hdbeukel/genestacker
Genestacker/Genestacker-lib/src/main/java/org/ugent/caagt/genestacker/exceptions/DuplicateConstraintException.java
1328
// Copyright 2012 Herman De Beukelaer // // 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.ugent.caagt.genestacker.exceptions; /** * Exception indicating that duplicate constraints are given as input to the * search algorithm. * * @author <a href="mailto:herman.debeukelaer@ugent.be">Herman De Beukelaer</a> */ public class DuplicateConstraintException extends SearchException { /** * Creates a new instance of <code>DuplicateConstraintException</code> without detail message. */ public DuplicateConstraintException() { } /** * Constructs an instance of <code>DuplicateConstraintException</code> with the specified detail message. * @param msg the detail message. */ public DuplicateConstraintException(String msg) { super(msg); } }
apache-2.0
AstroGypsophila/TryGank
TryGank/app/src/main/java/com/gypsophila/trygank/business/gank/model/GankBusinessImpl.java
1725
package com.gypsophila.trygank.business.gank.model; import com.gypsophila.commonlib.activity.BaseActivity; import com.gypsophila.commonlib.net.RequestCallback; import com.gypsophila.commonlib.net.RequestParameter; import com.gypsophila.trygank.business.gank.GankJsonUtils; import com.gypsophila.trygank.db.GankDataBaseManager; import com.gypsophila.trygank.business.RemoteService; import com.gypsophila.trygank.entity.GankBean; import com.gypsophila.trygank.entity.GankPlusBean; import java.util.List; /** * Description : * Author : AstroGypsophila * GitHub : https://github.com/AstroGypsophila * Date : 2016/10/4 */ public class GankBusinessImpl implements IGankBusiness { @Override public void loadBeans(BaseActivity activity, String url, List<RequestParameter> parameters, final GankLoadListener listener) { RequestCallback callback = new RequestCallback() { @Override public void onSuccess(String content) { GankPlusBean gankPlusBean = GankJsonUtils.readJsonGankPlusBean(content); listener.onSuccess(gankPlusBean.results); } @Override public void onFail(String errorMessage) { } }; RemoteService.getInstance().invoke(activity, url, parameters, callback); } @Override public void loadBeansFromDataBase(BaseActivity activity, String filter, final GankLoadListener listener) { List<GankBean> gankBeanList = GankDataBaseManager.getGankList(activity, filter); if (gankBeanList != null) { listener.onSuccess(gankBeanList); } else { } } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-backup/src/main/java/com/amazonaws/services/backup/model/transform/CreateBackupVaultResultJsonUnmarshaller.java
3394
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.backup.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.backup.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * CreateBackupVaultResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CreateBackupVaultResultJsonUnmarshaller implements Unmarshaller<CreateBackupVaultResult, JsonUnmarshallerContext> { public CreateBackupVaultResult unmarshall(JsonUnmarshallerContext context) throws Exception { CreateBackupVaultResult createBackupVaultResult = new CreateBackupVaultResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return createBackupVaultResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("BackupVaultName", targetDepth)) { context.nextToken(); createBackupVaultResult.setBackupVaultName(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("BackupVaultArn", targetDepth)) { context.nextToken(); createBackupVaultResult.setBackupVaultArn(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("CreationDate", targetDepth)) { context.nextToken(); createBackupVaultResult.setCreationDate(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return createBackupVaultResult; } private static CreateBackupVaultResultJsonUnmarshaller instance; public static CreateBackupVaultResultJsonUnmarshaller getInstance() { if (instance == null) instance = new CreateBackupVaultResultJsonUnmarshaller(); return instance; } }
apache-2.0
vam-google/google-cloud-java
google-cloud-clients/google-cloud-automl/src/main/java/com/google/cloud/automl/v1beta1/stub/GrpcPredictionServiceStub.java
5205
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.automl.v1beta1.stub; import com.google.api.core.BetaApi; import com.google.api.gax.core.BackgroundResource; import com.google.api.gax.core.BackgroundResourceAggregation; import com.google.api.gax.grpc.GrpcCallSettings; import com.google.api.gax.grpc.GrpcStubCallableFactory; import com.google.api.gax.rpc.ClientContext; import com.google.api.gax.rpc.UnaryCallable; import com.google.cloud.automl.v1beta1.PredictRequest; import com.google.cloud.automl.v1beta1.PredictResponse; import io.grpc.MethodDescriptor; import io.grpc.protobuf.ProtoUtils; import java.io.IOException; import java.util.concurrent.TimeUnit; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS /** * gRPC stub implementation for Cloud AutoML API. * * <p>This class is for advanced usage and reflects the underlying API directly. */ @Generated("by gapic-generator") @BetaApi("A restructuring of stub classes is planned, so this may break in the future") public class GrpcPredictionServiceStub extends PredictionServiceStub { private static final MethodDescriptor<PredictRequest, PredictResponse> predictMethodDescriptor = MethodDescriptor.<PredictRequest, PredictResponse>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("google.cloud.automl.v1beta1.PredictionService/Predict") .setRequestMarshaller(ProtoUtils.marshaller(PredictRequest.getDefaultInstance())) .setResponseMarshaller(ProtoUtils.marshaller(PredictResponse.getDefaultInstance())) .build(); private final BackgroundResource backgroundResources; private final UnaryCallable<PredictRequest, PredictResponse> predictCallable; private final GrpcStubCallableFactory callableFactory; public static final GrpcPredictionServiceStub create(PredictionServiceStubSettings settings) throws IOException { return new GrpcPredictionServiceStub(settings, ClientContext.create(settings)); } public static final GrpcPredictionServiceStub create(ClientContext clientContext) throws IOException { return new GrpcPredictionServiceStub( PredictionServiceStubSettings.newBuilder().build(), clientContext); } public static final GrpcPredictionServiceStub create( ClientContext clientContext, GrpcStubCallableFactory callableFactory) throws IOException { return new GrpcPredictionServiceStub( PredictionServiceStubSettings.newBuilder().build(), clientContext, callableFactory); } /** * Constructs an instance of GrpcPredictionServiceStub, using the given settings. This is * protected so that it is easy to make a subclass, but otherwise, the static factory methods * should be preferred. */ protected GrpcPredictionServiceStub( PredictionServiceStubSettings settings, ClientContext clientContext) throws IOException { this(settings, clientContext, new GrpcPredictionServiceCallableFactory()); } /** * Constructs an instance of GrpcPredictionServiceStub, using the given settings. This is * protected so that it is easy to make a subclass, but otherwise, the static factory methods * should be preferred. */ protected GrpcPredictionServiceStub( PredictionServiceStubSettings settings, ClientContext clientContext, GrpcStubCallableFactory callableFactory) throws IOException { this.callableFactory = callableFactory; GrpcCallSettings<PredictRequest, PredictResponse> predictTransportSettings = GrpcCallSettings.<PredictRequest, PredictResponse>newBuilder() .setMethodDescriptor(predictMethodDescriptor) .build(); this.predictCallable = callableFactory.createUnaryCallable( predictTransportSettings, settings.predictSettings(), clientContext); backgroundResources = new BackgroundResourceAggregation(clientContext.getBackgroundResources()); } public UnaryCallable<PredictRequest, PredictResponse> predictCallable() { return predictCallable; } @Override public final void close() { shutdown(); } @Override public void shutdown() { backgroundResources.shutdown(); } @Override public boolean isShutdown() { return backgroundResources.isShutdown(); } @Override public boolean isTerminated() { return backgroundResources.isTerminated(); } @Override public void shutdownNow() { backgroundResources.shutdownNow(); } @Override public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException { return backgroundResources.awaitTermination(duration, unit); } }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-ses/src/main/java/com/amazonaws/services/simpleemail/model/Message.java
5905
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.simpleemail.model; import java.io.Serializable; import javax.annotation.Generated; /** * <p> * Represents the message to be sent, composed of a subject and a body. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/email-2010-12-01/Message" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class Message implements Serializable, Cloneable { /** * <p> * The subject of the message: A short summary of the content, which will appear in the recipient's inbox. * </p> */ private Content subject; /** * <p> * The message body. * </p> */ private Body body; /** * Default constructor for Message object. Callers should use the setter or fluent setter (with...) methods to * initialize the object after creating it. */ public Message() { } /** * Constructs a new Message object. Callers should use the setter or fluent setter (with...) methods to initialize * any additional object members. * * @param subject * The subject of the message: A short summary of the content, which will appear in the recipient's inbox. * @param body * The message body. */ public Message(Content subject, Body body) { setSubject(subject); setBody(body); } /** * <p> * The subject of the message: A short summary of the content, which will appear in the recipient's inbox. * </p> * * @param subject * The subject of the message: A short summary of the content, which will appear in the recipient's inbox. */ public void setSubject(Content subject) { this.subject = subject; } /** * <p> * The subject of the message: A short summary of the content, which will appear in the recipient's inbox. * </p> * * @return The subject of the message: A short summary of the content, which will appear in the recipient's inbox. */ public Content getSubject() { return this.subject; } /** * <p> * The subject of the message: A short summary of the content, which will appear in the recipient's inbox. * </p> * * @param subject * The subject of the message: A short summary of the content, which will appear in the recipient's inbox. * @return Returns a reference to this object so that method calls can be chained together. */ public Message withSubject(Content subject) { setSubject(subject); return this; } /** * <p> * The message body. * </p> * * @param body * The message body. */ public void setBody(Body body) { this.body = body; } /** * <p> * The message body. * </p> * * @return The message body. */ public Body getBody() { return this.body; } /** * <p> * The message body. * </p> * * @param body * The message body. * @return Returns a reference to this object so that method calls can be chained together. */ public Message withBody(Body body) { setBody(body); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getSubject() != null) sb.append("Subject: ").append(getSubject()).append(","); if (getBody() != null) sb.append("Body: ").append(getBody()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof Message == false) return false; Message other = (Message) obj; if (other.getSubject() == null ^ this.getSubject() == null) return false; if (other.getSubject() != null && other.getSubject().equals(this.getSubject()) == false) return false; if (other.getBody() == null ^ this.getBody() == null) return false; if (other.getBody() != null && other.getBody().equals(this.getBody()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getSubject() == null) ? 0 : getSubject().hashCode()); hashCode = prime * hashCode + ((getBody() == null) ? 0 : getBody().hashCode()); return hashCode; } @Override public Message clone() { try { return (Message) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
apache-2.0
jittakal/4go
cdirections/channel-directions.go
334
package main import ( "fmt" ) func ping(pings chan<- string, msg string) { pings <- msg } func pong(pings <-chan string, pongs chan<- string) { msg := <-pings pongs <- msg } func main() { pings := make(chan string, 1) pongs := make(chan string, 1) ping(pings, "passed message") pong(pings, pongs) fmt.Println(<-pongs) }
apache-2.0
stdlib-js/stdlib
lib/node_modules/@stdlib/string/split-grapheme-clusters/lib/main.js
1756
/** * @license Apache-2.0 * * Copyright (c) 2021 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var isString = require( '@stdlib/assert/is-string' ).isPrimitive; var nextGraphemeClusterBreak = require( '@stdlib/string/next-grapheme-cluster-break' ); // MAIN // /** * Splits a string by its grapheme cluster breaks. * * @param {string} str - input string * @throws {TypeError} must provide a string primitive * @returns {StringArray} array of grapheme clusters * * @example * var out = splitGraphemeClusters( 'café' ); * // returns [ 'c', 'a', 'f', 'é' ] * * @example * var out = splitGraphemeClusters( '🍕🍕🍕' ); * // returns [ '🍕', '🍕', '🍕' ] */ function splitGraphemeClusters( str ) { var idx; var brk; var out; if ( !isString( str ) ) { throw new TypeError( 'invalid argument. Must provide a string. Value: `' + str + '`.' ); } idx = 0; out = []; if ( str.length === 0 ) { return out; } brk = nextGraphemeClusterBreak( str, idx ); while ( brk !== -1 ) { out.push( str.substring( idx, brk ) ); idx = brk; brk = nextGraphemeClusterBreak( str, idx ); } out.push( str.substring( idx ) ); return out; } // EXPORTS // module.exports = splitGraphemeClusters;
apache-2.0
ITMAOO/scenic
scenic-common/scenic-common-security/src/main/java/com/itmaoo/scenic/common/security/shiro/filter/RcFormAuthenticationFilter.java
743
package com.itmaoo.scenic.common.security.shiro.filter; import org.apache.shiro.web.filter.authc.FormAuthenticationFilter; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; /** * @desc 自定义form表单认证过滤器 * @author itmaoo * @version 2016年8月29日 上午10:52:13 */ public class RcFormAuthenticationFilter extends FormAuthenticationFilter { @Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception { if (request.getAttribute(getFailureKeyAttribute()) != null) { return true; } request.setAttribute("shiroLoginFailure", "用户未登录"); return super.onAccessDenied(request, response, mappedValue); } }
apache-2.0
Aconex/scrutineer
http/src/main/java/com/aconex/scrutineer/http/JsonEncodedHttpEndpointSourceConnector.java
4652
package com.aconex.scrutineer.http; import com.aconex.scrutineer.AbstractIdAndVersionStreamConnector; import com.aconex.scrutineer.ConnectorConfig; import com.aconex.scrutineer.IdAndVersion; import com.aconex.scrutineer.IdAndVersionFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Iterator; public class JsonEncodedHttpEndpointSourceConnector extends AbstractIdAndVersionStreamConnector { private final Logger logger = LoggerFactory.getLogger(JsonEncodedHttpEndpointSourceConnector.class); private HttpURLConnection httpConnection; private InputStream responseInputStream; protected JsonEncodedHttpEndpointSourceConnector(ConnectorConfig connectorConfig, IdAndVersionFactory idAndVersionFactory) { super(connectorConfig, idAndVersionFactory); } @Override public void open() { try { disableSSLValidation(); responseInputStream = sendRequest(getConfig()); } catch (Exception e) { throw new RuntimeException("Failed to list entities from source endpoint: " + getConfig(), e); } } public Iterator<IdAndVersion> fetchFromSource() { return new JsonEncodedIdAndVersionInputStreamIterator(responseInputStream, getIdAndVersionFactory()); } private InputStream sendRequest(HttpConnectorConfig config) throws IOException { String queryUrl = config.getHttpEndpointUrl(); logger.info("Querying http endpoint: {}", queryUrl); httpConnection = prepareConnection(config, queryUrl); httpConnection.connect(); return new BufferedInputStream(httpConnection.getInputStream()); } private HttpURLConnection prepareConnection(HttpConnectorConfig config, String queryUrl) throws IOException { HttpURLConnection connection = (HttpURLConnection) new URL(queryUrl).openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(config.getHttpConnectionTimeoutInMillisecond()); connection.setReadTimeout(config.getHttpReadTimeoutInMillisecond()); return connection; } public void disableSSLValidation() { try { HttpsURLConnection.setDefaultSSLSocketFactory(createSslContext().getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true); } catch (NoSuchAlgorithmException | KeyManagementException e) { logger.warn("Failed to disable SSL validation", e); } } private SSLContext createSslContext() throws NoSuchAlgorithmException, KeyManagementException { SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[]{createDumbTrustManager()}, null); return sslContext; } private X509TrustManager createDumbTrustManager() { return new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }; } @Override public void close() { closeResponseInputStream(); closeHttpConnection(); } private void closeResponseInputStream() { if (responseInputStream != null) { try { responseInputStream.close(); } catch (IOException e) { logger.warn("Failed to close the http response http stream", e); } } } private void closeHttpConnection() { if (httpConnection != null) { try { httpConnection.disconnect(); } catch (Exception e) { logger.warn("Failed to disconnect http url connection", e); } } } private HttpConnectorConfig getConfig() { return (HttpConnectorConfig) getConnectorConfig(); } }
apache-2.0
lostdragon/cobar
cobar-parser/src/main/java/com/alibaba/cobar/parser/ast/expression/primary/function/string/Quote.java
1275
/* * Copyright 1999-2012 Alibaba Group. * * 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. */ /** * (created at 2011-1-23) */ package com.alibaba.cobar.parser.ast.expression.primary.function.string; import java.util.List; import com.alibaba.cobar.parser.ast.expression.Expression; import com.alibaba.cobar.parser.ast.expression.primary.function.FunctionExpression; /** * @author <a href="mailto:shuo.qius@alibaba-inc.com">QIU Shuo</a> */ public class Quote extends FunctionExpression { public Quote(List<Expression> arguments) { super("QUOTE", arguments); } @Override public FunctionExpression constructFunction(List<Expression> arguments) { return new Quote(arguments); } }
apache-2.0
neo4j-contrib/spring-boot
spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/mvc/HalBrowserMvcEndpointDisabledIntegrationTests.java
3958
/* * Copyright 2012-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.actuate.endpoint.mvc; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.actuate.autoconfigure.MinimalActuatorHypermediaApplication; import org.springframework.boot.actuate.endpoint.mvc.HalBrowserMvcEndpointDisabledIntegrationTests.SpringBootHypermediaApplication; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * Integration tests for {@link HalBrowserMvcEndpoint} * * @author Dave Syer * @author Andy Wilkinson */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(SpringBootHypermediaApplication.class) @WebAppConfiguration @DirtiesContext public class HalBrowserMvcEndpointDisabledIntegrationTests { @Autowired private WebApplicationContext context; @Autowired private MvcEndpoints mvcEndpoints; private MockMvc mockMvc; @Before public void setUp() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build(); } @Test public void linksOnActuator() throws Exception { this.mockMvc.perform(get("/actuator").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andExpect(jsonPath("$._links").exists()) .andExpect(header().doesNotExist("cache-control")); } @Test public void browser() throws Exception { MvcResult response = this.mockMvc .perform(get("/actuator/").accept(MediaType.TEXT_HTML)) .andExpect(status().isOk()).andReturn(); assertThat(response.getResponse().getForwardedUrl()) .isEqualTo("/actuator/browser.html"); } @Test public void endpointsDoNotHaveLinks() throws Exception { for (MvcEndpoint endpoint : this.mvcEndpoints.getEndpoints()) { String path = endpoint.getPath(); if ("/actuator".equals(path)) { continue; } path = path.length() > 0 ? path : "/"; this.mockMvc.perform(get(path).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$._links").doesNotExist()); } } @MinimalActuatorHypermediaApplication @Configuration public static class SpringBootHypermediaApplication { public static void main(String[] args) { SpringApplication.run(SpringBootHypermediaApplication.class, new String[] { "--endpoints.hypermedia.enabled=false" }); } } }
apache-2.0
play1-maven-plugin/play1-maven-test-projects
external-modules/guice/guice-using-binding-annotation/test/ApplicationTest.java
598
import org.junit.*; import play.test.*; import play.mvc.*; import play.mvc.Http.*; //import models.*; public class ApplicationTest extends FunctionalTest { @Test public void car1() { Response response = GET("/car1"); assertContentEquals("Driving a Toyota", response); } @Test public void car2() { Response response = GET("/car2"); assertContentEquals("Driving a Ford", response); } @Test public void car3() { Response response = GET("/car3"); assertContentEquals("Driving a Holden", response); } }
apache-2.0
playernodie/java-desktop-apps
some-tools/webapp/src/main/java/vn/tuan/app/model/NewsModel.java
3419
package vn.tuan.app.model; import com.google.common.base.MoreObjects; import com.google.common.base.Strings; import com.google.common.collect.Lists; import vn.tuan.app.dao.ArticleDao; import vn.tuan.app.dao.entities.ArticleEntity; import java.text.SimpleDateFormat; import java.util.List; /** * Created by tuanlhd on 7/9/15. */ public class NewsModel { private int idPost; private String title; private String summary; private String thumb; private String content; private String author; private String time; private List<NewsModel> relatedPosts; public NewsModel() { } public NewsModel(int idPost, String title, String summary) { this.idPost = idPost; this.title = title; this.summary = summary; } public static List<NewsModel> convert(List<ArticleEntity> la){ List<NewsModel> newsl = Lists.newArrayList(); SimpleDateFormat dfm = new SimpleDateFormat("YYYY-MM-dd"); if(la!=null) for (ArticleEntity a : la){ NewsModel n = new NewsModel(); n.setIdPost(a.getId()); n.setTitle(a.getTitle()); n.setSummary(a.getSummary()); n.setThumb(a.getThumb()); n.setTime(dfm.format(a.getCreatetime())); newsl.add(n); } return newsl; } public static NewsModel convert(ArticleEntity a){ NewsModel n = new NewsModel(); n.setIdPost(a.getId()); n.setTitle(a.getTitle()); n.setSummary(a.getSummary()); n.setThumb(a.getThumb()); n.setContent(a.getContent()); n.setAuthor(a.getAuthor()); n.setTime(MoreObjects.firstNonNull(a.getCreatetime(),"").toString()); ArticleDao dao = new ArticleDao(); List<NewsModel> lr = Lists.newArrayList(); //get article by related posts for (String s : a.getRelatedpost().split(",")){ if(!Strings.isNullOrEmpty(s)){ ArticleEntity a2 = dao.getByOriginalUrl(s); if(a2!=null) lr.add(new NewsModel(a2.getId(),a2.getTitle(),a2.getSummary())); } } n.setRelatedPosts(lr); return n; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public String getThumb() { return thumb; } public void setThumb(String thumb) { this.thumb = thumb; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public int getIdPost() { return idPost; } public void setIdPost(int idPost) { this.idPost = idPost; } public List<NewsModel> getRelatedPosts() { return relatedPosts; } public void setRelatedPosts(List<NewsModel> relatedPosts) { this.relatedPosts = relatedPosts; } }
apache-2.0
blackducksoftware/hub-detect
hub-detect/src/main/groovy/com/blackducksoftware/integration/hub/detect/workflow/report/DetailedSearchSummaryData.java
2090
/** * hub-detect * * Copyright (C) 2019 Black Duck Software, Inc. * http://www.blackducksoftware.com/ * * 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.blackducksoftware.integration.hub.detect.workflow.report; import java.util.List; public class DetailedSearchSummaryData { private final String directory; private final List<DetailedSearchSummaryBomToolData> applicable; private final List<DetailedSearchSummaryBomToolData> notApplicable; private final List<DetailedSearchSummaryBomToolData> notSearchable; public DetailedSearchSummaryData(final String directory, final List<DetailedSearchSummaryBomToolData> applicable, final List<DetailedSearchSummaryBomToolData> notApplicable, final List<DetailedSearchSummaryBomToolData> notSearchable) { this.directory = directory; this.applicable = applicable; this.notApplicable = notApplicable; this.notSearchable = notSearchable; } public List<DetailedSearchSummaryBomToolData> getApplicable() { return applicable; } public List<DetailedSearchSummaryBomToolData> getNotApplicable() { return notApplicable; } public List<DetailedSearchSummaryBomToolData> getNotSearchable() { return notSearchable; } public String getDirectory() { return directory; } }
apache-2.0
cheeseplus/bento-ya
lib/bento/cli.rb
6559
require "optparse" require "ostruct" require "bento/common" require "bento/build" require "bento/delete" require "bento/normalize" require "bento/release" require "bento/revoke" require "bento/test" require "bento/upload" class Options NAME = File.basename($PROGRAM_NAME).freeze def self.parse(args) options = OpenStruct.new options.template_files = calculate_templates("**/*.json") global = OptionParser.new do |opts| opts.banner = "Usage: #{NAME} [SUBCOMMAND [options]]" opts.separator "" opts.separator <<-COMMANDS.gsub(/^ {8}/, "") build : build one or more templates help : prints this help message list : list all templates in project normalize : normalize one or more templates test : test one or more builds with kitchen upload : upload one or more builds to Vagrant Cloud and S3 release : release a version of a box on Vagrant Cloud revoke : revoke a version of a box on Vagrant Cloud delete : delete a version of a box from Vagrant Cloud COMMANDS end # @tas50: commenting this out since it's unused 11/30/2018 # platforms_argv_proc = proc { |opts| # opts.platforms = builds["public"] unless args.empty? # } templates_argv_proc = proc { |opts| opts.template_files = calculate_templates(args) unless args.empty? opts.template_files.each do |t| unless File.exist?("#{t}.json") warn "File #{t}.json does not exist for template '#{t}'" exit(1) end end } box_version_argv_proc = proc { |opts| opts.box = ARGV[0] opts.version = ARGV[1] } md_json_argv_proc = proc { |opts| opts.md_json = ARGV[0] } subcommand = { help: { parser: OptionParser.new {}, argv: proc { |_opts| puts global exit(0) }, }, build: { class: BuildRunner, parser: OptionParser.new do |opts| opts.banner = "Usage: #{NAME} build [options] TEMPLATE[ TEMPLATE ...]" opts.on("-n", "--dry-run", "Dry run (what would happen)") do |opt| options.dry_run = opt end opts.on("-c BUILD_YML", "--config BUILD_YML", "Use a configuration file") do |opt| options.config = opt end opts.on("-d", "--[no-]debug", "Run packer with debug output") do |opt| options.debug = opt end opts.on("-o BUILDS", "--only BUILDS", "Only build some Packer builds (ex: parallels-iso,virtualbox-iso,vmware-iso)") do |opt| options.only = opt end opts.on("-e BUILDS", "--except BUILDS", "Build all Packer builds except these (ex: parallels-iso,virtualbox-iso,vmware-iso)") do |opt| options.except = opt end opts.on("-m MIRROR", "--mirror MIRROR", "Look for isos at MIRROR") do |opt| options.mirror = opt end opts.on("-C cpus", "--cpus CPUS", "# of CPUs per provider") do |opt| options.cpus = opt end opts.on("-M MEMORY", "--memory MEMORY", "Memory (MB) per provider") do |opt| options.mem = opt end opts.on("-H", "--headed", "Display provider UI windows") do |opt| options.headed = opt end opts.on("-S", "--single", "Disable parallelization of Packer builds") do |opt| options.single = opt end opts.on("-v VERSION", "--version VERSION", "Override the version set in the template") do |opt| options.override_version = opt end end, argv: templates_argv_proc, }, list: { class: ListRunner, parser: OptionParser.new do |opts| opts.banner = "Usage: #{NAME} list [TEMPLATE ...]" end, argv: templates_argv_proc, }, normalize: { class: NormalizeRunner, parser: OptionParser.new do |opts| opts.banner = "Usage: #{NAME} normalize TEMPLATE[ TEMPLATE ...]" opts.on("-d", "--[no-]debug", "Run packer with debug output") do |opt| options.debug = opt end end, argv: templates_argv_proc, }, test: { class: TestRunner, parser: OptionParser.new do |opts| opts.banner = "Usage: #{NAME} test [options]" opts.on("--no-shared-folder", "Disable shared folder testing") do |opt| options.no_shared = opt end opts.on("-p", "--provisioner PROVISIONER", "Use a specfic provisioner") do |opt| options.provisioner = opt end end, argv: proc {}, }, upload: { class: UploadRunner, parser: OptionParser.new do |opts| opts.banner = "Usage: #{NAME} upload" end, argv: md_json_argv_proc, }, release: { class: ReleaseRunner, parser: OptionParser.new do |opts| opts.banner = "Usage: #{NAME} release BOX VERSION" end, argv: box_version_argv_proc, }, revoke: { class: RevokeRunner, parser: OptionParser.new do |opts| opts.banner = "Usage: #{NAME} revoke BOX VERSION" end, argv: box_version_argv_proc, }, delete: { class: DeleteRunner, parser: OptionParser.new do |opts| opts.banner = "Usage: #{NAME} delete BOX VERSION" end, argv: box_version_argv_proc, }, } global.order! command = args.empty? ? :help : ARGV.shift.to_sym subcommand.fetch(command).fetch(:parser).order! subcommand.fetch(command).fetch(:argv).call(options) options.command = command options.klass = subcommand.fetch(command).fetch(:class) options end def self.calculate_templates(globs) Array(globs) .map { |glob| result = Dir.glob(glob); result.empty? ? glob : result } .flatten .sort .delete_if { |file| file =~ /\.(variables||metadata)\.json/ } .map { |template| template.sub(/\.json$/, "") } end end class ListRunner include Common attr_reader :templates def initialize(opts) @templates = opts.template_files end def start templates.each { |template| puts template } end end class Runner attr_reader :options def initialize(options) @options = options end def start options.klass.new(options).start end end
apache-2.0
morsdatum/ArangoDB
js/apps/system/aardvark/frontend/js/models/foxx.js
518
/*global window, Backbone */ (function() { "use strict"; window.Foxx = Backbone.Model.extend({ defaults: { "title": "", "version": "", "mount": "", "description": "", "git": "", "isSystem": false, "development": false }, url: function() { if (this.get("_key")) { return "/_admin/aardvark/foxxes/" + this.get("_key"); } return "/_admin/aardvark/foxxes/install"; }, isNew: function() { return false; } }); }());
apache-2.0
ullgren/camel
core/camel-base/src/main/java/org/apache/camel/processor/PollEnricher.java
17631
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.processor; import org.apache.camel.AggregationStrategy; import org.apache.camel.AsyncCallback; import org.apache.camel.CamelContext; import org.apache.camel.CamelContextAware; import org.apache.camel.CamelExchangeException; import org.apache.camel.Consumer; import org.apache.camel.Endpoint; import org.apache.camel.Exchange; import org.apache.camel.Expression; import org.apache.camel.ExtendedCamelContext; import org.apache.camel.ExtendedExchange; import org.apache.camel.NoTypeConversionAvailableException; import org.apache.camel.PollingConsumer; import org.apache.camel.impl.engine.DefaultConsumerCache; import org.apache.camel.spi.ConsumerCache; import org.apache.camel.spi.EndpointUtilizationStatistics; import org.apache.camel.spi.ExceptionHandler; import org.apache.camel.spi.IdAware; import org.apache.camel.spi.NormalizedEndpointUri; import org.apache.camel.spi.RouteIdAware; import org.apache.camel.support.AsyncProcessorSupport; import org.apache.camel.support.BridgeExceptionHandlerToErrorHandler; import org.apache.camel.support.DefaultConsumer; import org.apache.camel.support.EventDrivenPollingConsumer; import org.apache.camel.support.ExchangeHelper; import org.apache.camel.support.service.ServiceHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.apache.camel.support.ExchangeHelper.copyResultsPreservePattern; /** * A content enricher that enriches input data by first obtaining additional * data from a <i>resource</i> represented by an endpoint <code>producer</code> * and second by aggregating input data and additional data. Aggregation of * input data and additional data is delegated to an {@link AggregationStrategy} * object. * <p/> * Uses a {@link org.apache.camel.PollingConsumer} to obtain the additional data as opposed to {@link Enricher} * that uses a {@link org.apache.camel.Producer}. * * @see Enricher */ public class PollEnricher extends AsyncProcessorSupport implements IdAware, RouteIdAware, CamelContextAware { private static final Logger LOG = LoggerFactory.getLogger(PollEnricher.class); private CamelContext camelContext; private ConsumerCache consumerCache; private String id; private String routeId; private AggregationStrategy aggregationStrategy; private final Expression expression; private long timeout; private boolean aggregateOnException; private int cacheSize; private boolean ignoreInvalidEndpoint; /** * Creates a new {@link PollEnricher}. * * @param expression expression to use to compute the endpoint to poll from. * @param timeout timeout in millis */ public PollEnricher(Expression expression, long timeout) { this.expression = expression; this.timeout = timeout; } @Override public CamelContext getCamelContext() { return camelContext; } @Override public void setCamelContext(CamelContext camelContext) { this.camelContext = camelContext; } @Override public String getId() { return id; } @Override public void setId(String id) { this.id = id; } @Override public String getRouteId() { return routeId; } @Override public void setRouteId(String routeId) { this.routeId = routeId; } public Expression getExpression() { return expression; } public EndpointUtilizationStatistics getEndpointUtilizationStatistics() { return consumerCache.getEndpointUtilizationStatistics(); } public AggregationStrategy getAggregationStrategy() { return aggregationStrategy; } /** * Sets the aggregation strategy for this poll enricher. * * @param aggregationStrategy the aggregationStrategy to set */ public void setAggregationStrategy(AggregationStrategy aggregationStrategy) { this.aggregationStrategy = aggregationStrategy; } public long getTimeout() { return timeout; } /** * Sets the timeout to use when polling. * <p/> * Use 0 to use receiveNoWait, * Use -1 to use receive with no timeout (which will block until data is available). * * @param timeout timeout in millis. */ public void setTimeout(long timeout) { this.timeout = timeout; } public boolean isAggregateOnException() { return aggregateOnException; } public void setAggregateOnException(boolean aggregateOnException) { this.aggregateOnException = aggregateOnException; } /** * Sets the default aggregation strategy for this poll enricher. */ public void setDefaultAggregationStrategy() { this.aggregationStrategy = defaultAggregationStrategy(); } public int getCacheSize() { return cacheSize; } public void setCacheSize(int cacheSize) { this.cacheSize = cacheSize; } public boolean isIgnoreInvalidEndpoint() { return ignoreInvalidEndpoint; } public void setIgnoreInvalidEndpoint(boolean ignoreInvalidEndpoint) { this.ignoreInvalidEndpoint = ignoreInvalidEndpoint; } /** * Enriches the input data (<code>exchange</code>) by first obtaining * additional data from an endpoint represented by an endpoint * <code>producer</code> and second by aggregating input data and additional * data. Aggregation of input data and additional data is delegated to an * {@link AggregationStrategy} object set at construction time. If the * message exchange with the resource endpoint fails then no aggregation * will be done and the failed exchange content is copied over to the * original message exchange. * * @param exchange input data. */ @Override public boolean process(Exchange exchange, AsyncCallback callback) { try { preCheckPoll(exchange); } catch (Exception e) { exchange.setException(new CamelExchangeException("Error during pre poll check", exchange, e)); callback.done(true); return true; } // which consumer to use PollingConsumer consumer; Endpoint endpoint; // use dynamic endpoint so calculate the endpoint to use Object recipient = null; boolean prototype = cacheSize < 0; try { recipient = expression.evaluate(exchange, Object.class); recipient = prepareRecipient(exchange, recipient); Endpoint existing = getExistingEndpoint(exchange, recipient); if (existing == null) { endpoint = resolveEndpoint(exchange, recipient, prototype); } else { endpoint = existing; // we have an existing endpoint then its not a prototype scope prototype = false; } // acquire the consumer from the cache consumer = consumerCache.acquirePollingConsumer(endpoint); } catch (Throwable e) { if (isIgnoreInvalidEndpoint()) { if (LOG.isDebugEnabled()) { LOG.debug("Endpoint uri is invalid: " + recipient + ". This exception will be ignored.", e); } } else { exchange.setException(e); } callback.done(true); return true; } // grab the real delegate consumer that performs the actual polling Consumer delegate = consumer; if (consumer instanceof EventDrivenPollingConsumer) { delegate = ((EventDrivenPollingConsumer) consumer).getDelegateConsumer(); } // is the consumer bridging the error handler? boolean bridgeErrorHandler = false; if (delegate instanceof DefaultConsumer) { ExceptionHandler handler = ((DefaultConsumer) delegate).getExceptionHandler(); if (handler instanceof BridgeExceptionHandlerToErrorHandler) { bridgeErrorHandler = true; } } Exchange resourceExchange; try { if (timeout < 0) { LOG.debug("Consumer receive: {}", consumer); resourceExchange = consumer.receive(); } else if (timeout == 0) { LOG.debug("Consumer receiveNoWait: {}", consumer); resourceExchange = consumer.receiveNoWait(); } else { LOG.debug("Consumer receive with timeout: {} ms. {}", timeout, consumer); resourceExchange = consumer.receive(timeout); } if (resourceExchange == null) { LOG.debug("Consumer received no exchange"); } else { LOG.debug("Consumer received: {}", resourceExchange); } } catch (Exception e) { exchange.setException(new CamelExchangeException("Error during poll", exchange, e)); callback.done(true); return true; } finally { // return the consumer back to the cache consumerCache.releasePollingConsumer(endpoint, consumer); // and stop prototype endpoints if (prototype) { ServiceHelper.stopAndShutdownService(endpoint); } } // remember current redelivery stats Object redeliveried = exchange.getIn().getHeader(Exchange.REDELIVERED); Object redeliveryCounter = exchange.getIn().getHeader(Exchange.REDELIVERY_COUNTER); Object redeliveryMaxCounter = exchange.getIn().getHeader(Exchange.REDELIVERY_MAX_COUNTER); // if we are bridging error handler and failed then remember the caused exception Throwable cause = null; if (resourceExchange != null && bridgeErrorHandler) { cause = resourceExchange.getException(); } try { if (!isAggregateOnException() && (resourceExchange != null && resourceExchange.isFailed())) { // copy resource exchange onto original exchange (preserving pattern) // and preserve redelivery headers copyResultsPreservePattern(exchange, resourceExchange); } else { prepareResult(exchange); // prepare the exchanges for aggregation ExchangeHelper.prepareAggregation(exchange, resourceExchange); // must catch any exception from aggregation Exchange aggregatedExchange = aggregationStrategy.aggregate(exchange, resourceExchange); if (aggregatedExchange != null) { // copy aggregation result onto original exchange (preserving pattern) copyResultsPreservePattern(exchange, aggregatedExchange); // handover any synchronization if (resourceExchange != null) { resourceExchange.adapt(ExtendedExchange.class).handoverCompletions(exchange); } } } // if we failed then restore caused exception if (cause != null) { // restore caused exception exchange.setException(cause); // remove the exhausted marker as we want to be able to perform redeliveries with the error handler exchange.adapt(ExtendedExchange.class).setRedeliveryExhausted(false); // preserve the redelivery stats if (redeliveried != null) { exchange.getMessage().setHeader(Exchange.REDELIVERED, redeliveried); } if (redeliveryCounter != null) { exchange.getMessage().setHeader(Exchange.REDELIVERY_COUNTER, redeliveryCounter); } if (redeliveryMaxCounter != null) { exchange.getMessage().setHeader(Exchange.REDELIVERY_MAX_COUNTER, redeliveryMaxCounter); } } // set header with the uri of the endpoint enriched so we can use that for tracing etc exchange.getMessage().setHeader(Exchange.TO_ENDPOINT, consumer.getEndpoint().getEndpointUri()); } catch (Throwable e) { exchange.setException(new CamelExchangeException("Error occurred during aggregation", exchange, e)); callback.done(true); return true; } callback.done(true); return true; } protected static Object prepareRecipient(Exchange exchange, Object recipient) throws NoTypeConversionAvailableException { if (recipient instanceof Endpoint || recipient instanceof NormalizedEndpointUri) { return recipient; } else if (recipient instanceof String) { // trim strings as end users might have added spaces between separators recipient = ((String) recipient).trim(); } if (recipient != null) { ExtendedCamelContext ecc = (ExtendedCamelContext) exchange.getContext(); String uri; if (recipient instanceof String) { uri = (String) recipient; } else { // convert to a string type we can work with uri = ecc.getTypeConverter().mandatoryConvertTo(String.class, exchange, recipient); } // optimize and normalize endpoint return ecc.normalizeUri(uri); } return null; } protected static Endpoint getExistingEndpoint(Exchange exchange, Object recipient) { if (recipient instanceof Endpoint) { return (Endpoint) recipient; } if (recipient != null) { if (recipient instanceof NormalizedEndpointUri) { NormalizedEndpointUri nu = (NormalizedEndpointUri) recipient; ExtendedCamelContext ecc = (ExtendedCamelContext) exchange.getContext(); return ecc.hasEndpoint(nu); } else { String uri = recipient.toString(); return exchange.getContext().hasEndpoint(uri); } } return null; } protected static Endpoint resolveEndpoint(Exchange exchange, Object recipient, boolean prototype) { return prototype ? ExchangeHelper.resolvePrototypeEndpoint(exchange, recipient) : ExchangeHelper.resolveEndpoint(exchange, recipient); } /** * Strategy to pre check polling. * <p/> * Is currently used to prevent doing poll enrich from a file based endpoint when the current route also * started from a file based endpoint as that is not currently supported. * * @param exchange the current exchange */ protected void preCheckPoll(Exchange exchange) throws Exception { // noop } private static void prepareResult(Exchange exchange) { if (exchange.getPattern().isOutCapable()) { exchange.getOut().copyFrom(exchange.getIn()); } } private static AggregationStrategy defaultAggregationStrategy() { return new CopyAggregationStrategy(); } @Override public String toString() { return id; } @Override protected void doStart() throws Exception { if (consumerCache == null) { // create consumer cache if we use dynamic expressions for computing the endpoints to poll consumerCache = new DefaultConsumerCache(this, camelContext, cacheSize); LOG.debug("PollEnrich {} using ConsumerCache with cacheSize={}", this, cacheSize); } if (aggregationStrategy instanceof CamelContextAware) { ((CamelContextAware) aggregationStrategy).setCamelContext(camelContext); } ServiceHelper.startService(consumerCache, aggregationStrategy); } @Override protected void doStop() throws Exception { ServiceHelper.stopService(aggregationStrategy, consumerCache); } @Override protected void doShutdown() throws Exception { ServiceHelper.stopAndShutdownServices(aggregationStrategy, consumerCache); } private static class CopyAggregationStrategy implements AggregationStrategy { @Override public Exchange aggregate(Exchange oldExchange, Exchange newExchange) { if (newExchange != null) { copyResultsPreservePattern(oldExchange, newExchange); } else { // if no newExchange then there was no message from the external resource // and therefore we should set an empty body to indicate this fact // but keep headers/attachments as we want to propagate those oldExchange.getIn().setBody(null); oldExchange.setOut(null); } return oldExchange; } } }
apache-2.0
mindsbackyard/galvanic-test
src/lib.rs
11427
/* Copyright 2017 Christopher Bacher * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use std::fmt::Debug; use std::ops::Drop; pub trait TestFixture<'param, P, R>: Drop where P: Debug + 'static, { fn new(curried_params: &'param P) -> Self; fn parameters() -> Option<Box<Iterator<Item = P>>>; fn setup(&mut self) -> FixtureBinding<Self, R> where Self: std::marker::Sized; fn tear_down(&self) {} } pub struct FixtureBinding<'fixture, F: 'fixture, R> { pub val: R, pub params: &'fixture F, } impl<'fixture, F: 'fixture, R> FixtureBinding<'fixture, F, R> { pub fn decompose(self) -> (R, &'fixture F) { (self.val, self.params) } pub fn into_val(self) -> R { self.val } pub fn into_params(self) -> &'fixture F { self.params } } /// Creates a new `TestFixture` implementation. /// /// A `fixture!` requires a name, parameters and a #[macro_export(local_inner_macros)] macro_rules! fixture { ( @impl_drop $name:ident ) => { impl<'param> ::std::ops::Drop for $name<'param> { fn drop(&mut self) { use ::galvanic_test::TestFixture; self.tear_down(); } } }; ( @impl_struct $name:ident Params[$($param:ident : $param_ty:ty),*] Members[$($member:ident : $member_ty:ty),*] ) => { #[allow(non_camel_case_types)] #[derive(Debug)] pub struct $name<'param> { $(pub $param : &'param $param_ty,)* $($member : Option<$member_ty>,)* } }; ( @new_method Params[$param:ident : $param_ty:ty] Members[$($member:ident),*] ) => { fn new($param : &'param $param_ty) -> Self { Self { $param, $($member: None,)* } } }; ( @new_method Params[$($param:ident : $param_ty:ty),+] Members[$($member:ident),*] ) => { fn new(&($(ref $param),*) : &'param ($($param_ty),*)) -> Self { Self { $($param,)* $($member: None,)* } } }; ( $name:ident ( ) -> $ret_ty:ty { $(members { $($member:ident : Option<$member_ty:ty>),* })* setup(& mut $self_setup:ident) $setup_body:block $(tear_down(&$self_td:ident) $tear_down_body:block)* } ) => { fixture!(@impl_struct $name Params[_phantom : ()] Members[$($($member : $member_ty),*),*]); impl<'param> ::galvanic_test::TestFixture<'param, (), $ret_ty> for $name<'param> { fn new(_phantom: &'param ()) -> Self { Self { _phantom, $($($member: None),*),* } } fn parameters() -> Option<Box<Iterator<Item=()>>> { Some(Box::new(Some(()).into_iter())) } fn setup(&mut $self_setup) -> ::galvanic_test::FixtureBinding<Self, $ret_ty> { let value = $setup_body; ::galvanic_test::FixtureBinding { val: value, params: $self_setup } } $(fn tear_down(&$self_td) $tear_down_body)* } fixture!(@impl_drop $name); }; ( $name:ident ($($param:ident : $param_ty:ty),+) -> $ret_ty:ty { $(members { $($member:ident : Option<$member_ty:ty>),* })* $(params $params_body:block)* setup(& mut $self_setup:ident) $setup_body:block $(tear_down(&$self_td:ident) $tear_down_body:block)* } ) => { fixture!(@impl_struct $name Params[$($param : $param_ty),*] Members[$($($member : $member_ty),*),*]); impl<'param> ::galvanic_test::TestFixture<'param, ($($param_ty),*), $ret_ty> for $name<'param> { fixture!(@new_method Params[$($param : $param_ty),*] Members[$($($member),*),*]); fn parameters() -> Option<Box<Iterator<Item=($($param_ty),*)>>> { (None as Option<Box<Iterator<Item=($($param_ty),*)>>>) $(; Some(Box::new($params_body)))* } fn setup(&mut $self_setup) -> ::galvanic_test::FixtureBinding<Self, $ret_ty> { let value = $setup_body; ::galvanic_test::FixtureBinding { val: value, params: $self_setup } } $(fn tear_down(&$self_td) $tear_down_body)* } fixture!(@impl_drop $name); }; } #[macro_export(local_inner_macros)] macro_rules! test { ( @parameters | $body:block $test_case_failed:ident ) => { $body }; ( @parameters | $body:block $test_case_failed:ident $(($fixture_obj:ident, $params:expr, $fixture:ident))+) => { let mut described_parameters = String::from("Test panicked before all fixtures have been assigned."); let result = ::std::panic::catch_unwind(::std::panic::AssertUnwindSafe(|| { let mut described_params = Vec::new(); $( let params = &$params; let mut $fixture_obj = $fixture::new(params); described_params.push(_galvanic__format!("{:?}", $fixture_obj)); let mut $fixture = $fixture_obj.setup(); noop(&$fixture); )* described_parameters = described_params.join(", "); $body })); if result.is_err() { _galvanic__println!("The above error occured with the following parameterisation of the test case:\n {}\n", described_parameters); $test_case_failed.set(true); } }; ( @parameters , $($remainder:tt)+ ) => { test!(@parameters $($remainder)*); }; ( @parameters $fixture:ident ( $($expr:expr),* ) $($remainder:tt)+ ) => { test!(@parameters $($remainder)* (fixture_obj, ($($expr),*), $fixture)); }; ( @parameters $fixture:ident $($remainder:tt)+ ) => { match $fixture::parameters() { Some(iterator) => { for params in iterator { test!(@parameters $($remainder)* (fixture_obj, params, $fixture)); } }, None => _galvanic__panic!(_galvanic__concat!( "If a test fixture should be injected without supplying parameters, ", "it either needs to have no arguments ", "or a `params` block returning an iterator of parameter tuples ", "must be given for the fixture.")) } }; ( $(#[$attr:meta])* $name:ident | $($args_and_body:tt)* ) => { #[test] $(#[$attr])* fn $name() { #[allow(dead_code)] fn noop<F, R>(_: &::galvanic_test::FixtureBinding<F,R>) { } // Cell is a workaround for #![allow(unused_mut)] which would affect the whole fn let test_case_failed = ::std::cell::Cell::new(false); test!(@parameters $($args_and_body)* test_case_failed); if test_case_failed.get() { _galvanic__panic!("Some parameterised test cases failed"); } } }; ( $(#[$attr:meta])* $name:ident $body:block ) => { #[test] $(#[$attr])* fn $name() { $body } }; } #[macro_export(local_inner_macros)] #[cfg(not(feature = "galvanic_mock_integration"))] macro_rules! test_suite { // named test suite ( name $name:ident ; $($remainder:tt)* ) => { #[cfg(test)] mod $name { #[allow(unused_imports)] use ::galvanic_test::TestFixture; galvanic_test::__test_suite_int!(@int $($remainder)*); } }; // anonymous test suite ( $($remainder:tt)* ) => { #[cfg(test)] mod __galvanic_test { #[allow(unused_imports)] use ::galvanic_test::TestFixture; galvanic_test::__test_suite_int!(@int $($remainder)*); } }; } #[macro_export(local_inner_macros)] #[cfg(feature = "galvanic_mock_integration")] macro_rules! test_suite { // named test suite ( name $name:ident ; $($remainder:tt)* ) => { #[cfg(test)] mod $name { #[allow(unused_imports)] use ::galvanic_mock::use_mocks; #[allow(unused_imports)] use super::*; #[use_mocks] mod with_mocks { #[allow(unused_imports)] use ::galvanic_test::TestFixture; galvanic_test::__test_suite_int!(@int $($remainder)*); } } }; // anonymous test suite ( $($remainder:tt)* ) => { #[cfg(test)] mod __galvanic_test { #[allow(unused_imports)] use ::galvanic_mock::use_mocks; #[allow(unused_imports)] use super::*; #[use_mocks] mod with_mocks { #[allow(unused_imports)] use ::galvanic_test::TestFixture; galvanic_test::__test_suite_int!(@int $($remainder)*); } } }; } #[macro_export(local_inner_macros)] macro_rules! __test_suite_int { // internal: fixture in test_suite ( @int $(#[$attr:meta])* fixture $name:ident ($($param:ident : $param_ty:ty),*) -> $ret_ty:ty { $(members { $($member:ident : Option<$member_ty:ty>),* })* $(params $params_body:block)* setup(& mut $self_setup:ident) $setup_body:block $(tear_down(&$self_td:ident) $tear_down_body:block)* } $($remainder:tt)* ) => { fixture!( $(#[$attr])* $name ($($param : $param_ty),*) -> $ret_ty { $(members { $($member : Option<$member_ty>),* })* $(params $params_body)* setup(& mut $self_setup) $setup_body $(tear_down(&$self_td) $tear_down_body)* }); galvanic_test::__test_suite_int!(@int $($remainder)*); }; // internal: test in test_suite ( @int $(#[$attr:meta])* test $name:ident ( $($fixture:ident $(($($expr:expr),*))*),* ) $body:block $($remainder:tt)* ) => { test!( $(#[$attr])* $name | $($fixture $(($($expr),*))* ),* | $body); galvanic_test::__test_suite_int!(@int $($remainder)*); }; // internal: arbitrary item in test suite ( @int $item:item $($remainder:tt)* ) => { $item galvanic_test::__test_suite_int!(@int $($remainder)*); }; // internal: empty test suite ( @int ) => { }; } #[doc(hidden)] #[macro_export] macro_rules! _galvanic__panic { ($($inner:tt)*) => { panic!($($inner)*) }; } #[doc(hidden)] #[macro_export] macro_rules! _galvanic__format { ($($inner:tt)*) => { format!($($inner)*) }; } #[doc(hidden)] #[macro_export] macro_rules! _galvanic__println { ($($inner:tt)*) => { println!($($inner)*) }; } #[doc(hidden)] #[macro_export] macro_rules! _galvanic__concat { ($($inner:tt)*) => { concat!($($inner)*) }; }
apache-2.0
gurleen-gks/athenz
servers/zms/src/main/java/com/yahoo/athenz/zms/ZMSResources.java
106907
// // This file generated by rdl 1.5.2. Do not modify! // package com.yahoo.athenz.zms; import com.yahoo.rdl.*; import javax.ws.rs.*; import javax.ws.rs.core.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.inject.Inject; @Path("/v1") public class ZMSResources { @GET @Path("/domain/{domain}") @Produces(MediaType.APPLICATION_JSON) public Domain getDomain(@PathParam("domain") String domain) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authenticate(); return this.delegate.getDomain(context, domain); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource getDomain"); throw typedException(code, e, ResourceError.class); } } } @GET @Path("/domain") @Produces(MediaType.APPLICATION_JSON) public DomainList getDomainList(@QueryParam("limit") Integer limit, @QueryParam("skip") String skip, @QueryParam("prefix") String prefix, @QueryParam("depth") Integer depth, @QueryParam("account") String account, @QueryParam("ypmid") Integer productId, @QueryParam("member") String roleMember, @QueryParam("role") String roleName, @HeaderParam("If-Modified-Since") String modifiedSince) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authenticate(); return this.delegate.getDomainList(context, limit, skip, prefix, depth, account, productId, roleMember, roleName, modifiedSince); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource getDomainList"); throw typedException(code, e, ResourceError.class); } } } @POST @Path("/domain") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Domain postTopLevelDomain(@HeaderParam("Y-Audit-Ref") String auditRef, TopLevelDomain detail) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("create", "sys.auth:domain", null); return this.delegate.postTopLevelDomain(context, auditRef, detail); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource postTopLevelDomain"); throw typedException(code, e, ResourceError.class); } } } @POST @Path("/subdomain/{parent}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Domain postSubDomain(@PathParam("parent") String parent, @HeaderParam("Y-Audit-Ref") String auditRef, SubDomain detail) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("create", "" + parent + ":domain", null); return this.delegate.postSubDomain(context, parent, auditRef, detail); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource postSubDomain"); throw typedException(code, e, ResourceError.class); } } } @POST @Path("/userdomain/{name}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Domain postUserDomain(@PathParam("name") String name, @HeaderParam("Y-Audit-Ref") String auditRef, UserDomain detail) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("create", "user." + name + ":domain", null); return this.delegate.postUserDomain(context, name, auditRef, detail); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource postUserDomain"); throw typedException(code, e, ResourceError.class); } } } @DELETE @Path("/domain/{name}") @Produces(MediaType.APPLICATION_JSON) public void deleteTopLevelDomain(@PathParam("name") String name, @HeaderParam("Y-Audit-Ref") String auditRef) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("delete", "sys.auth:domain", null); this.delegate.deleteTopLevelDomain(context, name, auditRef); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource deleteTopLevelDomain"); throw typedException(code, e, ResourceError.class); } } } @DELETE @Path("/subdomain/{parent}/{name}") @Produces(MediaType.APPLICATION_JSON) public void deleteSubDomain(@PathParam("parent") String parent, @PathParam("name") String name, @HeaderParam("Y-Audit-Ref") String auditRef) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("delete", "" + parent + ":domain", null); this.delegate.deleteSubDomain(context, parent, name, auditRef); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource deleteSubDomain"); throw typedException(code, e, ResourceError.class); } } } @DELETE @Path("/userdomain/{name}") @Produces(MediaType.APPLICATION_JSON) public void deleteUserDomain(@PathParam("name") String name, @HeaderParam("Y-Audit-Ref") String auditRef) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("delete", "user." + name + ":domain", null); this.delegate.deleteUserDomain(context, name, auditRef); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource deleteUserDomain"); throw typedException(code, e, ResourceError.class); } } } @PUT @Path("/domain/{name}/meta") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public void putDomainMeta(@PathParam("name") String name, @HeaderParam("Y-Audit-Ref") String auditRef, DomainMeta detail) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("update", "" + name + ":", null); this.delegate.putDomainMeta(context, name, auditRef, detail); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.CONFLICT: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource putDomainMeta"); throw typedException(code, e, ResourceError.class); } } } @PUT @Path("/domain/{name}/meta/system/{attribute}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public void putDomainSystemMeta(@PathParam("name") String name, @PathParam("attribute") String attribute, @HeaderParam("Y-Audit-Ref") String auditRef, DomainMeta detail) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("update", "sys.auth:meta." + attribute + "." + name + "", null); this.delegate.putDomainSystemMeta(context, name, attribute, auditRef, detail); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.CONFLICT: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource putDomainSystemMeta"); throw typedException(code, e, ResourceError.class); } } } @PUT @Path("/domain/{name}/template") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public void putDomainTemplate(@PathParam("name") String name, @HeaderParam("Y-Audit-Ref") String auditRef, DomainTemplate domainTemplate) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("update", "" + name + ":template", null); this.delegate.putDomainTemplate(context, name, auditRef, domainTemplate); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.CONFLICT: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource putDomainTemplate"); throw typedException(code, e, ResourceError.class); } } } @PUT @Path("/domain/{name}/template/{template}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public void putDomainTemplateExt(@PathParam("name") String name, @PathParam("template") String template, @HeaderParam("Y-Audit-Ref") String auditRef, DomainTemplate domainTemplate) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("update", "" + name + ":template." + template + "", null); this.delegate.putDomainTemplateExt(context, name, template, auditRef, domainTemplate); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.CONFLICT: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource putDomainTemplateExt"); throw typedException(code, e, ResourceError.class); } } } @GET @Path("/domain/{name}/template") @Produces(MediaType.APPLICATION_JSON) public DomainTemplateList getDomainTemplateList(@PathParam("name") String name) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authenticate(); return this.delegate.getDomainTemplateList(context, name); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource getDomainTemplateList"); throw typedException(code, e, ResourceError.class); } } } @DELETE @Path("/domain/{name}/template/{template}") @Produces(MediaType.APPLICATION_JSON) public void deleteDomainTemplate(@PathParam("name") String name, @PathParam("template") String template, @HeaderParam("Y-Audit-Ref") String auditRef) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("delete", "" + name + ":template." + template + "", null); this.delegate.deleteDomainTemplate(context, name, template, auditRef); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.CONFLICT: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource deleteDomainTemplate"); throw typedException(code, e, ResourceError.class); } } } @GET @Path("/domain/{domainName}/check") @Produces(MediaType.APPLICATION_JSON) public DomainDataCheck getDomainDataCheck(@PathParam("domainName") String domainName) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authenticate(); return this.delegate.getDomainDataCheck(context, domainName); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource getDomainDataCheck"); throw typedException(code, e, ResourceError.class); } } } @PUT @Path("/domain/{domainName}/entity/{entityName}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public void putEntity(@PathParam("domainName") String domainName, @PathParam("entityName") String entityName, @HeaderParam("Y-Audit-Ref") String auditRef, Entity entity) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("update", "" + domainName + ":" + entityName + "", null); this.delegate.putEntity(context, domainName, entityName, auditRef, entity); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.CONFLICT: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource putEntity"); throw typedException(code, e, ResourceError.class); } } } @GET @Path("/domain/{domainName}/entity/{entityName}") @Produces(MediaType.APPLICATION_JSON) public Entity getEntity(@PathParam("domainName") String domainName, @PathParam("entityName") String entityName) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authenticate(); return this.delegate.getEntity(context, domainName, entityName); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource getEntity"); throw typedException(code, e, ResourceError.class); } } } @DELETE @Path("/domain/{domainName}/entity/{entityName}") @Produces(MediaType.APPLICATION_JSON) public void deleteEntity(@PathParam("domainName") String domainName, @PathParam("entityName") String entityName, @HeaderParam("Y-Audit-Ref") String auditRef) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("delete", "" + domainName + ":" + entityName + "", null); this.delegate.deleteEntity(context, domainName, entityName, auditRef); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.CONFLICT: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource deleteEntity"); throw typedException(code, e, ResourceError.class); } } } @GET @Path("/domain/{domainName}/entity") @Produces(MediaType.APPLICATION_JSON) public EntityList getEntityList(@PathParam("domainName") String domainName) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authenticate(); return this.delegate.getEntityList(context, domainName); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource getEntityList"); throw typedException(code, e, ResourceError.class); } } } @GET @Path("/domain/{domainName}/role") @Produces(MediaType.APPLICATION_JSON) public RoleList getRoleList(@PathParam("domainName") String domainName, @QueryParam("limit") Integer limit, @QueryParam("skip") String skip) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authenticate(); return this.delegate.getRoleList(context, domainName, limit, skip); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource getRoleList"); throw typedException(code, e, ResourceError.class); } } } @GET @Path("/domain/{domainName}/roles") @Produces(MediaType.APPLICATION_JSON) public Roles getRoles(@PathParam("domainName") String domainName, @QueryParam("members") @DefaultValue("false") Boolean members) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authenticate(); return this.delegate.getRoles(context, domainName, members); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource getRoles"); throw typedException(code, e, ResourceError.class); } } } @GET @Path("/domain/{domainName}/role/{roleName}") @Produces(MediaType.APPLICATION_JSON) public Role getRole(@PathParam("domainName") String domainName, @PathParam("roleName") String roleName, @QueryParam("auditLog") @DefaultValue("false") Boolean auditLog, @QueryParam("expand") @DefaultValue("false") Boolean expand) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authenticate(); return this.delegate.getRole(context, domainName, roleName, auditLog, expand); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource getRole"); throw typedException(code, e, ResourceError.class); } } } @PUT @Path("/domain/{domainName}/role/{roleName}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public void putRole(@PathParam("domainName") String domainName, @PathParam("roleName") String roleName, @HeaderParam("Y-Audit-Ref") String auditRef, Role role) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("update", "" + domainName + ":role." + roleName + "", null); this.delegate.putRole(context, domainName, roleName, auditRef, role); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.CONFLICT: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource putRole"); throw typedException(code, e, ResourceError.class); } } } @DELETE @Path("/domain/{domainName}/role/{roleName}") @Produces(MediaType.APPLICATION_JSON) public void deleteRole(@PathParam("domainName") String domainName, @PathParam("roleName") String roleName, @HeaderParam("Y-Audit-Ref") String auditRef) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("delete", "" + domainName + ":role." + roleName + "", null); this.delegate.deleteRole(context, domainName, roleName, auditRef); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.CONFLICT: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource deleteRole"); throw typedException(code, e, ResourceError.class); } } } @GET @Path("/domain/{domainName}/role/{roleName}/member/{memberName}") @Produces(MediaType.APPLICATION_JSON) public Membership getMembership(@PathParam("domainName") String domainName, @PathParam("roleName") String roleName, @PathParam("memberName") String memberName) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authenticate(); return this.delegate.getMembership(context, domainName, roleName, memberName); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource getMembership"); throw typedException(code, e, ResourceError.class); } } } @GET @Path("/domain/{domainName}/member") @Produces(MediaType.APPLICATION_JSON) public DomainRoleMembers getDomainRoleMembers(@PathParam("domainName") String domainName) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authenticate(); return this.delegate.getDomainRoleMembers(context, domainName); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource getDomainRoleMembers"); throw typedException(code, e, ResourceError.class); } } } @PUT @Path("/domain/{domainName}/role/{roleName}/member/{memberName}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public void putMembership(@PathParam("domainName") String domainName, @PathParam("roleName") String roleName, @PathParam("memberName") String memberName, @HeaderParam("Y-Audit-Ref") String auditRef, Membership membership) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("update", "" + domainName + ":role." + roleName + "", null); this.delegate.putMembership(context, domainName, roleName, memberName, auditRef, membership); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.CONFLICT: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource putMembership"); throw typedException(code, e, ResourceError.class); } } } @DELETE @Path("/domain/{domainName}/role/{roleName}/member/{memberName}") @Produces(MediaType.APPLICATION_JSON) public void deleteMembership(@PathParam("domainName") String domainName, @PathParam("roleName") String roleName, @PathParam("memberName") String memberName, @HeaderParam("Y-Audit-Ref") String auditRef) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("update", "" + domainName + ":role." + roleName + "", null); this.delegate.deleteMembership(context, domainName, roleName, memberName, auditRef); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.CONFLICT: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource deleteMembership"); throw typedException(code, e, ResourceError.class); } } } @PUT @Path("/domain/{domainName}/admins") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public void putDefaultAdmins(@PathParam("domainName") String domainName, @HeaderParam("Y-Audit-Ref") String auditRef, DefaultAdmins defaultAdmins) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("update", "sys.auth:domain", null); this.delegate.putDefaultAdmins(context, domainName, auditRef, defaultAdmins); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource putDefaultAdmins"); throw typedException(code, e, ResourceError.class); } } } @PUT @Path("/domain/{domainName}/role/{roleName}/meta/system/{attribute}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public void putRoleSystemMeta(@PathParam("domainName") String domainName, @PathParam("roleName") String roleName, @PathParam("attribute") String attribute, @HeaderParam("Y-Audit-Ref") String auditRef, RoleSystemMeta detail) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("update", "sys.auth:role.meta." + attribute + "." + domainName + "", null); this.delegate.putRoleSystemMeta(context, domainName, roleName, attribute, auditRef, detail); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.CONFLICT: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource putRoleSystemMeta"); throw typedException(code, e, ResourceError.class); } } } @GET @Path("/domain/{domainName}/policy") @Produces(MediaType.APPLICATION_JSON) public PolicyList getPolicyList(@PathParam("domainName") String domainName, @QueryParam("limit") Integer limit, @QueryParam("skip") String skip) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authenticate(); return this.delegate.getPolicyList(context, domainName, limit, skip); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource getPolicyList"); throw typedException(code, e, ResourceError.class); } } } @GET @Path("/domain/{domainName}/policies") @Produces(MediaType.APPLICATION_JSON) public Policies getPolicies(@PathParam("domainName") String domainName, @QueryParam("assertions") @DefaultValue("false") Boolean assertions) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authenticate(); return this.delegate.getPolicies(context, domainName, assertions); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource getPolicies"); throw typedException(code, e, ResourceError.class); } } } @GET @Path("/domain/{domainName}/policy/{policyName}") @Produces(MediaType.APPLICATION_JSON) public Policy getPolicy(@PathParam("domainName") String domainName, @PathParam("policyName") String policyName) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authenticate(); return this.delegate.getPolicy(context, domainName, policyName); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource getPolicy"); throw typedException(code, e, ResourceError.class); } } } @PUT @Path("/domain/{domainName}/policy/{policyName}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public void putPolicy(@PathParam("domainName") String domainName, @PathParam("policyName") String policyName, @HeaderParam("Y-Audit-Ref") String auditRef, Policy policy) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("update", "" + domainName + ":policy." + policyName + "", null); this.delegate.putPolicy(context, domainName, policyName, auditRef, policy); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.CONFLICT: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource putPolicy"); throw typedException(code, e, ResourceError.class); } } } @DELETE @Path("/domain/{domainName}/policy/{policyName}") @Produces(MediaType.APPLICATION_JSON) public void deletePolicy(@PathParam("domainName") String domainName, @PathParam("policyName") String policyName, @HeaderParam("Y-Audit-Ref") String auditRef) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("delete", "" + domainName + ":policy." + policyName + "", null); this.delegate.deletePolicy(context, domainName, policyName, auditRef); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.CONFLICT: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource deletePolicy"); throw typedException(code, e, ResourceError.class); } } } @GET @Path("/domain/{domainName}/policy/{policyName}/assertion/{assertionId}") @Produces(MediaType.APPLICATION_JSON) public Assertion getAssertion(@PathParam("domainName") String domainName, @PathParam("policyName") String policyName, @PathParam("assertionId") Long assertionId) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authenticate(); return this.delegate.getAssertion(context, domainName, policyName, assertionId); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource getAssertion"); throw typedException(code, e, ResourceError.class); } } } @PUT @Path("/domain/{domainName}/policy/{policyName}/assertion") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Assertion putAssertion(@PathParam("domainName") String domainName, @PathParam("policyName") String policyName, @HeaderParam("Y-Audit-Ref") String auditRef, Assertion assertion) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("update", "" + domainName + ":policy." + policyName + "", null); return this.delegate.putAssertion(context, domainName, policyName, auditRef, assertion); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.CONFLICT: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource putAssertion"); throw typedException(code, e, ResourceError.class); } } } @DELETE @Path("/domain/{domainName}/policy/{policyName}/assertion/{assertionId}") @Produces(MediaType.APPLICATION_JSON) public void deleteAssertion(@PathParam("domainName") String domainName, @PathParam("policyName") String policyName, @PathParam("assertionId") Long assertionId, @HeaderParam("Y-Audit-Ref") String auditRef) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("update", "" + domainName + ":policy." + policyName + "", null); this.delegate.deleteAssertion(context, domainName, policyName, assertionId, auditRef); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.CONFLICT: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource deleteAssertion"); throw typedException(code, e, ResourceError.class); } } } @PUT @Path("/domain/{domain}/service/{service}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public void putServiceIdentity(@PathParam("domain") String domain, @PathParam("service") String service, @HeaderParam("Y-Audit-Ref") String auditRef, ServiceIdentity detail) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("update", "" + domain + ":service." + service + "", null); this.delegate.putServiceIdentity(context, domain, service, auditRef, detail); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.CONFLICT: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource putServiceIdentity"); throw typedException(code, e, ResourceError.class); } } } @GET @Path("/domain/{domain}/service/{service}") @Produces(MediaType.APPLICATION_JSON) public ServiceIdentity getServiceIdentity(@PathParam("domain") String domain, @PathParam("service") String service) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authenticate(); return this.delegate.getServiceIdentity(context, domain, service); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource getServiceIdentity"); throw typedException(code, e, ResourceError.class); } } } @DELETE @Path("/domain/{domain}/service/{service}") @Produces(MediaType.APPLICATION_JSON) public void deleteServiceIdentity(@PathParam("domain") String domain, @PathParam("service") String service, @HeaderParam("Y-Audit-Ref") String auditRef) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("delete", "" + domain + ":service." + service + "", null); this.delegate.deleteServiceIdentity(context, domain, service, auditRef); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.CONFLICT: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource deleteServiceIdentity"); throw typedException(code, e, ResourceError.class); } } } @GET @Path("/domain/{domainName}/services") @Produces(MediaType.APPLICATION_JSON) public ServiceIdentities getServiceIdentities(@PathParam("domainName") String domainName, @QueryParam("publickeys") @DefaultValue("false") Boolean publickeys, @QueryParam("hosts") @DefaultValue("false") Boolean hosts) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authenticate(); return this.delegate.getServiceIdentities(context, domainName, publickeys, hosts); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource getServiceIdentities"); throw typedException(code, e, ResourceError.class); } } } @GET @Path("/domain/{domainName}/service") @Produces(MediaType.APPLICATION_JSON) public ServiceIdentityList getServiceIdentityList(@PathParam("domainName") String domainName, @QueryParam("limit") Integer limit, @QueryParam("skip") String skip) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authenticate(); return this.delegate.getServiceIdentityList(context, domainName, limit, skip); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource getServiceIdentityList"); throw typedException(code, e, ResourceError.class); } } } @GET @Path("/domain/{domain}/service/{service}/publickey/{id}") @Produces(MediaType.APPLICATION_JSON) public PublicKeyEntry getPublicKeyEntry(@PathParam("domain") String domain, @PathParam("service") String service, @PathParam("id") String id) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authenticate(); return this.delegate.getPublicKeyEntry(context, domain, service, id); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource getPublicKeyEntry"); throw typedException(code, e, ResourceError.class); } } } @PUT @Path("/domain/{domain}/service/{service}/publickey/{id}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public void putPublicKeyEntry(@PathParam("domain") String domain, @PathParam("service") String service, @PathParam("id") String id, @HeaderParam("Y-Audit-Ref") String auditRef, PublicKeyEntry publicKeyEntry) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("update", "" + domain + ":service." + service + "", null); this.delegate.putPublicKeyEntry(context, domain, service, id, auditRef, publicKeyEntry); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.CONFLICT: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource putPublicKeyEntry"); throw typedException(code, e, ResourceError.class); } } } @DELETE @Path("/domain/{domain}/service/{service}/publickey/{id}") @Produces(MediaType.APPLICATION_JSON) public void deletePublicKeyEntry(@PathParam("domain") String domain, @PathParam("service") String service, @PathParam("id") String id, @HeaderParam("Y-Audit-Ref") String auditRef) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("update", "" + domain + ":service." + service + "", null); this.delegate.deletePublicKeyEntry(context, domain, service, id, auditRef); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.CONFLICT: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource deletePublicKeyEntry"); throw typedException(code, e, ResourceError.class); } } } @PUT @Path("/domain/{domain}/tenancy/{service}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public void putTenancy(@PathParam("domain") String domain, @PathParam("service") String service, @HeaderParam("Y-Audit-Ref") String auditRef, Tenancy detail) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("update", "" + domain + ":tenancy", null); this.delegate.putTenancy(context, domain, service, auditRef, detail); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.CONFLICT: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource putTenancy"); throw typedException(code, e, ResourceError.class); } } } @DELETE @Path("/domain/{domain}/tenancy/{service}") @Produces(MediaType.APPLICATION_JSON) public void deleteTenancy(@PathParam("domain") String domain, @PathParam("service") String service, @HeaderParam("Y-Audit-Ref") String auditRef) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("delete", "" + domain + ":tenancy", null); this.delegate.deleteTenancy(context, domain, service, auditRef); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.CONFLICT: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource deleteTenancy"); throw typedException(code, e, ResourceError.class); } } } @PUT @Path("/domain/{domain}/service/{service}/tenant/{tenantDomain}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public void putTenant(@PathParam("domain") String domain, @PathParam("service") String service, @PathParam("tenantDomain") String tenantDomain, @HeaderParam("Y-Audit-Ref") String auditRef, Tenancy detail) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("update", "" + domain + ":tenant." + service + "", null); this.delegate.putTenant(context, domain, service, tenantDomain, auditRef, detail); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.CONFLICT: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource putTenant"); throw typedException(code, e, ResourceError.class); } } } @DELETE @Path("/domain/{domain}/service/{service}/tenant/{tenantDomain}") @Produces(MediaType.APPLICATION_JSON) public void deleteTenant(@PathParam("domain") String domain, @PathParam("service") String service, @PathParam("tenantDomain") String tenantDomain, @HeaderParam("Y-Audit-Ref") String auditRef) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("delete", "" + domain + ":tenant." + service + "", null); this.delegate.deleteTenant(context, domain, service, tenantDomain, auditRef); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.CONFLICT: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource deleteTenant"); throw typedException(code, e, ResourceError.class); } } } @PUT @Path("/domain/{domain}/service/{service}/tenant/{tenantDomain}/resourceGroup/{resourceGroup}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public TenantResourceGroupRoles putTenantResourceGroupRoles(@PathParam("domain") String domain, @PathParam("service") String service, @PathParam("tenantDomain") String tenantDomain, @PathParam("resourceGroup") String resourceGroup, @HeaderParam("Y-Audit-Ref") String auditRef, TenantResourceGroupRoles detail) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("update", "" + domain + ":tenant." + service + "", null); return this.delegate.putTenantResourceGroupRoles(context, domain, service, tenantDomain, resourceGroup, auditRef, detail); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.CONFLICT: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource putTenantResourceGroupRoles"); throw typedException(code, e, ResourceError.class); } } } @GET @Path("/domain/{domain}/service/{service}/tenant/{tenantDomain}/resourceGroup/{resourceGroup}") @Produces(MediaType.APPLICATION_JSON) public TenantResourceGroupRoles getTenantResourceGroupRoles(@PathParam("domain") String domain, @PathParam("service") String service, @PathParam("tenantDomain") String tenantDomain, @PathParam("resourceGroup") String resourceGroup) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authenticate(); return this.delegate.getTenantResourceGroupRoles(context, domain, service, tenantDomain, resourceGroup); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource getTenantResourceGroupRoles"); throw typedException(code, e, ResourceError.class); } } } @DELETE @Path("/domain/{domain}/service/{service}/tenant/{tenantDomain}/resourceGroup/{resourceGroup}") @Produces(MediaType.APPLICATION_JSON) public void deleteTenantResourceGroupRoles(@PathParam("domain") String domain, @PathParam("service") String service, @PathParam("tenantDomain") String tenantDomain, @PathParam("resourceGroup") String resourceGroup, @HeaderParam("Y-Audit-Ref") String auditRef) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("update", "" + domain + ":tenant." + service + "", null); this.delegate.deleteTenantResourceGroupRoles(context, domain, service, tenantDomain, resourceGroup, auditRef); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.CONFLICT: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource deleteTenantResourceGroupRoles"); throw typedException(code, e, ResourceError.class); } } } @PUT @Path("/domain/{tenantDomain}/provDomain/{provDomain}/provService/{provService}/resourceGroup/{resourceGroup}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public ProviderResourceGroupRoles putProviderResourceGroupRoles(@PathParam("tenantDomain") String tenantDomain, @PathParam("provDomain") String provDomain, @PathParam("provService") String provService, @PathParam("resourceGroup") String resourceGroup, @HeaderParam("Y-Audit-Ref") String auditRef, ProviderResourceGroupRoles detail) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("update", "" + tenantDomain + ":tenancy." + provDomain + "." + provService + "", null); return this.delegate.putProviderResourceGroupRoles(context, tenantDomain, provDomain, provService, resourceGroup, auditRef, detail); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.CONFLICT: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource putProviderResourceGroupRoles"); throw typedException(code, e, ResourceError.class); } } } @GET @Path("/domain/{tenantDomain}/provDomain/{provDomain}/provService/{provService}/resourceGroup/{resourceGroup}") @Produces(MediaType.APPLICATION_JSON) public ProviderResourceGroupRoles getProviderResourceGroupRoles(@PathParam("tenantDomain") String tenantDomain, @PathParam("provDomain") String provDomain, @PathParam("provService") String provService, @PathParam("resourceGroup") String resourceGroup) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authenticate(); return this.delegate.getProviderResourceGroupRoles(context, tenantDomain, provDomain, provService, resourceGroup); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource getProviderResourceGroupRoles"); throw typedException(code, e, ResourceError.class); } } } @DELETE @Path("/domain/{tenantDomain}/provDomain/{provDomain}/provService/{provService}/resourceGroup/{resourceGroup}") @Produces(MediaType.APPLICATION_JSON) public void deleteProviderResourceGroupRoles(@PathParam("tenantDomain") String tenantDomain, @PathParam("provDomain") String provDomain, @PathParam("provService") String provService, @PathParam("resourceGroup") String resourceGroup, @HeaderParam("Y-Audit-Ref") String auditRef) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("update", "" + tenantDomain + ":tenancy." + provDomain + "." + provService + "", null); this.delegate.deleteProviderResourceGroupRoles(context, tenantDomain, provDomain, provService, resourceGroup, auditRef); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.CONFLICT: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource deleteProviderResourceGroupRoles"); throw typedException(code, e, ResourceError.class); } } } @GET @Path("/access/{action}/{resource}") @Produces(MediaType.APPLICATION_JSON) public Access getAccess(@PathParam("action") String action, @PathParam("resource") String resource, @QueryParam("domain") String domain, @QueryParam("principal") String checkPrincipal) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authenticate(); return this.delegate.getAccess(context, action, resource, domain, checkPrincipal); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource getAccess"); throw typedException(code, e, ResourceError.class); } } } @GET @Path("/access/{action}") @Produces(MediaType.APPLICATION_JSON) public Access getAccessExt(@PathParam("action") String action, @QueryParam("resource") String resource, @QueryParam("domain") String domain, @QueryParam("principal") String checkPrincipal) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authenticate(); return this.delegate.getAccessExt(context, action, resource, domain, checkPrincipal); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource getAccessExt"); throw typedException(code, e, ResourceError.class); } } } @GET @Path("/resource") @Produces(MediaType.APPLICATION_JSON) public ResourceAccessList getResourceAccessList(@QueryParam("principal") String principal, @QueryParam("action") String action) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authenticate(); return this.delegate.getResourceAccessList(context, principal, action); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource getResourceAccessList"); throw typedException(code, e, ResourceError.class); } } } @GET @Path("/sys/modified_domains") @Produces(MediaType.APPLICATION_JSON) public Response getSignedDomains(@QueryParam("domain") String domain, @QueryParam("metaonly") String metaOnly, @QueryParam("metaattr") String metaAttr, @HeaderParam("If-None-Match") String matchingTag) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authenticate(); return this.delegate.getSignedDomains(context, domain, metaOnly, metaAttr, matchingTag); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource getSignedDomains"); throw typedException(code, e, ResourceError.class); } } } @GET @Path("/user/{userName}/token") @Produces(MediaType.APPLICATION_JSON) public UserToken getUserToken(@PathParam("userName") String userName, @QueryParam("services") String serviceNames, @QueryParam("header") @DefaultValue("false") Boolean header) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authenticate(); return this.delegate.getUserToken(context, userName, serviceNames, header); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource getUserToken"); throw typedException(code, e, ResourceError.class); } } } @OPTIONS @Path("/user/{userName}/token") public UserToken optionsUserToken(@PathParam("userName") String userName, @QueryParam("services") String serviceNames) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); return this.delegate.optionsUserToken(context, userName, serviceNames); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource optionsUserToken"); throw typedException(code, e, ResourceError.class); } } } @GET @Path("/principal") @Produces(MediaType.APPLICATION_JSON) public ServicePrincipal getServicePrincipal() { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authenticate(); return this.delegate.getServicePrincipal(context); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource getServicePrincipal"); throw typedException(code, e, ResourceError.class); } } } @GET @Path("/template") @Produces(MediaType.APPLICATION_JSON) public ServerTemplateList getServerTemplateList() { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authenticate(); return this.delegate.getServerTemplateList(context); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource getServerTemplateList"); throw typedException(code, e, ResourceError.class); } } } @GET @Path("/template/{template}") @Produces(MediaType.APPLICATION_JSON) public Template getTemplate(@PathParam("template") String template) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authenticate(); return this.delegate.getTemplate(context, template); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource getTemplate"); throw typedException(code, e, ResourceError.class); } } } @GET @Path("/user") @Produces(MediaType.APPLICATION_JSON) public UserList getUserList() { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authenticate(); return this.delegate.getUserList(context); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource getUserList"); throw typedException(code, e, ResourceError.class); } } } @DELETE @Path("/user/{name}") @Produces(MediaType.APPLICATION_JSON) public void deleteUser(@PathParam("name") String name, @HeaderParam("Y-Audit-Ref") String auditRef) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("delete", "sys.auth:user", null); this.delegate.deleteUser(context, name, auditRef); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.CONFLICT: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource deleteUser"); throw typedException(code, e, ResourceError.class); } } } @DELETE @Path("/domain/{domainName}/member/{memberName}") @Produces(MediaType.APPLICATION_JSON) public void deleteDomainRoleMember(@PathParam("domainName") String domainName, @PathParam("memberName") String memberName, @HeaderParam("Y-Audit-Ref") String auditRef) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("update", "" + domainName + ":", null); this.delegate.deleteDomainRoleMember(context, domainName, memberName, auditRef); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.CONFLICT: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.TOO_MANY_REQUESTS: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource deleteDomainRoleMember"); throw typedException(code, e, ResourceError.class); } } } @GET @Path("/domain/{name}/quota") @Produces(MediaType.APPLICATION_JSON) public Quota getQuota(@PathParam("name") String name) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authenticate(); return this.delegate.getQuota(context, name); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource getQuota"); throw typedException(code, e, ResourceError.class); } } } @PUT @Path("/domain/{name}/quota") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public void putQuota(@PathParam("name") String name, @HeaderParam("Y-Audit-Ref") String auditRef, Quota quota) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("update", "sys.auth:quota", null); this.delegate.putQuota(context, name, auditRef, quota); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.CONFLICT: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource putQuota"); throw typedException(code, e, ResourceError.class); } } } @DELETE @Path("/domain/{name}/quota") @Produces(MediaType.APPLICATION_JSON) public void deleteQuota(@PathParam("name") String name, @HeaderParam("Y-Audit-Ref") String auditRef) { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authorize("update", "sys.auth:quota", null); this.delegate.deleteQuota(context, name, auditRef); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.CONFLICT: throw typedException(code, e, ResourceError.class); case ResourceException.FORBIDDEN: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource deleteQuota"); throw typedException(code, e, ResourceError.class); } } } @GET @Path("/status") @Produces(MediaType.APPLICATION_JSON) public Status getStatus() { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authenticate(); return this.delegate.getStatus(context); } catch (ResourceException e) { int code = e.getCode(); switch (code) { case ResourceException.BAD_REQUEST: throw typedException(code, e, ResourceError.class); case ResourceException.NOT_FOUND: throw typedException(code, e, ResourceError.class); case ResourceException.UNAUTHORIZED: throw typedException(code, e, ResourceError.class); default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource getStatus"); throw typedException(code, e, ResourceError.class); } } } @GET @Path("/schema") @Produces(MediaType.APPLICATION_JSON) public Schema getRdlSchema() { try { ResourceContext context = this.delegate.newResourceContext(this.request, this.response); context.authenticate(); return this.delegate.getRdlSchema(context); } catch (ResourceException e) { int code = e.getCode(); switch (code) { default: System.err.println("*** Warning: undeclared exception (" + code + ") for resource getRdlSchema"); throw typedException(code, e, ResourceError.class); } } } WebApplicationException typedException(int code, ResourceException e, Class<?> eClass) { Object data = e.getData(); Object entity = eClass.isInstance(data) ? data : null; if (entity != null) { return new WebApplicationException(Response.status(code).entity(entity).build()); } else { return new WebApplicationException(code); } } @Inject private ZMSHandler delegate; @Context private HttpServletRequest request; @Context private HttpServletResponse response; }
apache-2.0
CCI-MOC/python-novaclient
novaclient/openstack/common/_i18n.py
1432
# 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. """oslo.i18n integration module. See http://docs.openstack.org/developer/oslo.i18n/usage.html """ import oslo.i18n # NOTE(dhellmann): This reference to o-s-l-o will be replaced by the # application name when this module is synced into the separate # repository. It is OK to have more than one translation function # using the same domain, since there will still only be one message # catalog. _translators = oslo.i18n.TranslatorFactory(domain='novaclient') # The primary translation function using the well-known name "_" _ = _translators.primary # Translators for log levels. # # The abbreviated names are meant to reflect the usual use of a short # name like '_'. The "L" is for "log" and the other letter comes from # the level. _LI = _translators.log_info _LW = _translators.log_warning _LE = _translators.log_error _LC = _translators.log_critical
apache-2.0
OnApp/cloudnet
spec/models/invoice_item_spec.rb
2904
require 'rails_helper' describe InvoiceItem do let (:invoice_item) { FactoryGirl.create(:invoice_item) } it 'should be valid' do expect(invoice_item).to be_valid end it 'should not have any attributes related to cost assigned to it' do expect(invoice_item.read_attribute(:net_cost)).to be_nil expect(invoice_item.read_attribute(:tax_cost)).to be_nil end describe 'Costs' do it 'should calculate net cost dynamically' do # invoice_item.net_cost.should == 5 * 10 * 20 end it 'should calculate tax cost dynamically' do # invoice_item.tax_cost.should == 5 * 10 * 20 * invoice_item.tax_rate end it 'should calculate total cost dynamically' do invoice_item.net_cost = Random.rand(1_000_000) invoice_item.tax_cost = Random.rand(1_000_000) expect(invoice_item.total_cost).to eq(invoice_item.net_cost + invoice_item.tax_cost) end it 'should allow the override of net cost' do expect(invoice_item.net_cost).to eq(0) invoice_item.net_cost = 3000 expect(invoice_item.net_cost).to eq(3000) end it 'should allow the override of tax cost' do expect(invoice_item.tax_cost).to eq(0) invoice_item.tax_cost = 3000 expect(invoice_item.tax_cost).to eq(3000) end end it 'should have a tax rate equivalent to that of the invoice if not VAT exempt' do invoice = invoice_item.invoice allow(invoice).to receive_messages(vat_exempt?: false) expect(invoice_item.tax_rate).to eq(Invoice::TAX_RATE) end it 'should have a tax rate of zero if VAT Exempt in invoice' do invoice = invoice_item.invoice allow(invoice).to receive_messages(vat_exempt?: true) expect(invoice_item.tax_rate).to eq(0.0) end it 'should determine tax code from invoice' do expect(invoice_item.tax_code).to eq(invoice_item.invoice.tax_code) allow(invoice_item.invoice).to receive_messages(tax_code: 'abcd1234') expect(invoice_item.tax_code).to eq('abcd1234') end describe 'metadata' do it 'should assign and parse metadata and return it in the format it went in' do invoice_item.metadata = [{ abc: 123, de: 456 }] expect(invoice_item.metadata).to eq([{ abc: 123, de: 456 }]) end it 'should return an empty array for empty metadata' do invoice_item.metadata = nil expect(invoice_item.metadata).to eq([]) end end it 'should attempt to find the source of an object' do invoice = FactoryGirl.create(:invoice) invoice_item.source = invoice expect(invoice_item.source_id).to eq(invoice.id) expect(invoice_item.source_type).to eq(invoice.class.to_s) expect(invoice_item.source).to eq(invoice) end it 'should set the source class to the class of the source object' do obj = double('TestClass', id: 10) invoice_item.source = obj expect(invoice_item.source_type).to eq(obj.class.to_s) end end
apache-2.0
Sellegit/j2objc
translator/src/test/java/com/google/devtools/j2objc/gen/StatementGeneratorTest.java
82156
/* * 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. */ package com.google.devtools.j2objc.gen; import com.google.devtools.j2objc.GenerationTest; import com.google.devtools.j2objc.Options; import com.google.devtools.j2objc.Options.MemoryManagementOption; import com.google.devtools.j2objc.ast.Statement; import java.io.IOException; import java.util.List; /** * Tests for {@link StatementGenerator}. * * @author Tom Ball */ public class StatementGeneratorTest extends GenerationTest { @Override protected void tearDown() throws Exception { Options.resetMemoryManagementOption(); super.tearDown(); } // Verify that return statements output correctly for reserved words. public void testReturnReservedWord() throws IOException { String translation = translateSourceFile( "public class Test { static final String BOOL = \"bool\"; String test() { return BOOL; }}", "Test", "Test.m"); assertTranslation(translation, "return Test_BOOL__;"); } // Verify that both a class and interface type invoke getClass() correctly. public void testGetClass() throws IOException { String translation = translateSourceFile( "import java.util.*; public class A {" + " void test(ArrayList one, List two) { " + " Class<?> classOne = one.getClass();" + " Class<?> classTwo = two.getClass(); }}", "A", "A.m"); assertTranslation(translation, "[((JavaUtilArrayList *) nil_chk(one)) getClass]"); assertTranslation(translation, "[((id<JavaUtilList>) nil_chk(two)) getClass]"); } public void testEnumConstantsInSwitchStatement() throws IOException { String translation = translateSourceFile( "public class A { static enum EnumType { ONE, TWO }" + "public static void doSomething(EnumType e) {" + " switch (e) { case ONE: break; case TWO: break; }}}", "A", "A.m"); assertTranslation(translation, "switch ([e ordinal]) {"); assertTranslation(translation, "case A_EnumType_ONE:"); } public void testEnumConstantReferences() throws IOException { String translation = translateSourceFile( "public class A { static enum B { ONE, TWO; " + "public static B doSomething(boolean b) { return b ? ONE : TWO; }}}", "A", "A.m"); assertTranslation(translation, "return b ? A_BEnum_ONE : A_BEnum_TWO;"); } public void testInnerClassFQN() throws IOException { String translation = translateSourceFile( "package com.example.foo; " + "public class Foo { static class Inner { public static void doSomething() {} }}" + "class Bar { public static void mumber() { Foo.Inner.doSomething(); }}", "Foo", "com/example/foo/Foo.m"); assertTranslation(translation, "ComExampleFooFoo_Inner_doSomething();"); } public void testLocalVariableTranslation() throws IOException { String source = "Exception e;"; List<Statement> stmts = translateStatements(source); assertEquals(1, stmts.size()); String result = generateStatement(stmts.get(0)); assertEquals("JavaLangException *e;", result); } public void testClassCreationTranslation() throws IOException { String source = "new Exception(\"test\");"; List<Statement> stmts = translateStatements(source); assertEquals(1, stmts.size()); String result = generateStatement(stmts.get(0)); assertEquals("[new_JavaLangException_initWithNSString_(@\"test\") autorelease];", result); } public void testParameterTranslation() throws IOException { String source = "Throwable cause = new Throwable(); new Exception(cause);"; List<Statement> stmts = translateStatements(source); assertEquals(2, stmts.size()); String result = generateStatement(stmts.get(1)); assertEquals( "[new_JavaLangException_initWithJavaLangThrowable_(cause) autorelease];", result); } public void testCastTranslation() throws IOException { String source = "Object o = new Object(); Throwable t = (Throwable) o; int[] i = (int[]) o;"; List<Statement> stmts = translateStatements(source); assertEquals(3, stmts.size()); String result = generateStatement(stmts.get(1)); assertEquals("JavaLangThrowable *t = " + "(JavaLangThrowable *) check_class_cast(o, [JavaLangThrowable class]);", result); result = generateStatement(stmts.get(2)); assertEquals("IOSIntArray *i = " + "(IOSIntArray *) check_class_cast(o, [IOSIntArray class]);", result); } public void testInterfaceCastTranslation() throws IOException { String source = "java.util.Collection al = new java.util.ArrayList(); " + "java.util.List l = (java.util.List) al;"; List<Statement> stmts = translateStatements(source); assertEquals(2, stmts.size()); String result = generateStatement(stmts.get(1)); assertEquals("id<JavaUtilList> l = " + "(id<JavaUtilList>) check_protocol_cast(al, @protocol(JavaUtilList));", result); } public void testCatchTranslation() throws IOException { String source = "try { ; } catch (Exception e) {}"; List<Statement> stmts = translateStatements(source); assertEquals(1, stmts.size()); String result = generateStatement(stmts.get(0)); assertEquals("@try {\n;\n}\n @catch (JavaLangException *e) {\n}", result); } public void testInstanceOfTranslation() throws IOException { String source = "Exception e = new Exception(); if (e instanceof Throwable) {}"; List<Statement> stmts = translateStatements(source); assertEquals(2, stmts.size()); String result = generateStatement(stmts.get(1)); assertEquals("if ([e isKindOfClass:[JavaLangThrowable class]]) {\n}", result); } public void testFullyQualifiedTypeTranslation() throws IOException { String source = "java.lang.Exception e = null;"; List<Statement> stmts = translateStatements(source); assertEquals(1, stmts.size()); String result = generateStatement(stmts.get(0)); assertEquals("JavaLangException *e = nil;", result); } public void testToStringRenaming() throws IOException { String source = "Object o = new Object(); o.toString(); toString();"; List<Statement> stmts = translateStatements(source); assertEquals(3, stmts.size()); String result = generateStatement(stmts.get(1)); assertEquals("[o description];", result); result = generateStatement(stmts.get(2)); assertEquals("[self description];", result); } public void testSuperToStringRenaming() throws IOException { String translation = translateSourceFile( "public class Example { public String toString() { return super.toString(); } }", "Example", "Example.m"); assertTranslation(translation, "return [super description];"); } public void testAccessPublicConstant() throws IOException { String translation = translateSourceFile( "public class Example { public static final int FOO=1; int foo; { foo = FOO; } }", "Example", "Example.m"); assertTranslation(translation, "foo_ = Example_FOO;"); } public void testAccessPublicConstant2() throws IOException { String translation = translateSourceFile( "public class Example { public static final int FOO=1;" + "int test() { int foo = FOO; return foo;} }", "Example", "Example.m"); assertTranslation(translation, "foo = Example_FOO;"); } public void testAccessPrivateConstant() throws IOException { String translation = translateSourceFile( "public class Example { private static final int FOO=1;" + "int test() { int foo = FOO; return foo;} }", "Example", "Example.m"); assertTranslation(translation, "foo = Example_FOO;"); } public void testAccessExternalConstant() throws IOException { String translation = translateSourceFile( "public class Example { static class Bar { public static final int FOO=1; } " + "int foo; { foo = Bar.FOO; } }", "Example", "Example.m"); assertTranslation(translation, "foo_ = Example_Bar_FOO;"); assertFalse(translation.contains("int Example_Bar_FOO_ = 1;")); translation = getTranslatedFile("Example.h"); assertTranslation(translation, "#define Example_Bar_FOO 1"); } public void testAccessExternalStringConstant() throws IOException { String translation = translateSourceFile( "public class Example { static class Bar { public static final String FOO=\"Mumble\"; } " + "String foo; { foo = Bar.FOO; } }", "Example", "Example.m"); assertTranslation(translation, "Example_set_foo_(self, Example_Bar_get_FOO_())"); assertTranslation(translation, "NSString *Example_Bar_FOO_ = @\"Mumble\";"); translation = getTranslatedFile("Example.h"); assertTranslation(translation, "FOUNDATION_EXPORT NSString *Example_Bar_FOO_;"); assertTranslation(translation, "J2OBJC_STATIC_FIELD_GETTER(Example_Bar, FOO_, NSString *)"); } public void testMultipleVariableDeclarations() throws IOException { String source = "String one, two;"; List<Statement> stmts = translateStatements(source); assertEquals(1, stmts.size()); String result = generateStatement(stmts.get(0)); assertEquals("NSString *one, *two;", result); } public void testObjectDeclaration() throws IOException { List<Statement> stmts = translateStatements("Object o;"); assertEquals(1, stmts.size()); String result = generateStatement(stmts.get(0)); assertEquals("id o;", result); } public void testStaticBooleanFields() throws IOException { String translation = translateSourceFile( "public class Example { Boolean b1 = Boolean.TRUE; Boolean b2 = Boolean.FALSE; }", "Example", "Example.m"); assertTranslation(translation, "Example_set_b1_(self, JavaLangBoolean_get_TRUE__())"); assertTranslation(translation, "Example_set_b2_(self, JavaLangBoolean_get_FALSE__())"); } public void testStringConcatenation() throws IOException { String translation = translateSourceFile( "public class Example<K,V> { void test() { String s = \"hello, \" + \"world\"; }}", "Example", "Example.m"); assertTranslation(translation, "NSString *s = @\"hello, world\""); } public void testStringConcatenation2() throws IOException { String source = "class A { " + "private static final String A = \"bob\"; " + "private static final char SPACE = ' '; " + "private static final double ANSWER = 22.0 / 2; " + "private static final boolean B = false; " + "private static final String C = " + "\"hello \" + A + ' ' + 3 + SPACE + true + ' ' + ANSWER + ' ' + B; }"; String translation = translateSourceFile(source, "A", "A.m"); assertTranslation(translation, "\"hello bob 3 true 11.0 false\""); } public void testStringConcatenationTypes() throws IOException { String translation = translateSourceFile( "public class Example<K,V> { Object obj; boolean b; char c; double d; float f; int i; " + "long l; short s; String str; public String toString() { " + "return \"obj=\" + obj + \" b=\" + b + \" c=\" + c + \" d=\" + d + \" f=\" + f" + " + \" i=\" + i + \" l=\" + l + \" s=\" + s; }}", "Example", "Example.m"); assertTranslation(translation, "return JreStrcat(\"$@$Z$C$D$F$I$J$S\", @\"obj=\", obj_, @\" b=\", b_, @\" c=\", c_," + " @\" d=\", d_, @\" f=\", f_, @\" i=\", i_, @\" l=\", l_, @\" s=\", s_);"); } public void testStringConcatenationWithLiterals() throws IOException { String translation = translateSourceFile( "public class Example<K,V> { public String toString() { " + "return \"literals: \" + true + \", \" + 'c' + \", \" + 1.0d + \", \" + 3.14 + \", \"" + " + 42 + \", \" + 123L + \", \" + 1; }}", "Example", "Example.m"); assertTranslation(translation, "return @\"literals: true, c, 1.0, 3.14, 42, 123, 1\";"); } public void testStringConcatenationEscaping() throws IOException { String translation = translateSourceFile( "public class Example<K,V> { String s = \"hello, \" + 50 + \"% of the world\\n\"; }", "Example", "Example.m"); assertTranslation(translation, "Example_set_s_(self, @\"hello, 50% of the world\\n\");"); } public void testStringConcatenationMethodInvocation() throws IOException { String translation = translateSourceFile( "public class Test { " + " String getStr() { return \"str\"; } " + " int getInt() { return 42; } " + " void test() { " + " String a = \"foo\" + getStr() + \"bar\" + getInt() + \"baz\"; } }", "Test", "Test.m"); assertTranslation(translation, "JreStrcat(\"$$$I$\", @\"foo\", [self getStr], @\"bar\", [self getInt], @\"baz\")"); } public void testVarargsMethodInvocation() throws IOException { String translation = translateSourceFile("public class Example { " + "public void call() { foo(null); bar(\"\", null, null); }" + "void foo(Object ... args) { }" + "void bar(String firstArg, Object ... varArgs) { }}", "Example", "Example.m"); assertTranslation(translation, "[self fooWithNSObjectArray:"); assertTranslation(translation, "[IOSObjectArray arrayWithObjects:(id[]){ nil, nil } count:2 type:NSObject_class_()]"); assertTranslation(translation, "[self barWithNSString:"); assertTranslation(translation, "withNSObjectArray:"); } public void testVarargsMethodInvocationSingleArg() throws IOException { String translation = translateSourceFile("public class Example { " + "public void call() { foo(1); }" + "void foo(Object ... args) { }}", "Example", "Example.m"); assertTranslation(translation, "[self fooWithNSObjectArray:" + "[IOSObjectArray arrayWithObjects:(id[]){ JavaLangInteger_valueOfWithInt_(1) } count:1 " + "type:NSObject_class_()]];"); } public void testVarargsMethodInvocationPrimitiveArgs() throws IOException { String translation = translateSourceFile( "class Test { void call() { foo(1); } void foo(int... i) {} }", "Test", "Test.m"); assertTranslation(translation, "[self fooWithIntArray:[IOSIntArray arrayWithInts:(jint[]){ 1 } count:1]];"); } public void testStaticInnerSubclassAccessingOuterStaticVar() throws IOException { String translation = translateSourceFile( "public class Test { public static final Object FOO = new Object(); " + "static class Inner { Object test() { return FOO; }}}", "Test", "Test.m"); assertTranslation(translation, "return Test_get_FOO_();"); } public void testReservedIdentifierReference() throws IOException { String translation = translateSourceFile( "public class Test { public int test(int id) { return id; }}", "Test", "Test.m"); assertTranslation(translation, "- (jint)testWithInt:(jint)id_"); assertTranslation(translation, "return id_;"); } public void testReservedTypeQualifierReference() throws IOException { String translation = translateSourceFile( "public class Test { public int test(int in, int out) { return in + out; }}", "Test", "Test.m"); assertTranslation(translation, "- (jint)testWithInt:(jint)inArg"); assertTranslation(translation, "return inArg + outArg;"); } public void testFieldAccess() throws IOException { String translation = translateSourceFile( "import com.google.j2objc.annotations.Weak;" + "public class Test { " + " Object i;" + " @Weak Object j;" + " Test(Object otherI, Object otherJ) {" + " i = otherI;" + " j = otherJ;" + " }" + "}", "Test", "Test.m"); assertTranslation(translation, "Test_set_i_(self, otherI);"); assertTranslation(translation, "j_ = otherJ;"); assertTranslation(translation, "RELEASE_(i_);"); } public void testInnerInnerClassFieldAccess() throws IOException { String translation = translateSourceFile( "public class Test { static class One {} static class Two extends Test { " + "Integer i; Two(Integer i) { this.i = i; } int getI() { return i.intValue(); }}}", "Test", "Test.m"); assertTranslation(translation, "- (instancetype)initWithJavaLangInteger:(JavaLangInteger *)i {"); assertTranslation(translation, "return [((JavaLangInteger *) nil_chk(i_)) intValue];"); } public void testInnerClassSuperConstructor() throws IOException { String translation = translateSourceFile( "public class Test { static class One { int i; One(int i) { this.i = i; }} " + "static class Two extends One { Two(int i) { super(i); }}}", "Test", "Test.m"); assertTranslation(translation, "- (instancetype)initWithInt:(jint)i"); assertTranslatedLines(translation, "void Test_Two_initWithInt_(Test_Two *self, jint i) {", " Test_One_initWithInt_(self, i);", "}"); } public void testStaticInnerClassSuperFieldAccess() throws IOException { String translation = translateSourceFile( "public class Test { protected int foo; " + "static class One extends Test { int i; One() { i = foo; } int test() { return i; }}}", "Test", "Test.m"); assertTranslation(translation, "- (instancetype)init {"); assertTranslation(translation, "self->i_ = self->foo_;"); assertTranslation(translation, "return i_;"); } public void testMethodInvocationOfReturnedInterface() throws IOException { String translation = translateSourceFile( "import java.util.*; public class Test <K,V> { " + "Iterator<Map.Entry<K,V>> iterator; " + "K test() { return iterator.next().getKey(); }}", "Test", "Test.m"); assertTranslation(translation, "return [((id<JavaUtilMap_Entry>) " + "nil_chk([((id<JavaUtilIterator>) nil_chk(iterator_)) next])) getKey];"); } public void testAnonymousClassInInnerStatic() throws IOException { String translation = translateSourceFile( "import java.util.*; public class Test { " + "static <T> Enumeration<T> enumeration(Collection<T> collection) {" + "final Collection<T> c = collection; " + "return new Enumeration<T>() { " + "Iterator<T> it = c.iterator(); " + "public boolean hasMoreElements() { return it.hasNext(); } " + "public T nextElement() { return it.next(); } }; }}", "Test", "Test.m"); assertTranslation(translation, "return [((id<JavaUtilIterator>) nil_chk(it_)) hasNext];"); assertTranslation(translation, "return [((id<JavaUtilIterator>) nil_chk(it_)) next];"); assertFalse(translation.contains("Test *this$0;")); } public void testGenericMethodWithAnonymousReturn() throws IOException { String translation = translateSourceFile( "import java.util.*; public class Test { " + "public static <T> Enumeration<T> enumeration(final Collection<T> collection) {" + "return new Enumeration<T>() {" + " Iterator<T> it = collection.iterator();" + " public boolean hasMoreElements() { return it.hasNext(); }" + " public T nextElement() { return it.next(); }}; }}", "Test", "Test.m"); assertTranslation(translation, "return [new_Test_$1_initWithJavaUtilCollection_(collection) autorelease];"); translation = getTranslatedFile("Test.h"); assertTranslation(translation, "- (instancetype)initWithJavaUtilCollection:(id<JavaUtilCollection>)capture$0;"); assertTranslation(translation, "FOUNDATION_EXPORT Test_$1 *new_Test_$1_initWithJavaUtilCollection_(" + "id<JavaUtilCollection> capture$0) NS_RETURNS_RETAINED;"); } public void testEnumInEqualsTest() throws IOException { String translation = translateSourceFile( "public class Test { enum TicTacToe { X, Y } " + "boolean isX(TicTacToe ttt) { return ttt == TicTacToe.X; } }", "Test", "Test.m"); assertTranslation(translation, "return ttt == Test_TicTacToeEnum_get_X();"); } public void testArrayLocalVariable() throws IOException { String source = "char[] array = new char[1];"; List<Statement> stmts = translateStatements(source); assertEquals(1, stmts.size()); String result = generateStatement(stmts.get(0)); assertEquals("IOSCharArray *array = [IOSCharArray arrayWithLength:1];", result); source = "char array[] = new char[1];"; stmts = translateStatements(source); assertEquals(1, stmts.size()); result = generateStatement(stmts.get(0)); assertEquals("IOSCharArray *array = [IOSCharArray arrayWithLength:1];", result); } public void testArrayParameterLengthUse() throws IOException { String translation = translateSourceFile( "public class Test { void test(char[] foo, char bar[]) { " + "sync(foo.length, bar.length); } void sync(int a, int b) {} }", "Test", "Test.m"); assertTranslation(translation, "[self syncWithInt:((IOSCharArray *) nil_chk(foo))->size_ withInt:" + "((IOSCharArray *) nil_chk(bar))->size_];"); } public void testLongLiteral() throws IOException { String translation = translateSourceFile("public class Test { " + "public static void testLong() { long l1 = 1L; }}", "Test", "Test.m"); assertTranslation(translation, "jlong l1 = 1LL"); } public void testStringLiteralEscaping() throws IOException { String source = "String s = \"\\u1234\\u2345\\n\";"; List<Statement> stmts = translateStatements(source); assertEquals(1, stmts.size()); String result = generateStatement(stmts.get(0)); assertEquals("NSString *s = @\"\\u1234\\u2345\\n\";", result); } public void testStringLiteralEscapingInStringConcatenation() throws IOException { String source = "String s = \"\\u1234\" + \"Hi\" + \"\\u2345\\n\";"; List<Statement> stmts = translateStatements(source); assertEquals(1, stmts.size()); String result = generateStatement(stmts.get(0)); assertEquals("NSString *s = @\"\\u1234Hi\\u2345\\n\";", result); } /** * Verify that Unicode escape sequences that aren't legal C++ Unicode are * converted to C hexadecimal escape sequences. This works because all * illegal sequences are less than 0xA0. */ public void testStringLiteralWithInvalidCppUnicode() throws IOException { String source = "String s = \"\\u0093\\u0048\\u0069\\u0094\\n\";"; List<Statement> stmts = translateStatements(source); assertEquals(1, stmts.size()); String result = generateStatement(stmts.get(0)); assertEquals("NSString *s = @\"\\xc2\\x93Hi\\xc2\\x94\\n\";", result); } public void testArrayInitializer() { String source = "int[] a = { 1, 2, 3 }; char b[] = { '4', '5' };"; List<Statement> stmts = translateStatements(source); assertEquals(2, stmts.size()); String result = generateStatement(stmts.get(0)); assertEquals("IOSIntArray *a = [IOSIntArray arrayWithInts:(jint[]){ 1, 2, 3 } count:3];", result); result = generateStatement(stmts.get(1)); assertEquals("IOSCharArray *b = " + "[IOSCharArray arrayWithChars:(jchar[]){ '4', '5' } count:2];", result); } /** * Verify that static array initializers are rewritten as method calls. */ public void testStaticArrayInitializer() throws IOException { String translation = translateSourceFile( "public class Test { static int[] a = { 1, 2, 3 }; static char b[] = { '4', '5' }; }", "Test", "Test.m"); assertTranslation(translation, "JreStrongAssignAndConsume(&Test_a_, nil, " + "[IOSIntArray newArrayWithInts:(jint[]){ 1, 2, 3 } count:3]);"); assertTranslation(translation, "JreStrongAssignAndConsume(&Test_b_, nil, " + "[IOSCharArray newArrayWithChars:(jchar[]){ '4', '5' } count:2]);"); } public void testLocalArrayCreation() throws IOException { String translation = translateSourceFile( "public class Example { char[] test() { int high = 0xD800, low = 0xDC00; " + "return new char[] { (char) high, (char) low }; } }", "Example", "Example.m"); assertTranslation(translation, "return [IOSCharArray " + "arrayWithChars:(jchar[]){ (jchar) high, (jchar) low } count:2];"); } // Regression test: "case:" was output instead of "case". public void testSwitchCaseStatement() throws IOException { String source = "int c = 1; " + "switch (c) { case 1: c = 0; break; default: break; }"; List<Statement> stmts = translateStatements(source); assertEquals(2, stmts.size()); String result = generateStatement(stmts.get(1)); assertTrue(result.contains("case 1:")); } public void testEnhancedForStatement() throws IOException { String source = "String[] strings = {\"test1\", \"test2\"};" + "for (String string : strings) { }"; List<Statement> stmts = translateStatements(source); assertEquals(2, stmts.size()); String result = generateStatement(stmts.get(1)); assertTranslatedLines(result, "{", "IOSObjectArray *a__ = strings;", "NSString * const *b__ = a__->buffer_;", "NSString * const *e__ = b__ + a__->size_;", "while (b__ < e__) {", "NSString *string = *b__++;", "}", "}"); } public void testEnhancedForStatementInSwitchStatement() throws IOException { String source = "int test = 5; int[] myInts = new int[10]; " + "switch (test) { case 0: break; default: " + "for (int i : myInts) {} break; }"; List<Statement> stmts = translateStatements(source); assertEquals(3, stmts.size()); String result = generateStatement(stmts.get(2)); assertTranslatedLines(result, "switch (test) {", "case 0:", "break;", "default:", "{", "IOSIntArray *a__ = myInts;", "jint const *b__ = a__->buffer_;", "jint const *e__ = b__ + a__->size_;", "while (b__ < e__) {", "jint i = *b__++;", "}", "}", "break;", "}"); } public void testSwitchStatementWithExpression() throws IOException { String translation = translateSourceFile("public class Example { " + "static enum Test { ONE, TWO } " + "Test foo() { return Test.ONE; } " + "void bar() { switch (foo()) { case ONE: break; case TWO: break; }}}", "Example", "Example.m"); assertTranslation(translation, "switch ([[self foo] ordinal])"); } public void testClassVariable() throws IOException { String source = "Class<?> myClass = getClass();" + "Class<?> mySuperClass = myClass.getSuperclass();" + "Class<?> enumClass = Enum.class;"; List<Statement> stmts = translateStatements(source); assertEquals(3, stmts.size()); String result = generateStatement(stmts.get(0)); assertEquals("IOSClass *myClass = [self getClass];", result); result = generateStatement(stmts.get(1)); assertEquals("IOSClass *mySuperClass = [myClass getSuperclass];", result); result = generateStatement(stmts.get(2)); assertEquals("IOSClass *enumClass = JavaLangEnum_class_();", result); } public void testInnerClassCreation() throws IOException { String translation = translateSourceFile( "public class A { int x; class Inner { int y; Inner(int i) { y = i + x; }}" + "public Inner test() { return this.new Inner(3); }}", "A", "A.m"); assertTranslation(translation, "return [new_A_Inner_initWithA_withInt_(self, 3) autorelease];"); } public void testNewFieldNotRetained() throws IOException { String translation = translateSourceFile( "import java.util.*; public class A { Map map; A() { map = new HashMap(); }}", "A", "A.m"); assertTranslation(translation, "A_setAndConsume_map_(self, new_JavaUtilHashMap_init())"); } public void testStringAddOperator() throws IOException { String translation = translateSourceFile( "import java.util.*; public class A { String myString;" + " A() { myString = \"Foo\"; myString += \"Bar\"; }}", "A", "A.m"); assertTranslation(translation, "A_set_myString_(self, JreStrcat(\"$$\", self->myString_, @\"Bar\"));"); } public void testPrimitiveConstantInSwitchCase() throws IOException { String translation = translateSourceFile( "public class A { public static final char PREFIX = 'p';" + "public boolean doSomething(char c) { switch (c) { " + "case PREFIX: return true; " + "default: return false; }}}", "A", "A.h"); assertTranslation(translation, "#define A_PREFIX 'p'"); translation = getTranslatedFile("A.m"); assertTranslation(translation, "case A_PREFIX:"); } public void testInterfaceStaticVarReference() throws IOException { String translation = translateSourceFile( "public class Test { " + " public interface I { " + " void foo(); public static final int FOO = 1; } " + " public class Bar implements I { public void foo() { int i = I.FOO; } } }", "Test", "Test.m"); assertTranslation(translation, "int i = Test_I_FOO;"); } public void testMethodWithPrimitiveArrayParameter() throws IOException { String translation = translateSourceFile( "public class Test { " + " public void foo(char[] chars) { } }", "Test", "Test.m"); assertTranslation(translation, "fooWithCharArray:"); } public void testMethodWithGenericArrayParameter() throws IOException { String translation = translateSourceFile( "public class Test<T> { " + " T[] tArray; " + " public void foo(T[] ts) { } " + " public void bar(Test<? extends T>[] tLists) { } " + " public void foo() { foo(tArray); } " + " public class Inner<S extends Test<T>> { " + " public void baz(S[] ss) { } } }", "Test", "Test.m"); assertTranslation(translation, "- (void)fooWithNSObjectArray:"); assertTranslation(translation, "- (void)barWithTestArray:"); assertTranslation(translation, "- (void)foo {"); assertTranslation(translation, "[self fooWithNSObjectArray:"); assertTranslation(translation, "- (void)bazWithTestArray:"); } public void testGenericMethodWithfGenericArrayParameter() throws IOException { String translation = translateSourceFile( "public class Test { " + " public <T> void foo(T[] ts) { } " + " public void foo() { foo(new String[1]); } }", "Test", "Test.m"); assertTranslation(translation, "[self fooWithNSObjectArray:"); } public void testJreDoubleNegativeInfinity() throws IOException { String translation = translateSourceFile( "public class Test { " + " public void foo() { Double d = Double.NEGATIVE_INFINITY; } }", "Test", "Test.m"); assertTranslation(translation, "JavaLangDouble_valueOfWithDouble_(JavaLangDouble_NEGATIVE_INFINITY)"); } public void testInvokeMethodInConcreteImplOfGenericInterface() throws IOException { String translation = translateSourceFile( "public class Test { " + " public interface Foo<T> { void foo(T t); } " + " public class FooImpl implements Foo<Test> { " + " public void foo(Test t) { } " + " public void bar() { foo(new Test()); } } }", "Test", "Test.m"); assertTranslation(translation, "[self fooWithId:"); } public void testNewStringWithArrayInAnonymousClass() throws IOException { String translation = translateSourceFile( "public class Test { " + " public Runnable foo() { " + " String s1 = new String(new char[10]); " + " return new Runnable() { " + " public void run() { String s = new String(new char[10]); } }; } }", "Test", "Test.m"); assertTranslation(translation, "s = [NSString stringWith"); } public void testMostNegativeIntegers() throws IOException { String translation = translateSourceFile( "public class Test { " + " int min_int = 0x80000000; " + " long min_long = 0x8000000000000000L; }", "Test", "Test.m"); assertTranslation(translation, "-0x7fffffff - 1"); assertTranslation(translation, "-0x7fffffffffffffffLL - 1"); } public void testInnerNewStatement() throws IOException { String translation = translateSourceFile( "class A { class B {} static B test() { return new A().new B(); }}", "A", "A.m"); assertTranslation(translation, "[new_A_B_initWithA_([new_A_init() autorelease]) autorelease]"); } public void testSuperFieldAccess() throws IOException { String translation = translateSourceFile( "public class A { int i; class B extends A { int i; int test() { return super.i + i; }}}", "A", "A.m"); assertTranslation(translation, "return i_ + i_B_;"); } public void testStaticConstants() throws IOException { String source = "float f = Float.NaN; double d = Double.POSITIVE_INFINITY;"; List<Statement> stmts = translateStatements(source); assertEquals(2, stmts.size()); String result = generateStatement(stmts.get(0)).trim(); assertEquals(result, "jfloat f = JavaLangFloat_NaN;"); result = generateStatement(stmts.get(1)).trim(); assertEquals(result, "jdouble d = JavaLangDouble_POSITIVE_INFINITY;"); } public void testInstanceStaticConstants() throws IOException { String translation = translateSourceFile( "public class Test { Foo f; void test() { int i = f.DEFAULT; Object lock = f.LOCK; }} " + "class Foo { public static final int DEFAULT = 1; " + "public static final Object LOCK = null; }", "Test", "Test.m"); assertTranslation(translation, "int i = Foo_DEFAULT;"); assertTranslation(translation, "id lock = Foo_get_LOCK_();"); } public void testCastGenericReturnType() throws IOException { String translation = translateSourceFile( "class Test { " + " static class A<E extends A> { E other; public E getOther() { return other; } } " + " static class B extends A<B> { B other = getOther(); } }", "Test", "Test.h"); // Test_B's "other" needs a trailing underscore, since there is an "other" // field in its superclass. assertTranslation(translation, "Test_B *other_B_;"); translation = getTranslatedFile("Test.m"); assertTranslation(translation, "Test_B_set_other_B_(self, [self getOther])"); } public void testArrayInstanceOfTranslation() throws IOException { String source = "Object args = new String[0]; if (args instanceof String[]) {}"; List<Statement> stmts = translateStatements(source); assertEquals(2, stmts.size()); String result = generateStatement(stmts.get(1)); assertEquals( "if ([IOSClass_arrayType(NSString_class_(), 1) isInstance:args]) {\n}", result); } public void testInterfaceArrayInstanceOfTranslation() throws IOException { String source = "Object args = new Readable[0]; if (args instanceof Readable[]) {}"; List<Statement> stmts = translateStatements(source); assertEquals(2, stmts.size()); String result = generateStatement(stmts.get(1)); assertEquals( "if ([IOSClass_arrayType(JavaLangReadable_class_(), 1) isInstance:args]) {\n}", result); } public void testPrimitiveArrayInstanceOfTranslation() throws IOException { String source = "Object args = new int[0]; if (args instanceof int[]) {}"; List<Statement> stmts = translateStatements(source); assertEquals(2, stmts.size()); String result = generateStatement(stmts.get(1)); assertEquals("if ([args isKindOfClass:[IOSIntArray class]]) {\n}", result); } public void testObjectArrayInitializer() throws IOException { String source = "String[] a = { \"one\", \"two\", \"three\" };"; List<Statement> stmts = translateStatements(source); assertEquals(1, stmts.size()); String result = generateStatement(stmts.get(0)); assertEquals("IOSObjectArray *a = [IOSObjectArray " + "arrayWithObjects:(id[]){ @\"one\", @\"two\", @\"three\" } " + "count:3 type:NSString_class_()];", result); source = "Comparable[] a = { \"one\", \"two\", \"three\" };"; stmts = translateStatements(source); assertEquals(1, stmts.size()); result = generateStatement(stmts.get(0)); assertEquals("IOSObjectArray *a = [IOSObjectArray " + "arrayWithObjects:(id[]){ @\"one\", @\"two\", @\"three\" } " + "count:3 type:JavaLangComparable_class_()];", result); } public void testArrayPlusAssign() throws IOException { String source = "int[] array = new int[] { 1, 2, 3 }; int offset = 1; array[offset] += 23;"; List<Statement> stmts = translateStatements(source); assertEquals(3, stmts.size()); String result = generateStatement(stmts.get(2)); assertEquals("*IOSIntArray_GetRef(array, offset) += 23;", result); } public void testRegisterVariableName() throws IOException { String source = "int register = 42;"; List<Statement> stmts = translateStatements(source); assertEquals(1, stmts.size()); String result = generateStatement(stmts.get(0)); assertEquals("jint register_ = 42;", result); } public void testStaticVariableSetterReference() throws IOException { String translation = translateSourceFile( "public class Example { public static java.util.Date today; }" + "class Test { void test(java.util.Date now) { Example.today = now; }}", "Example", "Example.m"); assertTranslation(translation, "Example_set_today_(now);"); } // b/5872533: reserved method name not renamed correctly in super invocation. public void testSuperReservedName() throws IOException { addSourceFile("public class A { A() {} public void init(int a) { }}", "A.java"); addSourceFile( "public class B extends A { B() {} public void init(int b) { super.init(b); }}", "B.java"); String translation = translateSourceFile("A", "A.h"); assertTranslation(translation, "- (instancetype)init;"); assertTranslation(translation, "- (void)init__WithInt:(jint)a"); translation = translateSourceFile("B", "B.m"); assertTranslation(translation, "A_init(self);"); assertTranslation(translation, "[super init__WithInt:b];"); } // b/5872757: verify multi-dimensional array has cast before each // secondary reference. public void testMultiDimArrayCast() throws IOException { String translation = translateSourceFile( "public class Test {" + " static String[][] a = new String[1][1];" + " public static void main(String[] args) { " + " a[0][0] = \"42\"; System.out.println(a[0].length); }}", "Test", "Test.m"); assertTranslation(translation, "IOSObjectArray_Set(nil_chk(IOSObjectArray_Get(nil_chk(Test_a_), 0)), 0, @\"42\");"); assertTranslation(translation, "((IOSObjectArray *) nil_chk(IOSObjectArray_Get(Test_a_, 0)))->size_"); } public void testMultiDimArray() throws IOException { String source = "int[][] a = new int[][] { null, { 0, 2 }, { 2, 2 }};"; List<Statement> stmts = translateStatements(source); assertEquals(1, stmts.size()); String translation = generateStatement(stmts.get(0)); assertTranslation(translation, "IOSObjectArray *a = [IOSObjectArray arrayWithObjects:(id[]){ nil, " + "[IOSIntArray arrayWithInts:(jint[]){ 0, 2 } count:2], " + "[IOSIntArray arrayWithInts:(jint[]){ 2, 2 } count:2] } count:3 " + "type:IOSClass_intArray(1)];"); } public void testObjectMultiDimArray() throws IOException { String source = "class Test { Integer i = new Integer(1); Integer j = new Integer(2);" + "void test() { Integer[][] a = new Integer[][] { null, { i, j }, { j, i }}; }}"; String translation = translateSourceFile(source, "Test", "Test.m"); assertTranslation(translation, "IOSObjectArray *a = [IOSObjectArray arrayWithObjects:(id[]){ nil, " + "[IOSObjectArray arrayWithObjects:(id[]){ i_, j_ } count:2 " + "type:JavaLangInteger_class_()], " + "[IOSObjectArray arrayWithObjects:(id[]){ j_, i_ } count:2 " + "type:JavaLangInteger_class_()] } count:3 " + "type:IOSClass_arrayType(JavaLangInteger_class_(), 1)];"); } public void testVarargsMethodInvocationZeroLengthArray() throws IOException { String translation = translateSourceFile( "public class Example { " + " public void call() { foo(new Object[0]); bar(new Object[0]); } " + " public void foo(Object ... args) { } " + " public void bar(Object[] ... args) { } }", "Example", "Example.h"); assertTranslation(translation, "- (void)fooWithNSObjectArray:(IOSObjectArray *)args"); assertTranslation(translation, "- (void)barWithNSObjectArray2:(IOSObjectArray *)args"); translation = getTranslatedFile("Example.m"); // Should be equivalent to foo(new Object[0]). assertTranslation(translation, "[self fooWithNSObjectArray:[IOSObjectArray arrayWithLength:0 type:NSObject_class_()]]"); // Should be equivalent to bar(new Object[] { new Object[0] }). assertTranslation(translation, "[self barWithNSObjectArray2:[IOSObjectArray arrayWithObjects:" + "(id[]){ [IOSObjectArray arrayWithLength:0 type:NSObject_class_()] } count:1 " + "type:IOSClass_arrayType(NSObject_class_(), 1)]];"); } public void testVarargsIOSMethodInvocation() throws IOException { String translation = translateSourceFile( "import java.lang.reflect.Constructor; public class Test { " + " public void test() throws Exception { " + " Constructor c1 = Test.class.getConstructor();" + " Constructor c2 = Test.class.getConstructor(String.class);" + " Constructor c3 = Test.class.getConstructor(String.class, Byte.TYPE);" + " Class[] types = new Class[] { Object.class, Exception.class };" + " Constructor c4 = Test.class.getConstructor(types); }}", "Test", "Test.m"); assertTranslation(translation, "c1 = [Test_class_() getConstructor:" + "[IOSObjectArray arrayWithLength:0 type:IOSClass_class_()]];"); assertTranslation(translation, "c2 = [Test_class_() getConstructor:[IOSObjectArray " + "arrayWithObjects:(id[]){ NSString_class_() } count:1 type:IOSClass_class_()]];"); assertTranslation(translation, "c3 = [Test_class_() getConstructor:[IOSObjectArray arrayWithObjects:" + "(id[]){ NSString_class_(), JavaLangByte_get_TYPE_() } count:2 " + "type:IOSClass_class_()]];"); // Array contents should be expanded. assertTranslation(translation, "c4 = [Test_class_() getConstructor:types];"); } public void testGetVarargsWithLeadingParameter() throws IOException { String translation = translateSourceFile( "public class Test {" + " void test() throws Exception { " + " getClass().getMethod(\"equals\", Object.class); }}", "Test", "Test.m"); assertTranslation(translation, "[[self getClass] getMethod:@\"equals\" parameterTypes:[IOSObjectArray " + "arrayWithObjects:(id[]){ NSObject_class_() } count:1 type:IOSClass_class_()]];"); } public void testGetVarargsWithLeadingParameterNoArgs() throws IOException { String translation = translateSourceFile( "public class Test {" + " void test() throws Exception { " + " getClass().getMethod(\"hashCode\", new Class[0]); }}", "Test", "Test.m"); assertTranslation(translation, "[[self getClass] getMethod:@\"hashCode\" parameterTypes:[IOSObjectArray " + "arrayWithLength:0 type:IOSClass_class_()]];"); } public void testTypeVariableWithBoundCast() throws IOException { String translation = translateSourceFile( "import java.util.ArrayList; public class Test {" + " public static class Foo<T extends Foo.Bar> {" + " public static class Bar { } " + " public T foo() { return null; } } " + " public static class BarD extends Foo.Bar { } " + " public void bar(Foo<BarD> f) { BarD b = f.foo(); } }", "Test", "Test.m"); assertTranslation(translation, "[((Test_Foo *) nil_chk(f)) foo]"); } // b/5934474: verify that static variables are always referenced by // their accessors in functions, since their class may not have loaded. public void testFunctionReferencesStaticVariable() throws IOException { String translation = translateSourceFile( "public class HelloWorld {" + " static String staticString = \"hello world\";" + " public static void main(String[] args) {" + " System.out.println(staticString);" + " }}", "HelloWorld", "HelloWorld.m"); assertTranslation(translation, "printlnWithNSString:HelloWorld_staticString_];"); } public void testThisCallInEnumConstructor() throws IOException { String translation = translateSourceFile( "public enum Test {" + " A, B(1);" + " private int i;" + " private Test(int i) { this.i = i; } " + " private Test() { this(0); }}", "Test", "Test.m"); assertTranslation(translation, "TestEnum_initWithInt_withNSString_withInt_(self, 0, __name, __ordinal);"); } public void testThisCallInInnerConstructor() throws IOException { String translation = translateSourceFile( "public class Test {" + " class Inner {" + " public Inner() { }" + " public Inner(int foo) { this(); int i = foo; }}}", "Test", "Test.m"); assertTranslation(translation, "Test_Inner_initWithTest_(self, outer$);"); } // Verify that an external string can be used in string concatenation, // for a parameter to a translated method. public void testConcatPublicStaticString() throws IOException { String translation = translateSourceFile( "class B { public static final String separator = \"/\"; } " + "public class A { String prefix(Object o) { return new String(o + B.separator); }}", "A", "A.m"); assertTranslation(translation, "[NSString stringWithString:JreStrcat(\"@$\", o, B_get_separator_())]"); } public void testStringConcatWithBoolean() throws IOException { String translation = translateSourceFile( "public class A { String test(boolean b) { return \"foo: \" + b; }}", "A", "A.m"); assertTranslation(translation, "return JreStrcat(\"$Z\", @\"foo: \", b);"); } public void testStringConcatWithChar() throws IOException { String translation = translateSourceFile( "public class A { String test(char c) { return \"foo: \" + c; }}", "A", "A.m"); assertTranslation(translation, "return JreStrcat(\"$C\", @\"foo: \", c);"); } // Verify that double quote character constants are concatenated correctly. public void testConcatDoubleQuoteChar() throws IOException { String translation = translateSourceFile( "public class Test { " + "static final char QUOTE = '\"'; static final String TEST = QUOTE + \"\"; }", "Test", "Test.m"); assertTranslation(translation, "Test_TEST_ = @\"\\\"\";"); } /** * Verify that when a the last switch case is empty (no statement), * an empty statement is added. Java doesn't require an empty statement * here, while C does. */ public void testEmptyLastCaseStatement() throws IOException { String translation = translateSourceFile( "public class A {" + " int test(int i) { " + " switch (i) { case 1: return 1; case 2: return 2; default: } return i; }}", "A", "A.m"); assertTranslation(translation, "default:\n ;\n }"); } public void testBuildStringFromChars() { String s = "a\uffffz"; String result = StatementGenerator.buildStringFromChars(s); assertEquals(result, "[NSString stringWithCharacters:(jchar[]) " + "{ (int) 0x61, (int) 0xffff, (int) 0x7a } length:3]"); } // Verify that return statements in constructors return self. public void testConstructorReturn() throws IOException { String translation = translateSourceFile( "public class A { public A() { return; }}", "A", "A.m"); assertTranslation(translation, "return self;"); } public void testNonAsciiOctalEscapeInString() throws IOException { String translation = translateSourceFile( "public class A { String s1 = \"\\177\"; String s2 = \"\\200\"; String s3 = \"\\377\"; }", "A", "A.m"); assertTranslation(translation, "@\"\\x7f\""); assertTranslation(translation, "@\"\\xc2\\x80\""); assertTranslation(translation, "@\"\\u00ff\""); } public void testCharLiteralsAreEscaped() throws IOException { String translation = translateSourceFile( "public class A {" + "public static final char APOSTROPHE = '\\''; " + "public static final char BACKSLASH = '\\\\'; " + "void foo(char c) {} void test() { foo('\\''); foo('\\\\'); }}", "A", "A.h"); assertTranslation(translation, "#define A_APOSTROPHE '\\''"); assertTranslation(translation, "#define A_BACKSLASH '\\\\'"); translation = getTranslatedFile("A.m"); assertTranslation(translation, "fooWithChar:'\\'']"); assertTranslation(translation, "fooWithChar:'\\\\']"); } public void testStaticVarAccessFromInnerClass() throws IOException { String translation = translateSourceFile("public class Test { public static String foo; " + "interface Assigner { void assign(String s); } static { " + "new Assigner() { public void assign(String s) { foo = s; }}; }}", "Test", "Test.m"); assertTranslation(translation, "Test_set_foo_(s);"); } public void testNoAutoreleasePoolForStatement() throws IOException { String translation = translateSourceFile( "public class Test {" + " public void foo() {" + " for (int i = 0; i < 10; i++) {" + " }" + " }" + "}", "Test", "Test.m"); assertTranslation(translation, " for (jint i = 0; i < 10; i++) {\n }"); } public void testAutoreleasePoolForStatement() throws IOException { String translation = translateSourceFile( "import com.google.j2objc.annotations.AutoreleasePool;" + "public class Test {" + " public void foo() {" + " for (@AutoreleasePool int i = 0; i < 10; i++) {" + " }" + " }" + "}", "Test", "Test.m"); assertTranslation(translation, " for (jint i = 0; i < 10; i++) {\n" + " @autoreleasepool {\n }\n" + " }"); } public void testAutoreleasePoolEnhancedForStatement() throws IOException { String translation = translateSourceFile( "import com.google.j2objc.annotations.AutoreleasePool;" + "public class Test {" + " public void foo(String[] strings) {" + " for (@AutoreleasePool String s : strings) {" + " }" + " }" + "}", "Test", "Test.m"); assertTranslation(translation, "@autoreleasepool"); } public void testARCAutoreleasePoolForStatement() throws IOException { Options.setMemoryManagementOption(MemoryManagementOption.ARC); String translation = translateSourceFile( "import com.google.j2objc.annotations.AutoreleasePool;" + "public class Test {" + " public void foo() {" + " for (@AutoreleasePool int i = 0; i < 10; i++) {" + " }" + " }" + "}", "Test", "Test.m"); assertTranslation(translation, " for (jint i = 0; i < 10; i++) {\n" + " @autoreleasepool {\n" + " }\n" + " }"); } public void testARCAutoreleasePoolEnhancedForStatement() throws IOException { Options.setMemoryManagementOption(MemoryManagementOption.ARC); String translation = translateSourceFile( "import com.google.j2objc.annotations.AutoreleasePool;" + "public class Test {" + " public void foo(String[] strings) {" + " for (@AutoreleasePool String s : strings) {" + " }" + " }" + "}", "Test", "Test.m"); assertTranslation(translation, "@autoreleasepool {"); } public void testShiftAssignArrayElement() throws IOException { String translation = translateSourceFile( "public class Test { void test(int[] array) { " + "int i = 2;" + "array[0] >>>= 2; " + "array[i - 1] >>>= 3; " + "array[1] >>= 4;" + "array[2] <<= 5;}}", "Test", "Test.m"); assertTranslation(translation, "URShiftAssignInt(IOSIntArray_GetRef(nil_chk(array), 0), 2)"); assertTranslation(translation, "URShiftAssignInt(IOSIntArray_GetRef(array, i - 1), 3)"); assertTranslation(translation, "RShiftAssignInt(IOSIntArray_GetRef(array, 1), 4)"); assertTranslation(translation, "LShiftAssignInt(IOSIntArray_GetRef(array, 2), 5)"); } public void testAssertWithoutDescription() throws IOException { String translation = translateSourceFile( "public class Test { void test() {\n" + "int a = 5;\nint b = 6;\nassert a < b;\n}\n}\n", "Test", "Test.m"); assertTranslation(translation, "NSAssert(a < b, @\"Test.java:4 condition failed: assert a < b;\")"); } public void testAssertWithDescription() throws IOException { String translation = translateSourceFile( "public class Test { void test() { " + "int a = 5; int b = 6; assert a < b : \"a should be lower than b\";}}", "Test", "Test.m"); assertTranslation(translation, "NSAssert(a < b, @\"a should be lower than b\")"); } public void testAssertWithDynamicDescription() throws IOException { String translation = translateSourceFile( "public class Test { void test() { " + "int a = 5; int b = 6; assert a < b : a + \" should be lower than \" + b;}}", "Test", "Test.m"); assertTranslation(translation, "NSAssert(a < b, [JreStrcat(\"I$I\" J2OBJC_COMMA() a J2OBJC_COMMA()" + " @\" should be lower than \" J2OBJC_COMMA() b) description]);"); } // Verify that a Unicode escape sequence is preserved with string // concatenation. public void testUnicodeStringConcat() throws IOException { String translation = translateSourceFile( "class Test { static final String NAME = \"\\u4e2d\\u56fd\";" + " static final String CAPTION = \"China's name is \";" + " static final String TEST = CAPTION + NAME; }", "Test", "Test.m"); assertTranslation(translation, "Test_TEST_ = @\"China's name is \\u4e2d\\u56fd\""); } public void testPartialArrayCreation2D() throws IOException { String translation = translateSourceFile( "class Test { void foo() { char[][] c = new char[3][]; } }", "Test", "Test.m"); assertTranslation(translation, "#include \"IOSObjectArray.h\""); assertTranslation(translation, "#include \"IOSClass.h\""); assertTranslation(translation, "IOSObjectArray *c = [IOSObjectArray arrayWithLength:3 type:IOSClass_charArray(1)]"); } public void testPartialArrayCreation3D() throws IOException { String translation = translateSourceFile( "class Test { void foo() { char[][][] c = new char[3][][]; } }", "Test", "Test.m"); assertTranslation(translation, "#include \"IOSObjectArray.h\""); assertTranslation(translation, "IOSObjectArray *c = [IOSObjectArray arrayWithLength:3 type:IOSClass_charArray(2)]"); } public void testUnsignedRightShift() throws IOException { String translation = translateSourceFile( "public class Test { void test(int a, long b, char c, byte d, short e) { " + "long r; r = a >>> 1; r = b >>> 2; r = c >>> 3; r = d >>> 4; r = e >>> 5; }}", "Test", "Test.m"); assertTranslation(translation, "r = URShift32(a, 1);"); assertTranslation(translation, "r = URShift64(b, 2);"); assertTranslation(translation, "r = URShift32(c, 3);"); assertTranslation(translation, "r = URShift32(d, 4);"); assertTranslation(translation, "r = URShift32(e, 5);"); } public void testUnsignedRightShiftAssign() throws IOException { String translation = translateSourceFile( "public class Test { void test(int a, long b, char c, byte d, short e) { " + "a >>>= 1; b >>>= 2; c >>>= 3; d >>>= 4; e >>>= 5; }}", "Test", "Test.m"); assertTranslation(translation, "URShiftAssignInt(&a, 1);"); assertTranslation(translation, "URShiftAssignLong(&b, 2);"); assertTranslation(translation, "URShiftAssignChar(&c, 3);"); assertTranslation(translation, "URShiftAssignByte(&d, 4);"); assertTranslation(translation, "URShiftAssignShort(&e, 5);"); } public void testUnsignedShiftRightAssignCharArray() throws IOException { String translation = translateSourceFile( "public class Test { void test(char[] array) { " + "array[0] >>>= 2; }}", "Test", "Test.m"); assertTranslation(translation, "URShiftAssignChar(IOSCharArray_GetRef(nil_chk(array), 0), 2)"); } public void testDoubleQuoteConcatenation() throws IOException { String translation = translateSourceFile( "public class Test { String test(String s) { return '\"' + s + '\"'; }}", "Test", "Test.m"); assertTranslation(translation, "return JreStrcat(\"C$C\", '\"', s, '\"');"); } public void testIntConcatenation() throws IOException { String translation = translateSourceFile( "public class Test { void check(boolean expr, String fmt, Object... args) {} " + "void test(int i, int j) { check(true, \"%d-%d\", i, j); }}", "Test", "Test.m"); assertTranslation(translation, "[self checkWithBoolean:YES withNSString:@\"%d-%d\" " + "withNSObjectArray:[IOSObjectArray arrayWithObjects:(id[]){ " + "JavaLangInteger_valueOfWithInt_(i), JavaLangInteger_valueOfWithInt_(j) } count:2 " + "type:NSObject_class_()]];"); } // Verify that a string == comparison is converted to compare invocation. public void testStringComparison() throws IOException { String translation = translateSourceFile( "public class Test { void check(String s, Object o) { " + "boolean b1 = s == null; boolean b2 = \"foo\" == s; boolean b3 = o == \"bar\"; " + "boolean b4 = \"baz\" != s; boolean b5 = null != \"abc\"; }}", "Test", "Test.m"); // Assert that non-string compare isn't converted. assertTranslation(translation, "jboolean b1 = s == nil;"); // Assert string equate is converted, assertTranslation(translation, "jboolean b2 = [@\"foo\" isEqual:s];"); // Order is reversed when literal is on the right. assertTranslation(translation, "jboolean b3 = [@\"bar\" isEqual:o];"); // Not equals is converted. assertTranslation(translation, "jboolean b4 = ![@\"baz\" isEqual:s];"); // Comparing null with string literal. assertTranslation(translation, "jboolean b5 = ![@\"abc\" isEqual:nil];"); } public void testBinaryLiterals() throws IOException { String translation = translateSourceFile( "public class A { " + " byte aByte = (byte)0b00100001; short aShort = (short)0b1010000101000101;" + " int anInt1 = 0b10100001010001011010000101000101; " + " int anInt2 = 0b101; int anInt3 = 0B101;" // b can be lower or upper case. + " long aLong = 0b1010000101000101101000010100010110100001010001011010000101000101L; }", "A", "A.m"); assertTranslation(translation, "aByte_ = (jbyte) 0b00100001;"); assertTranslation(translation, "aShort_ = (jshort) 0b1010000101000101;"); assertTranslation(translation, "anInt1_ = 0b10100001010001011010000101000101;"); assertTranslation(translation, "anInt2_ = 0b101;"); assertTranslation(translation, "anInt3_ = 0B101;"); assertTranslation(translation, "aLong_ = 0b1010000101000101101000010100010110100001010001011010000101000101LL;"); } public void testUnderscoresInNumericLiterals() throws IOException { String translation = translateSourceFile( "public class A { " + " long creditCardNumber = 1234_5678_9012_3456L; " + " long socialSecurityNumber = 999_99_9999L; " + " float pi = 3.14_15F; " + " long hexBytes = 0xFF_EC_DE_5E; " + " long hexWords = 0xCAFE_BABE; " + " long maxLong = 0x7fff_ffff_ffff_ffffL; " + " byte nybbles = 0b0010_0101; " + " long bytes = 0b11010010_01101001_10010100_10010010; }", "A", "A.m"); assertTranslation(translation, "creditCardNumber_ = 1234567890123456LL;"); assertTranslation(translation, "socialSecurityNumber_ = 999999999LL;"); assertTranslation(translation, "pi_ = 3.1415f;"); assertTranslation(translation, "hexBytes_ = (jint) 0xFFECDE5E;"); assertTranslation(translation, "hexWords_ = (jint) 0xCAFEBABE;"); assertTranslation(translation, "maxLong_ = (jlong) 0x7fffffffffffffffLL;"); assertTranslation(translation, "nybbles_ = 0b00100101;"); assertTranslation(translation, "bytes_ = 0b11010010011010011001010010010010;"); } // Verify that the null literal is concatenated as "null" in strings. public void testNullConcatenation() throws IOException { String translation = translateSourceFile( "public class Test { String test(String s) { return \"the nil value is \" + null; }}", "Test", "Test.m"); assertTranslation(translation, "return JreStrcat(\"$@\", @\"the nil value is \", nil);"); } public void testTypeVariableWithBoundsIsCast() throws IOException { String translation = translateSourceFile( "class Test<E> { interface A<T> { void foo(); } class B { int foo() { return 1; } } " + "<T extends A<? super E>> void test(T t) { t.foo(); } " + "<T extends B> void test2(T t) { t.foo(); } }", "Test", "Test.m"); assertTranslation(translation, "[((id<Test_A>) nil_chk(t)) foo];"); assertTranslation(translation, "[((Test_B *) nil_chk(t)) foo];"); } public void testTypeVariableWithMultipleBounds() throws IOException { String translation = translateSourceFile( "class Test<T extends String & Runnable & Cloneable> { T t; }", "Test", "Test.h"); assertTranslation(translation, "NSString<JavaLangRunnable, NSCopying> *t"); } public void testMultiCatch() throws IOException { String translation = translateSourceFile( "import java.util.*; public class Test { " + " static class FirstException extends Exception {} " + " static class SecondException extends Exception {} " + " public void rethrowException(String exceptionName) " + " throws FirstException, SecondException { " + " try { " + " if (exceptionName.equals(\"First\")) { throw new FirstException(); } " + " else { throw new SecondException(); }" + " } catch (FirstException|SecondException e) { throw e; }}}", "Test", "Test.m"); assertTranslation(translation, "@catch (Test_FirstException *e) {\n @throw e;\n }"); assertTranslation(translation, "@catch (Test_SecondException *e) {\n @throw e;\n }"); } public void testDifferentTypesInConditionalExpression() throws IOException { String translation = translateSourceFile( "class Test { String test(Runnable r) { return \"foo\" + (r != null ? r : \"bar\"); } }", "Test", "Test.m"); assertTranslation(translation, "(r != nil ? ((id) r) : @\"bar\")"); } // Verify that when a method invocation returns an object that is ignored, // it is cast to (void) to avoid a clang warning when compiling with ARC. public void testVoidedUnusedInvocationReturn() throws IOException { Options.setMemoryManagementOption(MemoryManagementOption.ARC); String translation = translateSourceFile( "class Test { void test() {" + " StringBuilder sb = new StringBuilder();" + " sb.append(\"hello, world\");" + " new Throwable(); }}", "Test", "Test.m"); assertTranslation(translation, "(void) [sb appendWithNSString:@\"hello, world\"];"); assertTranslation(translation, "(void) new_JavaLangThrowable_init();"); } // Verify Java 7's switch statements with strings. public void testStringSwitchStatement() throws IOException { String translation = translateSourceFile( "public class Test { " + "static final String constant = \"mumble\";" + "int test(String s) { " + " switch(s) {" + " case \"foo\": return 42;" + " case \"bar\": return 666;" + " case constant: return -1;" + " default: return -1;" + " }}}", "Test", "Test.m"); assertTranslation(translation, "case 0:\n return 42;"); assertTranslation(translation, "case 1:\n return 666;"); assertTranslation(translation, "case 2:\n return -1;"); assertTranslation(translation, "default:\n return -1;"); assertTranslation(translation, "NSArray *__caseValues = " + "[NSArray arrayWithObjects:@\"foo\", @\"bar\", @\"mumble\", nil];"); assertTranslation(translation, "NSUInteger __index = [__caseValues indexOfObject:s];"); assertTranslation(translation, "switch (__index)"); } // Verify Java 7 try-with-resources translation. public void testTryWithResourceNoCatchOrFinally() throws IOException { // Only runs on Java 7, due to AutoCloseable dependency. String javaVersion = System.getProperty("java.version"); if (javaVersion.startsWith("1.7")) { String translation = translateSourceFile( "import java.io.*; public class Test { String test(String path) throws IOException { " + " try (BufferedReader br = new BufferedReader(new FileReader(path))) {" + " return br.readLine(); } }}", "Test", "Test.m"); assertTranslation(translation, "JavaIoBufferedReader *br = [new_JavaIoBufferedReader_initWithJavaIoReader_(" + "[new_JavaIoFileReader_initWithNSString_(path) autorelease]) autorelease];"); assertTranslation(translation, "@try {\n return [br readLine];\n }"); assertTranslation(translation, "@finally {"); assertTranslation(translation, "@try {\n [br close];\n }"); assertTranslation(translation, "@catch (JavaLangThrowable *e) {"); assertTranslation(translation, "if (__mainException) {"); assertTranslation(translation, "[__mainException addSuppressedWithJavaLangThrowable:e];"); assertTranslation(translation, "} else {\n __mainException = e;\n }"); assertTranslation(translation, "if (__mainException) {\n @throw __mainException;\n }"); } } public void testGenericResultIsCastForChainedMethodCall() throws IOException { String translation = translateSourceFile( "abstract class Test<T extends Test.Foo> { " + "abstract T getObj(); static class Foo { void foo() { } } " + "static void test(Test<Foo> t) { t.getObj().foo(); } }", "Test", "Test.m"); assertTranslation(translation, "[((Test_Foo *) nil_chk([((Test *) nil_chk(t)) getObj])) foo]"); } public void testCastResultWhenInterfaceDeclaresMoreGenericType() throws IOException { String translation = translateSourceFile( "class Test { " + "interface I1 { A foo(); } " + "interface I2 { B foo(); } " + "static class A { } static class B extends A { } " + "static abstract class C { abstract B foo(); } " + "static abstract class D extends C implements I1, I2 { } " + "B test(D d) { return d.foo(); } }", "Test", "Test.h"); // Check that protocols are declared in the same order. assertTranslation(translation, "@interface Test_D : Test_C < Test_I1, Test_I2 >"); translation = getTranslatedFile("Test.m"); // Check that the result of d.foo() is cast because the compiler will think // it returns a Test_A type. assertTranslation(translation, "return ((Test_B *) [((Test_D *) nil_chk(d)) foo]);"); } public void testStaticMethodCalledOnObject() throws IOException { String translation = translateSourceFile( "class Test { static void foo() {} void test(Test t) { t.foo(); } }", "Test", "Test.m"); assertTranslation(translation, "Test_foo();"); } public void testAnnotationVariableDeclaration() throws IOException { String translation = translateSourceFile( "public class Test { void test() { " + "Deprecated annotation = null; }}", "Test", "Test.m"); assertTranslation(translation, "id<JavaLangDeprecated> annotation = "); } public void testAnnotationTypeLiteral() throws IOException { String translation = translateSourceFile( "@Deprecated public class Test { " + " Deprecated deprecated() { " + " return Test.class.getAnnotation(Deprecated.class); }}", "Test", "Test.m"); assertTranslation(translation, "JavaLangDeprecated_class_()"); } public void testEnumThisCallWithNoArguments() throws IOException { String translation = translateSourceFile( "enum Test { A, B; Test() {} Test(int i) { this(); } }", "Test", "Test.m"); assertTranslation(translation, "JavaLangEnum_initWithNSString_withInt_(self, __name, __ordinal);"); // Called from the "this()" call, the method wrapper, and the allocating constructor. assertOccurrences(translation, "TestEnum_initWithNSString_withInt_(self, __name, __ordinal);", 3); } public void testForStatementWithMultipleInitializers() throws IOException { String translation = translateSourceFile( "class Test { void test() { " + "for (String s1 = null, s2 = null;;) {}}}", "Test", "Test.m"); // C requires that each var have its own pointer. assertTranslation(translation, "for (NSString *s1 = nil, *s2 = nil; ; )"); } // Verify that constant variables are directly referenced when expression is "self". public void testSelfStaticVarAccess() throws IOException { String translation = translateSourceFile( "public class Test { enum Type { TYPE_BOOL; } Type test() { return Type.TYPE_BOOL; }}", "Test", "Test.m"); assertTranslation(translation, "return Test_TypeEnum_get_TYPE_BOOL();"); } public void testMakeQuotedStringHang() throws IOException { // Test hangs if bug makeQuotedString() isn't fixed. translateSourceFile( "public class Test { void test(String s) { assert !\"null\\foo\\nbar\".equals(s); }}", "Test", "Test.m"); } // Verify that the type of superclass field's type variable is cast properly. public void testSuperTypeVariable() throws IOException { addSourceFile("import java.util.List; class TestList <T extends List> { " + " protected final T testField; TestList(T field) { testField = field; }}", "TestList.java"); addSourceFile("import java.util.ArrayList; class TestArrayList extends TestList<ArrayList> { " + " TestArrayList(ArrayList list) { super(list); }}", "TestArrayList.java"); String translation = translateSourceFile( "import java.util.ArrayList; class Test extends TestArrayList { " + " Test(ArrayList list) { super(list); } " + " private class Inner {" + " void test() { testField.ensureCapacity(42); }}}", "Test", "Test.m"); assertTranslation(translation, "[((JavaUtilArrayList *) nil_chk(this$0_->testField_)) ensureCapacityWithInt:42];"); } public void testNoTrigraphs() throws IOException { String translation = translateSourceFile( // C trigraph list from http://en.wikipedia.org/wiki/Digraphs_and_trigraphs#C. "class Test { static final String S1 = \"??=??/??'??(??)??!??<??>??-\"; " // S2 has char sequences that start with ?? but aren't trigraphs. + " static final String S2 = \"??@??$??%??&??*??A??z??1??.\"; }", "Test", "Test.m"); assertTranslation(translation, "S1_ = @\"?\" \"?=?\" \"?/?\" \"?'?\" \"?(?\" \"?)?\" \"?!?\" \"?<?\" \"?>?\" \"?-\";"); assertTranslation(translation, "S2_ = @\"??@??$??%??&??*??A??z??1??.\";"); } // Verify that casting from a floating point primitive to an integral primitive // uses the right cast macro. public void testFloatingPointCasts() throws IOException { String translation = translateSourceFile( "public class Test { " + " byte testByte(float f) { return (byte) f; }" + " char testChar(float f) { return (char) f; }" + " short testShort(float f) { return (short) f; }" + " int testInt(float f) { return (int) f; }" + " long testLong(float f) { return (long) f; }" + " byte testByte(double d) { return (byte) d; }" + " char testChar(double d) { return (char) d; }" + " short testShort(double d) { return (short) d; }" + " int testInt(double d) { return (int) d; }" + " long testLong(double d) { return (long) d; }}", "Test", "Test.m"); // Verify referenced return value is cast. assertTranslatedLines(translation, "- (jbyte)testByteWithFloat:(jfloat)f {", "return (jbyte) J2ObjCFpToInt(f);"); assertTranslatedLines(translation, "- (jchar)testCharWithFloat:(jfloat)f {", "return J2ObjCFpToUnichar(f);"); assertTranslatedLines(translation, "- (jshort)testShortWithFloat:(jfloat)f {", "return (jshort) J2ObjCFpToInt(f);"); assertTranslatedLines(translation, "- (jint)testIntWithFloat:(jfloat)f {", "return J2ObjCFpToInt(f);"); assertTranslatedLines(translation, "- (jlong)testLongWithFloat:(jfloat)f {", "return J2ObjCFpToLong(f);"); assertTranslatedLines(translation, "- (jbyte)testByteWithDouble:(jdouble)d {", "return (jbyte) J2ObjCFpToInt(d);"); assertTranslatedLines(translation, "- (jchar)testCharWithDouble:(jdouble)d {", "return J2ObjCFpToUnichar(d);"); assertTranslatedLines(translation, "- (jshort)testShortWithDouble:(jdouble)d {", "return (jshort) J2ObjCFpToInt(d);"); assertTranslatedLines(translation, "- (jint)testIntWithDouble:(jdouble)d {", "return J2ObjCFpToInt(d);"); assertTranslatedLines(translation, "- (jlong)testLongWithDouble:(jdouble)d {", "return J2ObjCFpToLong(d);"); } // rewrite the java block object into // ObjC block object when calling such method public void testBlockRewriting() throws IOException { String source = "import com.google.j2objc.annotations.*;\n" + "\n" + "interface VoidBlock1<A> {\n" + " @Mapping(\"run:param:\")\n" + " void run(A a, String b);\n" + "}\n" + "public class BlockTester {\n" + " public static void main(final String[] args) {\n" + " BlockTester instance = new BlockTester();\n" + " instance.go(new VoidBlock1<String>() {\n" + " @Override\n" + " public void run(String a, String b) {\n" + " String[] ok = args;\n" + " System.out.println(a);\n" + " System.out.println(b);\n" + " }\n" + " });\n" + " }" + " @Mapping(\"go:\")\n" + " public void go(@Block(ret=\"void\", params={\"NSString *\", \"NSString *\"}) final VoidBlock1<String> hehe) {\n" + " hehe.run(\"hehe\", \"haha\");\n" + " }\n" + "}"; String translation = translateSourceFile(source, "BlockTester", "BlockTester.m"); assertTranslation(translation, "[^void (NSString *____a, NSString *____b) { [___$runner run:____a param:____b];} copy]"); assertTranslation(translation, "return ___$runner == nil ? nil :"); } public void testBlockRewritingWithoutExplicitAnnotation() throws IOException { String source = "import com.google.j2objc.annotations.*;\n" + "\n" + "interface VoidBlock1<A> {\n" + " @Mapping(\"run:param:\")\n" + " void run(A a, boolean b);\n" + "}\n" + "public class BlockTester {\n" + " public static void main(final String[] args) {\n" + " BlockTester instance = new BlockTester();\n" + " instance.go(new VoidBlock1<String>() {\n" + " @Override\n" + " public void run(String a, boolean b) {\n" + " String[] ok = args;\n" + " System.out.println(a);\n" + " System.out.println(b);\n" + " }\n" + " });\n" + " }" + " @Mapping(\"go:\")\n" + " public void go(@Block final VoidBlock1<String> hehe) {\n" + " hehe.run(\"hehe\", false);\n" + " }\n" + "}"; String translation = translateSourceFile(source, "BlockTester", "BlockTester.m"); assertTranslation(translation, "[^void (NSString *____a, jboolean ____b) { [___$runner run:____a param:____b];} copy]"); } public void testDotMapping() throws IOException { String translation = translateSourceFile("import com.google.j2objc.annotations.*;\n" + "\n" + "@Mapping(\"Dummy\")\n" + "class Mapped {\n" + " @DotMapping(\"dot\")\n" + " public native int method();\n" + "\n" + "}\n" + "\n" + "class Implementer {\n" + " public void runTest() {\n" + " Mapped o = (Mapped) new Object();\n" + " int b = o.method();\n" + " }\n" + "}", "Test", "Test.m"); assertTranslation(translation, "jint b = o.dot;"); } public void testGlobalConstant() throws IOException { String translation = translateSourceFile("import com.google.j2objc.annotations.*;\n" + "\n" + "@Mapping(\"Dummy\")\n" + "class Mapped {\n" + " @GlobalConstant(\"constant\")\n" + " static public native int method();\n" + "\n" + "}\n" + "\n" + "class Test {\n" + " public void runTest() {\n" + " int b = Mapped.method();\n" + " }\n" + "}", "Test", "Test.m"); assertTranslation(translation, "jint b = constant;"); } public void testGlobalFunction() throws IOException { String translation = translateSourceFile("import com.google.j2objc.annotations.*;\n" + "\n" + "@Mapping(\"Dummy\")\n" + "class Mapped {\n" + " @GlobalFunction(\"fn\")\n" + " static public native int method();\n" + " @GlobalFunction(\"fn1\")\n" + " static public native int method(int a);\n" + "\n" + "}\n" + "\n" + "class Test {\n" + " public void runTest() {\n" + " int b = Mapped.method();\n" + " int c = Mapped.method(1);\n" + " }\n" + "}", "Test", "Test.m"); assertTranslation(translation, "jint b = fn();"); assertTranslation(translation, "jint c = fn1(1);"); } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-simpleworkflow/src/main/java/com/amazonaws/services/simpleworkflow/model/transform/ContinueAsNewWorkflowExecutionDecisionAttributesMarshaller.java
5226
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.simpleworkflow.model.transform; import java.util.List; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.simpleworkflow.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * ContinueAsNewWorkflowExecutionDecisionAttributesMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class ContinueAsNewWorkflowExecutionDecisionAttributesMarshaller { private static final MarshallingInfo<String> INPUT_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("input").build(); private static final MarshallingInfo<String> EXECUTIONSTARTTOCLOSETIMEOUT_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("executionStartToCloseTimeout").build(); private static final MarshallingInfo<StructuredPojo> TASKLIST_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("taskList").build(); private static final MarshallingInfo<String> TASKPRIORITY_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("taskPriority").build(); private static final MarshallingInfo<String> TASKSTARTTOCLOSETIMEOUT_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("taskStartToCloseTimeout").build(); private static final MarshallingInfo<String> CHILDPOLICY_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("childPolicy").build(); private static final MarshallingInfo<List> TAGLIST_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("tagList").build(); private static final MarshallingInfo<String> WORKFLOWTYPEVERSION_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("workflowTypeVersion").build(); private static final MarshallingInfo<String> LAMBDAROLE_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("lambdaRole").build(); private static final ContinueAsNewWorkflowExecutionDecisionAttributesMarshaller instance = new ContinueAsNewWorkflowExecutionDecisionAttributesMarshaller(); public static ContinueAsNewWorkflowExecutionDecisionAttributesMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(ContinueAsNewWorkflowExecutionDecisionAttributes continueAsNewWorkflowExecutionDecisionAttributes, ProtocolMarshaller protocolMarshaller) { if (continueAsNewWorkflowExecutionDecisionAttributes == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(continueAsNewWorkflowExecutionDecisionAttributes.getInput(), INPUT_BINDING); protocolMarshaller.marshall(continueAsNewWorkflowExecutionDecisionAttributes.getExecutionStartToCloseTimeout(), EXECUTIONSTARTTOCLOSETIMEOUT_BINDING); protocolMarshaller.marshall(continueAsNewWorkflowExecutionDecisionAttributes.getTaskList(), TASKLIST_BINDING); protocolMarshaller.marshall(continueAsNewWorkflowExecutionDecisionAttributes.getTaskPriority(), TASKPRIORITY_BINDING); protocolMarshaller.marshall(continueAsNewWorkflowExecutionDecisionAttributes.getTaskStartToCloseTimeout(), TASKSTARTTOCLOSETIMEOUT_BINDING); protocolMarshaller.marshall(continueAsNewWorkflowExecutionDecisionAttributes.getChildPolicy(), CHILDPOLICY_BINDING); protocolMarshaller.marshall(continueAsNewWorkflowExecutionDecisionAttributes.getTagList(), TAGLIST_BINDING); protocolMarshaller.marshall(continueAsNewWorkflowExecutionDecisionAttributes.getWorkflowTypeVersion(), WORKFLOWTYPEVERSION_BINDING); protocolMarshaller.marshall(continueAsNewWorkflowExecutionDecisionAttributes.getLambdaRole(), LAMBDAROLE_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
StQuote/VisEditor
Runtime/src/com/kotcrab/vis/runtime/util/autotable/ATEnumProperty.java
1077
/* * Copyright 2014-2015 See AUTHORS file. * * 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.kotcrab.vis.runtime.util.autotable; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Target field must have default value set! * @author Kotcrab */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface ATEnumProperty { String fieldName () default ""; Class<? extends EnumNameProvider<?>> uiNameProvider (); }
apache-2.0
jyotisingh/gocd
server/webapp/WEB-INF/rails/spec/presenters/api_v2/user_summary_representer_spec.rb
1521
########################################################################## # Copyright 2017 ThoughtWorks, 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. ########################################################################## require 'rails_helper' describe ApiV2::UserSummaryRepresenter do it 'renders a user summary' do presenter = ApiV2::UserSummaryRepresenter.new("jdoe") actual_json = presenter.to_hash(url_builder: UrlBuilder.new) expect(actual_json).to have_links(:self, :find, :doc, :current_user) expect(actual_json).to have_link(:self).with_url('http://test.host/api/users/jdoe') expect(actual_json).to have_link(:find).with_url('http://test.host/api/users/:login_name') expect(actual_json).to have_link(:current_user).with_url('http://test.host/api/current_user') expect(actual_json).to have_link(:doc).with_url(com.thoughtworks.go.CurrentGoCDVersion.apiDocsUrl '#users') actual_json.delete(:_links) expect(actual_json).to eq({login_name: 'jdoe'}) end end
apache-2.0
jagrosh/MusicBot
src/main/java/com/jagrosh/jmusicbot/Listener.java
4521
/* * Copyright 2016 John Grosh <john.a.grosh@gmail.com>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jagrosh.jmusicbot; import com.jagrosh.jmusicbot.utils.OtherUtil; import java.util.concurrent.TimeUnit; import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.entities.VoiceChannel; import net.dv8tion.jda.api.events.ReadyEvent; import net.dv8tion.jda.api.events.ShutdownEvent; import net.dv8tion.jda.api.events.guild.GuildJoinEvent; import net.dv8tion.jda.api.events.guild.voice.GuildVoiceUpdateEvent; import net.dv8tion.jda.api.events.message.guild.GuildMessageDeleteEvent; import net.dv8tion.jda.api.hooks.ListenerAdapter; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author John Grosh (john.a.grosh@gmail.com) */ public class Listener extends ListenerAdapter { private final Bot bot; public Listener(Bot bot) { this.bot = bot; } @Override public void onReady(ReadyEvent event) { if(event.getJDA().getGuildCache().isEmpty()) { Logger log = LoggerFactory.getLogger("MusicBot"); log.warn("This bot is not on any guilds! Use the following link to add the bot to your guilds!"); log.warn(event.getJDA().getInviteUrl(JMusicBot.RECOMMENDED_PERMS)); } credit(event.getJDA()); event.getJDA().getGuilds().forEach((guild) -> { try { String defpl = bot.getSettingsManager().getSettings(guild).getDefaultPlaylist(); VoiceChannel vc = bot.getSettingsManager().getSettings(guild).getVoiceChannel(guild); if(defpl!=null && vc!=null && bot.getPlayerManager().setUpHandler(guild).playFromDefault()) { guild.getAudioManager().openAudioConnection(vc); } } catch(Exception ignore) {} }); if(bot.getConfig().useUpdateAlerts()) { bot.getThreadpool().scheduleWithFixedDelay(() -> { try { User owner = bot.getJDA().retrieveUserById(bot.getConfig().getOwnerId()).complete(); String currentVersion = OtherUtil.getCurrentVersion(); String latestVersion = OtherUtil.getLatestVersion(); if(latestVersion!=null && !currentVersion.equalsIgnoreCase(latestVersion)) { String msg = String.format(OtherUtil.NEW_VERSION_AVAILABLE, currentVersion, latestVersion); owner.openPrivateChannel().queue(pc -> pc.sendMessage(msg).queue()); } } catch(Exception ex) {} // ignored }, 0, 24, TimeUnit.HOURS); } } @Override public void onGuildMessageDelete(GuildMessageDeleteEvent event) { bot.getNowplayingHandler().onMessageDelete(event.getGuild(), event.getMessageIdLong()); } @Override public void onGuildVoiceUpdate(@NotNull GuildVoiceUpdateEvent event) { bot.getAloneInVoiceHandler().onVoiceUpdate(event); } @Override public void onShutdown(ShutdownEvent event) { bot.shutdown(); } @Override public void onGuildJoin(GuildJoinEvent event) { credit(event.getJDA()); } // make sure people aren't adding clones to dbots private void credit(JDA jda) { Guild dbots = jda.getGuildById(110373943822540800L); if(dbots==null) return; if(bot.getConfig().getDBots()) return; jda.getTextChannelById(119222314964353025L) .sendMessage("This account is running JMusicBot. Please do not list bot clones on this server, <@"+bot.getConfig().getOwnerId()+">.").complete(); dbots.leave().queue(); } }
apache-2.0
danshannon/javastrava-test
src/main/java/test/json/impl/gson/serializer/GenderSerializerTest.java
559
package test.json.impl.gson.serializer; import javastrava.model.reference.StravaGender; /** * @author Dan Shannon * */ public class GenderSerializerTest extends EnumSerializerTest<StravaGender> { /** * @see test.json.impl.gson.serializer.SerializerTest#getClassUnderTest() */ @Override public Class<StravaGender> getClassUnderTest() { return StravaGender.class; } /** * @see test.json.impl.gson.serializer.EnumSerializerTest#getUnknownValue() */ @Override protected StravaGender getUnknownValue() { return StravaGender.UNKNOWN; } }
apache-2.0
googleads/googleads-java-lib
modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v202108/TargetingPresetServiceInterface.java
3245
// 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 // // 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.api.ads.admanager.jaxws.v202108; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.ws.RequestWrapper; import javax.xml.ws.ResponseWrapper; /** * * Service for interacting with Targeting Presets. * * * This class was generated by the JAX-WS RI. * JAX-WS RI 2.2.9-b130926.1035 * Generated source version: 2.1 * */ @WebService(name = "TargetingPresetServiceInterface", targetNamespace = "https://www.google.com/apis/ads/publisher/v202108") @XmlSeeAlso({ ObjectFactory.class }) public interface TargetingPresetServiceInterface { /** * * Gets a {@link TargetingPresetPage} of {@link TargetingPreset} objects that satisfy the given * {@link Statement#query}. The following fields are supported for filtering: * * <table> * <tr> * <th scope="col">PQL Property</th> <th scope="col">Object Property</th> * </tr> * <tr> * <td>{@code id}</td> * <td>{@link TargetingPreset#id}</td> * </tr> * <tr> * <td>{@code name}</td> * <td>{@link TargetingPreset#name}</td> * </tr> * </table> * * @param filterStatement a Publisher Query Language statement used to filter a set of labels. * @return the targeting presets that match the given filter * * * @param filterStatement * @return * returns com.google.api.ads.admanager.jaxws.v202108.TargetingPresetPage * @throws ApiException_Exception */ @WebMethod @WebResult(name = "rval", targetNamespace = "https://www.google.com/apis/ads/publisher/v202108") @RequestWrapper(localName = "getTargetingPresetsByStatement", targetNamespace = "https://www.google.com/apis/ads/publisher/v202108", className = "com.google.api.ads.admanager.jaxws.v202108.TargetingPresetServiceInterfacegetTargetingPresetsByStatement") @ResponseWrapper(localName = "getTargetingPresetsByStatementResponse", targetNamespace = "https://www.google.com/apis/ads/publisher/v202108", className = "com.google.api.ads.admanager.jaxws.v202108.TargetingPresetServiceInterfacegetTargetingPresetsByStatementResponse") public TargetingPresetPage getTargetingPresetsByStatement( @WebParam(name = "filterStatement", targetNamespace = "https://www.google.com/apis/ads/publisher/v202108") Statement filterStatement) throws ApiException_Exception ; }
apache-2.0
OlgaAnay/PFT-18
addressbook/src/com/example/fw/JdbcHelper.java
1291
package com.example.fw; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.example.entities.GroupData; import com.example.utils.SortedListOf; public class JdbcHelper { private Connection conn; public JdbcHelper(ApplicationManager app, String url) { try { Class.forName("com.mysql.jdbc.Driver").newInstance(); } catch (Exception e) { e.printStackTrace(); } try { conn = DriverManager.getConnection(url); } catch (SQLException e) { e.printStackTrace(); } } public SortedListOf<GroupData> listGroups() { SortedListOf<GroupData> groups = new SortedListOf<GroupData>(); Statement st = null; ResultSet res = null; try { st = conn.createStatement(); res = st.executeQuery("SELECT group_id,group_name,group_header,group_footer FROM group_list"); while (res.next()) { GroupData gr = new GroupData().withId(res.getString(1)).withName(res.getString(2)).withHeader(res.getString(3)).withFooter(res.getString(4)); groups.add(gr); } } catch (SQLException e) { e.printStackTrace(); } finally { try { res.close(); st.close(); } catch (SQLException e) { e.printStackTrace(); } } return groups; } }
apache-2.0
baraksu/Interviews
JobTester/Program.cs
258
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JobTester { class Program { static void Main(string[] args) { } } }
apache-2.0
freeVM/freeVM
enhanced/buildtest/tests/functional/src/test/functional/org/apache/harmony/test/func/api/java/util/WeakHashMap/F_WeakHashMapTest_01/F_WeakHashMapTest_01.java
2976
/* * 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. */ /* * Created on 06.09.2005 * * This tests if WeakHashMap. * 1.Create WeakHashMap. * 2.Fill it with key-value pairs, assigning key to null. * 3.Check if the put value is the same with which obtained by get method. * 4.Invoked gc(). * 5.Check if not null values become less. * */ package org.apache.harmony.test.func.api.java.util.WeakHashMap.F_WeakHashMapTest_01; import java.util.*; import org.apache.harmony.test.func.share.ScenarioTest; /** * This tests if WeakHashMap. * 1.Create WeakHashMap. * 2.Fill it with key-value pairs, assigning key to null. * 3.Check if the put value is the same with which obtained by get method. * 4.Invoked gc(). * 5.Check if not null values become less. */ public class F_WeakHashMapTest_01 extends ScenarioTest { private static int NUM = 1000; public static void main(String [] args) { System.exit(new F_WeakHashMapTest_01().test(args)); } public int test() { WeakHashMap whm = new WeakHashMap(); for(int i=0;i<NUM;++i) { String key = "key" + i; String value = "value" + i; whm.put(key, value); key = null; } int GCed = 0; for(int j=0;j<NUM;++j) { String key = "key" + j; String value = (String) whm.get(key); if(value == null) { GCed++; continue; } if(!("value" + j).equals(value)) { return fail("incorrect value " + value + " for key key" + j); } } log.info("GCed = " + GCed); System.gc(); try { Thread.sleep(200); } catch(InterruptedException e) { return fail("InterruptedException thrown"); } log.info("GCing!!!"); int GCed2 = 0; for(int k=0;k<NUM;++k) { String key = "key" + k; String value = (String) whm.get(key); if(value == null) { GCed2++; continue; } if(!("value" + k).equals(value)) { return fail("incorrect value " + value + " for key key" + k); } } log.info("GCed2 = " + GCed2); if(GCed2 == 0) return fail("No values were erased"); return pass(); } }
apache-2.0
cloudfoundry/php-buildpack
fixtures/symfony_5_local_deps/vendor/ocramius/proxy-manager/src/ProxyManager/ProxyGenerator/Util/PublicScopeSimulator.php
6731
<?php declare(strict_types=1); namespace ProxyManager\ProxyGenerator\Util; use Zend\Code\Generator\PropertyGenerator; /** * Generates code necessary to simulate a fatal error in case of unauthorized * access to class members in magic methods even when in child classes and dealing * with protected members. * * @author Marco Pivetta <ocramius@gmail.com> * @license MIT */ class PublicScopeSimulator { const OPERATION_SET = 'set'; const OPERATION_GET = 'get'; const OPERATION_ISSET = 'isset'; const OPERATION_UNSET = 'unset'; /** * Generates code for simulating access to a property from the scope that is accessing a proxy. * This is done by introspecting `debug_backtrace()` and then binding a closure to the scope * of the parent caller. * * @param string $operationType operation to execute: one of 'get', 'set', 'isset' or 'unset' * @param string $nameParameter name of the `name` parameter of the magic method * @param string|null $valueParameter name of the `value` parameter of the magic method * @param PropertyGenerator $valueHolder name of the property containing the target object from which * to read the property. `$this` if none provided * @param string|null $returnPropertyName name of the property to which we want to assign the result of * the operation. Return directly if none provided * * @throws \InvalidArgumentException */ public static function getPublicAccessSimulationCode( string $operationType, string $nameParameter, $valueParameter = null, PropertyGenerator $valueHolder = null, $returnPropertyName = null ) : string { $byRef = self::getByRefReturnValue($operationType); $value = static::OPERATION_SET === $operationType ? ', $value' : ''; $target = '$this'; if ($valueHolder) { $target = '$this->' . $valueHolder->getName(); } return '$realInstanceReflection = new \\ReflectionClass(get_parent_class($this));' . "\n\n" . 'if (! $realInstanceReflection->hasProperty($' . $nameParameter . ')) {' . "\n" . ' $targetObject = ' . $target . ';' . "\n\n" . self::getUndefinedPropertyNotice($operationType, $nameParameter) . ' ' . self::getOperation($operationType, $nameParameter, $valueParameter) . "\n" . " return;\n" . '}' . "\n\n" . '$targetObject = ' . self::getTargetObject($valueHolder) . ";\n" . '$accessor = function ' . $byRef . '() use ($targetObject, $name' . $value . ') {' . "\n" . ' ' . self::getOperation($operationType, $nameParameter, $valueParameter) . "\n" . "};\n" . self::getScopeReBind() . ( $returnPropertyName ? '$' . $returnPropertyName . ' = ' . $byRef . '$accessor();' : '$returnValue = ' . $byRef . '$accessor();' . "\n\n" . 'return $returnValue;' ); } /** * This will generate code that triggers a notice if access is attempted on a non-existing property * * @param string $operationType * @param string $nameParameter * * @return string */ private static function getUndefinedPropertyNotice(string $operationType, string $nameParameter) : string { if (static::OPERATION_GET !== $operationType) { return ''; } return ' $backtrace = debug_backtrace(false);' . "\n" . ' trigger_error(' . "\n" . ' sprintf(' . "\n" . ' \'Undefined property: %s::$%s in %s on line %s\',' . "\n" . ' get_parent_class($this),' . "\n" . ' $' . $nameParameter . ',' . "\n" . ' $backtrace[0][\'file\'],' . "\n" . ' $backtrace[0][\'line\']' . "\n" . ' ),' . "\n" . ' \E_USER_NOTICE' . "\n" . ' );' . "\n"; } /** * Defines whether the given operation produces a reference. * * Note: if the object is a wrapper, the wrapped instance is accessed directly. If the object * is a ghost or the proxy has no wrapper, then an instance of the parent class is created via * on-the-fly unserialization */ private static function getByRefReturnValue(string $operationType) : string { return (static::OPERATION_GET === $operationType || static::OPERATION_SET === $operationType) ? '& ' : ''; } /** * Retrieves the logic to fetch the object on which access should be attempted * * @param PropertyGenerator $valueHolder * * @return string */ private static function getTargetObject(PropertyGenerator $valueHolder = null) : string { if ($valueHolder) { return '$this->' . $valueHolder->getName(); } return 'unserialize(sprintf(\'O:%d:"%s":0:{}\', strlen(get_parent_class($this)), get_parent_class($this)))'; } /** * @throws \InvalidArgumentException */ private static function getOperation(string $operationType, string $nameParameter, ?string $valueParameter) : string { switch ($operationType) { case static::OPERATION_GET: return 'return $targetObject->$' . $nameParameter . ';'; case static::OPERATION_SET: if (null === $valueParameter) { throw new \InvalidArgumentException('Parameter $valueParameter not provided'); } return 'return $targetObject->$' . $nameParameter . ' = $' . $valueParameter . ';'; case static::OPERATION_ISSET: return 'return isset($targetObject->$' . $nameParameter . ');'; case static::OPERATION_UNSET: return 'unset($targetObject->$' . $nameParameter . ');'; } throw new \InvalidArgumentException(sprintf('Invalid operation "%s" provided', $operationType)); } /** * Generates code to bind operations to the parent scope * * @return string */ private static function getScopeReBind() : string { return '$backtrace = debug_backtrace(true);' . "\n" . '$scopeObject = isset($backtrace[1][\'object\'])' . ' ? $backtrace[1][\'object\'] : new \ProxyManager\Stub\EmptyClassStub();' . "\n" . '$accessor = $accessor->bindTo($scopeObject, get_class($scopeObject));' . "\n"; } }
apache-2.0
agwlvssainokuni/springmvctutorial
src/foundation/java/cherry/foundation/AppCtxTag.java
1953
/* * Copyright 2014 agwlvssainokuni * * 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 cherry.foundation; import static cherry.foundation.AppCtxHolder.getAppCtx; import org.springframework.context.ApplicationContext; /** * アプリケーションコンテキスト ({@link ApplicationContext}) が管理するBeanを取出す機能を提供する。<br /> * 特に、JSPカスタムタグ (関数) として使用することを想定する。 */ public class AppCtxTag { /** * 名前とクラスを指定してBeanを取出す。 * * @param name * Beanの名前。 * @param requiredType * Beanのクラス。 * @return 名前とクラスから特定されるBean。 */ public static <T> T getBean(String name, Class<T> requiredType) { return getAppCtx().getBean(name, requiredType); } /** * 名前を指定してBeanを取出す。 * * @param name * Beanの名前。 * @return 名前から特定されるBean。 */ public static Object getBeanByName(String name) { return getAppCtx().getBean(name); } /** * クラスを指定してBeanを取出す。 * * @param requiredType * Beanのクラス。 * @return クラスから特定されるBean。 */ public static <T> T getBeanByClass(Class<T> requiredType) { return getAppCtx().getBean(requiredType); } }
apache-2.0
streamtune/gadget-web
gulp/build.js
3029
'use strict'; var path = require('path'); var gulp = require('gulp'); var conf = require('./conf'); var $ = require('gulp-load-plugins')({ pattern: ['gulp-*', 'main-bower-files', 'uglify-save-license', 'del'] }); gulp.task('partials', function () { return gulp.src([ path.join(conf.paths.src, '/app/**/*.html'), path.join(conf.paths.tmp, '/serve/app/**/*.html') ]) .pipe($.minifyHtml({ empty: true, spare: true, quotes: true })) .pipe($.angularTemplatecache('templateCacheHtml.js', { module: 'gadgetWeb', root: 'app' })) .pipe(gulp.dest(conf.paths.tmp + '/partials/')); }); gulp.task('html', ['inject', 'partials'], function () { var partialsInjectFile = gulp.src(path.join(conf.paths.tmp, '/partials/templateCacheHtml.js'), { read: false }); var partialsInjectOptions = { starttag: '<!-- inject:partials -->', ignorePath: path.join(conf.paths.tmp, '/partials'), addRootSlash: false }; var htmlFilter = $.filter('*.html', { restore: true }); var jsFilter = $.filter('**/*.js', { restore: true }); var cssFilter = $.filter('**/*.css', { restore: true }); var assets; return gulp.src(path.join(conf.paths.tmp, '/serve/*.html')) .pipe($.inject(partialsInjectFile, partialsInjectOptions)) .pipe(assets = $.useref.assets()) .pipe($.rev()) .pipe(jsFilter) .pipe($.sourcemaps.init()) .pipe($.ngAnnotate()) .pipe($.uglify({ preserveComments: $.uglifySaveLicense })).on('error', conf.errorHandler('Uglify')) .pipe($.sourcemaps.write('maps')) .pipe(jsFilter.restore) .pipe(cssFilter) .pipe($.sourcemaps.init()) .pipe($.replace('../../bower_components/bootstrap/fonts/', '../fonts/')) .pipe($.minifyCss({ processImport: false })) .pipe($.sourcemaps.write('maps')) .pipe(cssFilter.restore) .pipe(assets.restore()) .pipe($.useref()) .pipe($.revReplace()) .pipe(htmlFilter) .pipe($.minifyHtml({ empty: true, spare: true, quotes: true, conditionals: true })) .pipe(htmlFilter.restore) .pipe(gulp.dest(path.join(conf.paths.dist, '/'))) .pipe($.size({ title: path.join(conf.paths.dist, '/'), showFiles: true })); }); // Only applies for fonts from bower dependencies // Custom fonts are handled by the "other" task gulp.task('fonts', function () { return gulp.src($.mainBowerFiles()) .pipe($.filter('**/*.{eot,svg,ttf,woff,woff2}')) .pipe($.flatten()) .pipe(gulp.dest(path.join(conf.paths.dist, '/fonts/'))); }); gulp.task('other', function () { var fileFilter = $.filter(function (file) { return file.stat.isFile(); }); return gulp.src([ path.join(conf.paths.src, '/**/*'), path.join('!' + conf.paths.src, '/**/*.{html,css,js,less}') ]) .pipe(fileFilter) .pipe(gulp.dest(path.join(conf.paths.dist, '/'))); }); gulp.task('clean', function () { return $.del([path.join(conf.paths.dist, '/'), path.join(conf.paths.tmp, '/')]); }); gulp.task('build', ['html', 'fonts', 'other']);
apache-2.0
VahidN/Dependency-Injection-Samples
DI11_WinFormsIoc/WinFormsIoc.Services/IEmailsService.cs
160
namespace WinFormsIoc.Services { public interface IEmailsService { void SendEmail(string from, string to, string title, string message); } }
apache-2.0
massfords/we99
we99-domain/src/main/java/edu/harvard/we99/services/storage/UserStorage.java
1408
package edu.harvard.we99.services.storage; import edu.harvard.we99.domain.lists.Users; import edu.harvard.we99.security.RoleName; import edu.harvard.we99.security.User; /** * Storage interface for reading/writing User objects to the system. * * @author mford */ public interface UserStorage extends CRUDStorage<User> { /** * Looks up a user that has the given UUID for their * password. This is only for users that are in the * process of creating a new account. * @param uuid * @param email * @return User or EntityNotFoundException */ User findByUUID(String uuid, String email); /** * Find the user by their email * @param email * @return */ User findByEmail(String email); /** * Returns all of the users that match the given query. The query is considered * as literal text that appears in their first name, last name, or email address. * If no typeAhead is provided then it's a simple listing of all users by name */ Users listAll(Integer page, Integer pageSize, String typeAhead); String resetPassword(Long id); /** * Activates the user account by setting the password in place. * @param uuid * @param email * @param password * @return */ void activate(String uuid, String email, String password); void assignRole(Long id, RoleName roleName); }
apache-2.0
johnewart/shuzai
src/main/java/net/johnewart/shuzai/Frequency.java
488
package net.johnewart.shuzai; import java.util.concurrent.TimeUnit; public class Frequency { public final int offset; public final TimeUnit timeUnit; public Frequency(int offset, TimeUnit timeUnit) { this.offset = offset; this.timeUnit = timeUnit; } public static Frequency of(int offset, TimeUnit timeUnit) { return new Frequency(offset, timeUnit); } public long milliseconds() { return timeUnit.toMillis(offset); } }
apache-2.0
alefherrera/tp1-ing-soft
CinemaCerca/client/app/app.js
351
'use strict'; angular.module('cinemaCercaApp', [ 'ngCookies', 'ngResource', 'ngSanitize', 'ui.router', 'ui.bootstrap', 'ncy-angular-breadcrumb', 'angular-carousel' ]) .config(function ($stateProvider, $urlRouterProvider, $locationProvider) { $urlRouterProvider .otherwise('/'); $locationProvider.html5Mode(true); });
apache-2.0
RonnSanji/sbojze
app/lib/managers/ControllerManager.js
14404
/* * Copyright: Activate Interactive * Date: March 01 2014 * * Title: ControllerManager.js * Description: Manages flow of controllers * * ChangeLog: * * */ //=========================================================================== // REQUIRED FILES //=========================================================================== var Alloy = require("alloy"), _ = require("alloy/underscore")._, Backbone = require("alloy/backbone"); //=========================================================================== // END OF REQUIRED FILES //=========================================================================== //=========================================================================== // MODULE DECLARACTION //=========================================================================== function ControllerManager(){} module.exports = ControllerManager; module.exports.baseView = null; module.exports.defaultController = null; module.exports.prevController = null; module.exports.currController = null; module.exports.arrayControllers = []; module.exports.isRunning = false; //add by me module.exports.baseNavigator = null; module.exports.baseContent = null; module.exports.defaultNavigator = null; module.exports.prevNavigator = null; module.exports.currNavigator = null; module.exports.arrayNavigators = []; //=========================================================================== // END OF MODULE DECLARACTION //=========================================================================== //=========================================================================== // HANDLERS //=========================================================================== // this is to make sure nothing is trigger during animation var OnNavBaseAnimateEnd = function(e) { Alloy.CFG.REF_WIN.SetViewProtector(false); ControllerManager.isRunning = false; Alloy.Globals.Debug("Controller isRunning = " + ControllerManager.isRunning); }; //=========================================================================== // END OF HANDLERS //=========================================================================== //=========================================================================== // EXPORTS //=========================================================================== // initialise module.exports.Init = function(baseView, baseNavigator, baseContent, controller, navigatorController) { ControllerManager.baseView = baseView; ControllerManager.baseNavigator = baseNavigator; ControllerManager.baseContent = baseContent; ControllerManager.defaultController = controller; ControllerManager.currController = controller; ControllerManager.defaultNavigator = navigatorController; ControllerManager.currNavigator = navigatorController; // add default view to parent ControllerManager.baseContent.add(ControllerManager.defaultController.getView()); ControllerManager.baseNavigator.add(ControllerManager.defaultNavigator.getView()); // register listener // Alloy.CFG.REF_NAVIGATION_BAR.RegisterListener({type: Alloy.CFG.NAVBAR_BASE_ANIMATE_END, callback: OnNavBaseAnimateEnd}); }; // switch view module.exports.SwitchView = function(e) { var viewPath = e.path; var navPath = e.navPath; var viewTitle = e.title; var viewID = e.id; // alert(navPath); var nextController = null; var nextView = null; var nextNavigator = null; var nextNavView = null; Alloy.CFG.REF_WIN.SetViewProtector(true); Ti.API.info("******path: ",viewPath); Ti.API.info("******title: ",viewTitle); Ti.API.info("******id: ",viewID); if(viewID != ControllerManager.currController.getView().id) { Ti.API.info("******controller id: ",ControllerManager.currController.getView().id); // use default if error creating controller try { nextController = Alloy.createController(viewPath); nextNavigator = Alloy.createController(navPath); Ti.API.info("******new ncontroller id: ",nextController.getView().id); nextView = nextController.getView(); nextNavView = nextNavigator.getView(); } catch(err) { nextController = ControllerManager.defaultController; nextView = nextController.getView(); nextNavigator = ControllerManager.defaultNavigator; nextNavView = nextNavigator.getView(); } // Alloy.CFG.REF_NAVIGATION_BAR.HideAllBtns(true); if(nextController && nextNavigator) { ControllerManager.baseContent.add(nextView); ControllerManager.baseNavigator.add(nextNavView); if(ControllerManager.currController != null) { ControllerManager.baseContent.remove(ControllerManager.currController.getView()); if(ControllerManager.currController.OnExit && ControllerManager.currController.hasEntered) { ControllerManager.currController.OnExit(); } if(ControllerManager.currController.OnDestroy){ ControllerManager.currController.OnDestroy(); } ControllerManager.currController.destroy(); ControllerManager.currController = null; } ControllerManager.prevController = ControllerManager.currController; ControllerManager.currController = nextController; ControllerManager.prevNavigator = ControllerManager.currNavigator; ControllerManager.currNavigator = nextNavigator; } } // animate view if(Alloy.CFG.REF_VIEW_BASE.rect.x > 0){ Ti.App.fireEvent('showMenu',{}); // Alloy.CFG.REF_WIN.SetViewProtector(false); } // Alloy.CFG.REF_NAVIGATION_BAR.getView("btnMenu").fireEvent("click"); else { Alloy.CFG.REF_WIN.SetViewProtector(false); ControllerManager.isRunning = false; } }; // refresh view module.exports.RefreshView = function(extraParams) { var currPath = ControllerManager.currController.__controllerPath; var viewPath = Alloy.CFG.PATH_DUMMY; var nextController = null; var flagIsLogin = false; // clear any activity indicator //Alloy.Globals.ActivityIndicator.Hide({forceStop: true, note: "ControllerManager RefreshView force stop"}) // refresh if has login status if(ControllerManager.currController.LOGIN_TYPE != null) { // create new controller (a dummy controller) nextController = Alloy.createController(viewPath); if(nextController.OnEnter) nextController.OnEnter(); ControllerManager.baseContent.add(nextController.getView()); ControllerManager.baseContent.remove(ControllerManager.currController.getView()); // destroy current controller if(ControllerManager.currController.OnExit) ControllerManager.currController.OnExit(); if(ControllerManager.currController.OnDestroy) ControllerManager.currController.OnDestroy(); ControllerManager.currController.destroy(); // recreate current controller ControllerManager.currController = Alloy.createController(currPath); var OnIsLoginReturn = function(e) { // add the current controller ControllerManager.baseContent.add(ControllerManager.currController.getView()); flagIsLogin = e; if(flagIsLogin && ControllerManager.currController.OnEnter) { ControllerManager.currController.OnEnter(); if(ControllerManager.currController.OnFirstLoad) ControllerManager.currController.OnFirstLoad(extraParams); ControllerManager.currController.hasEntered = true; } // remove the dummy controller ControllerManager.baseContent.remove(nextController.getView()); if(nextController.OnExit) nextController.OnExit(); if(nextController.OnDestroy) nextController.OnDestroy(); nextController.destroy(); }; Alloy.CFG.REF_NAVIGATION_BAR.HideAllBtns(true); //Alloy.Globals.LoginManager.IsLogin({controllerView: ControllerManager.currController, callback: OnIsLoginReturn}); } }; // add view module.exports.AddView = function(viewPath, navPath, params) { // return if controller is running if(ControllerManager.isRunning == true) return; var flagOnEnter = false; // for loading of loginView // create next controller var nextController = Alloy.createController(viewPath, params); var nextNavigator = Alloy.createController(navPath); // add protector Alloy.CFG.REF_WIN.SetViewProtector(true); ControllerManager.isRunning = true; // exit current controller // Alloy.CFG.REF_NAVIGATION_BAR.HideAllBtns(); if(ControllerManager.currController.OnExit) { ControllerManager.currController.OnExit(); } var baseView = ControllerManager.baseView; var nextView = nextController.getView(); var nextNavView = nextNavigator.getView(); baseView.left = "99%"; ControllerManager.currNavigator.getView().add(nextNavView); ControllerManager.arrayNavigators.push(ControllerManager.prevNavigator); ControllerManager.prevNavigator = ControllerManager.currNavigator; ControllerManager.currNavigator = nextNavigator; ControllerManager.currController.getView().add(nextView); ControllerManager.arrayControllers.push(ControllerManager.prevController); ControllerManager.prevController = ControllerManager.currController; ControllerManager.currController = nextController; //add by me var animation = Titanium.UI.createAnimation(); animation.left = 0; animation.opacity = 1; animation.duration = Alloy.CFG.BASEVIEW_ANINMATE_SPEED; var AnimComplete = function() { animation.removeEventListener("complete", AnimComplete); if(nextController.OnEnter && flagOnEnter == true) { nextController.OnEnter(); if(nextController.OnFirstLoad) nextController.OnFirstLoad(); nextController.hasEntered = true; } // clear protector Alloy.CFG.REF_WIN.SetViewProtector(false); ControllerManager.isRunning = false; }; animation.addEventListener("complete", AnimComplete); baseView.animate(animation); }; // remove view module.exports.RemoveView = function() { // get current view var baseView = ControllerManager.baseView; var currView = ControllerManager.currController.getView(); var currNavView = ControllerManager.currNavigator.getView(); // workaround to fix some stupid issue if(ControllerManager.currController.OnExitWorkaround) { ControllerManager.currController.OnExitWorkaround(); } Alloy.CFG.REF_WIN.SetViewProtector(true); // Alloy.CFG.REF_NAVIGATION_BAR.HideAllBtns(); // exit current controller if(ControllerManager.currController.OnExit && ControllerManager.currController.hasEntered) { ControllerManager.currController.OnExit(); } var animation = Titanium.UI.createAnimation(); animation.left = "99%"; var OnComplete = function(e) { animation.removeEventListener('complete',OnComplete); if(ControllerManager.currController.OnDestroy) { ControllerManager.currController.OnDestroy(); } ControllerManager.prevController.getView().remove(currView); ControllerManager.currController.destroy(); ControllerManager.currController = null; var prevController = ControllerManager.prevController; ControllerManager.currController = ControllerManager.prevController; ControllerManager.prevController = ControllerManager.arrayControllers.pop(); if(prevController.OnEnter) { prevController.OnEnter(); } ControllerManager.prevNavigator.getView().remove(currNavView); ControllerManager.currNavigator.destroy(); ControllerManager.currNavigator = null; ControllerManager.currNavigator = ControllerManager.prevNavigator; ControllerManager.prevNavigator = ControllerManager.arrayNavigators.pop(); // exit current view Alloy.CFG.REF_WIN.SetViewProtector(false); }; animation.addEventListener("complete",OnComplete); currView.animate(animation); }; // return to main module.exports.ReturnToMainView = function(e) { var args = e || {}; var toRefresh = args.toRefresh || false; var extraParams = args.extraParams; var length = ControllerManager.arrayControllers.length; // if previous controller exist if(length > 0) { // exit and destroy current controller if(ControllerManager.currController.OnExit) ControllerManager.currController.OnExit(); if(ControllerManager.currController.OnDestroy) ControllerManager.currController.OnDestroy(); if(length > 1) { // hide previous view ControllerManager.prevController.getView().visible = false; } ControllerManager.prevController.getView().remove(ControllerManager.currController.getView()); ControllerManager.currController.destroy(); for(var i = (length - 1); i >= 1; i--) { if(ControllerManager.prevController.OnDestroy) ControllerManager.prevController.OnDestroy(); // hide previous view if(i > 1) ControllerManager.arrayControllers[i].getView().visible = false; ControllerManager.arrayControllers[i].getView().remove(ControllerManager.prevController.getView()); ControllerManager.prevController.destroy(); ControllerManager.prevController = ControllerManager.arrayControllers[i]; } Alloy.CFG.REF_NAVIGATION_BAR.HideAllBtns(); // enter main controller ControllerManager.currController = ControllerManager.prevController; if(ControllerManager.currController.OnEnter) ControllerManager.currController.OnEnter(extraParams); ControllerManager.prevController = null; // clear the array ControllerManager.arrayControllers.length = 0; } // refresh view if(toRefresh) { //Alloy.Globals.LoginManager.CheckElapsedTime({expiryTime: 5}) ControllerManager.RefreshView(extraParams); } }; // get current controller module.exports.GetCurrentController = function() { return ControllerManager.currController; }; // enter controller after login module.exports.EnterController = function(controller) { if(controller.OnEnter) { controller.OnEnter(); if(controller.OnFirstLoad) controller.OnFirstLoad(); controller.hasEntered = true; } }; // clean up module.exports.Clean = function() { // destroy any existing controller if(ControllerManager.currController != null) { if(ControllerManager.currController.OnExit) ControllerManager.currController.OnExit(); if(ControllerManager.currController.OnDestroy) ControllerManager.currController.OnDestroy(); } // unregister listener Alloy.CFG.REF_NAVIGATION_BAR.UnRegisterListener({type: Alloy.CFG.NAVBAR_BASE_ANIMATE_END, callback: OnNavBaseAnimateEnd}); }; //=========================================================================== // EXPORTS //===========================================================================
apache-2.0
submergerock/avatar-hadoop
src/examples/org/apache/hadoop/examples/terasort/TeraSort.java
8951
/** * 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.examples.terasort; import java.io.IOException; import java.io.PrintStream; import java.net.URI; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.filecache.DistributedCache; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.SequenceFile; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.FileOutputFormat; import org.apache.hadoop.mapred.JobClient; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.Partitioner; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; /** * Generates the sampled split points, launches the job, and waits for it to * finish. * <p> * To run the program: * <b>bin/hadoop jar hadoop-*-examples.jar terasort in-dir out-dir</b> */ public class TeraSort extends Configured implements Tool { private static final Log LOG = LogFactory.getLog(TeraSort.class); /** * A partitioner that splits text keys into roughly equal partitions * in a global sorted order. */ static class TotalOrderPartitioner implements Partitioner<Text,Text>{ private TrieNode trie; private Text[] splitPoints; /** * A generic trie node */ static abstract class TrieNode { private int level; TrieNode(int level) { this.level = level; } abstract int findPartition(Text key); abstract void print(PrintStream strm) throws IOException; int getLevel() { return level; } } /** * An inner trie node that contains 256 children based on the next * character. */ static class InnerTrieNode extends TrieNode { private TrieNode[] child = new TrieNode[256]; InnerTrieNode(int level) { super(level); } int findPartition(Text key) { int level = getLevel(); if (key.getLength() <= level) { return child[0].findPartition(key); } return child[key.getBytes()[level]].findPartition(key); } void setChild(int idx, TrieNode child) { this.child[idx] = child; } void print(PrintStream strm) throws IOException { for(int ch=0; ch < 255; ++ch) { for(int i = 0; i < 2*getLevel(); ++i) { strm.print(' '); } strm.print(ch); strm.println(" ->"); if (child[ch] != null) { child[ch].print(strm); } } } } /** * A leaf trie node that does string compares to figure out where the given * key belongs between lower..upper. */ static class LeafTrieNode extends TrieNode { int lower; int upper; Text[] splitPoints; LeafTrieNode(int level, Text[] splitPoints, int lower, int upper) { super(level); this.splitPoints = splitPoints; this.lower = lower; this.upper = upper; } int findPartition(Text key) { for(int i=lower; i<upper; ++i) { if (splitPoints[i].compareTo(key) >= 0) { return i; } } return upper; } void print(PrintStream strm) throws IOException { for(int i = 0; i < 2*getLevel(); ++i) { strm.print(' '); } strm.print(lower); strm.print(", "); strm.println(upper); } } /** * Read the cut points from the given sequence file. * @param fs the file system * @param p the path to read * @param job the job config * @return the strings to split the partitions on * @throws IOException */ private static Text[] readPartitions(FileSystem fs, Path p, JobConf job) throws IOException { SequenceFile.Reader reader = new SequenceFile.Reader(fs, p, job); List<Text> parts = new ArrayList<Text>(); Text key = new Text(); NullWritable value = NullWritable.get(); while (reader.next(key, value)) { parts.add(key); key = new Text(); } reader.close(); return parts.toArray(new Text[parts.size()]); } /** * Given a sorted set of cut points, build a trie that will find the correct * partition quickly. * @param splits the list of cut points * @param lower the lower bound of partitions 0..numPartitions-1 * @param upper the upper bound of partitions 0..numPartitions-1 * @param prefix the prefix that we have already checked against * @param maxDepth the maximum depth we will build a trie for * @return the trie node that will divide the splits correctly */ private static TrieNode buildTrie(Text[] splits, int lower, int upper, Text prefix, int maxDepth) { int depth = prefix.getLength(); if (depth >= maxDepth || lower == upper) { return new LeafTrieNode(depth, splits, lower, upper); } InnerTrieNode result = new InnerTrieNode(depth); Text trial = new Text(prefix); // append an extra byte on to the prefix trial.append(new byte[1], 0, 1); int currentBound = lower; for(int ch = 0; ch < 255; ++ch) { trial.getBytes()[depth] = (byte) (ch + 1); lower = currentBound; while (currentBound < upper) { if (splits[currentBound].compareTo(trial) >= 0) { break; } currentBound += 1; } trial.getBytes()[depth] = (byte) ch; result.child[ch] = buildTrie(splits, lower, currentBound, trial, maxDepth); } // pick up the rest trial.getBytes()[depth] = 127; result.child[255] = buildTrie(splits, currentBound, upper, trial, maxDepth); return result; } public void configure(JobConf job) { try { FileSystem fs = FileSystem.getLocal(job); Path partFile = new Path(TeraInputFormat.PARTITION_FILENAME); splitPoints = readPartitions(fs, partFile, job); trie = buildTrie(splitPoints, 0, splitPoints.length, new Text(), 2); } catch (IOException ie) { throw new IllegalArgumentException("can't read paritions file", ie); } } public TotalOrderPartitioner() { } public int getPartition(Text key, Text value, int numPartitions) { return trie.findPartition(key); } } public int run(String[] args) throws Exception { LOG.info("starting version : 1"); JobConf job = (JobConf) getConf(); Path inputDir = new Path(args[0]); inputDir = inputDir.makeQualified(inputDir.getFileSystem(job)); Path partitionFile = new Path(inputDir, TeraInputFormat.PARTITION_FILENAME); URI partitionUri = new URI(partitionFile.toString() + "#" + TeraInputFormat.PARTITION_FILENAME); TeraInputFormat.setInputPaths(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); job.setJobName("TeraSort"); job.setJarByClass(TeraSort.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); job.setInputFormat(TeraInputFormat.class); job.setOutputFormat(TeraOutputFormat.class); job.setPartitionerClass(TotalOrderPartitioner.class); TeraInputFormat.writePartitionFile(job, partitionFile); DistributedCache.addCacheFile(partitionUri, job); DistributedCache.createSymlink(job); //job.setInt("dfs.replication", 2); job.setInt("dfs.replication", 1); //job.setBoolean("map.mustlocal", true); job.set("mapred.child.java.opts", "-server -Xmx1000m -Xms64m"); TeraOutputFormat.setFinalSync(job, true); JobClient.runJob(job); LOG.info("done"); return 0; } /** * @param args */ public static void main(String[] args) throws Exception { int res = ToolRunner.run(new JobConf(), new TeraSort(), args); System.exit(res); } }
apache-2.0
schristakidis/p2ner
p2ner/components/plugin/loggergui/loggergui/__init__.py
87
from loggergui import LoggerGui as loggerGUI from vizirloggergui import VizirLoggerGui
apache-2.0
dubswcraft/handson-scala
src/main/java/com/dubswcraft/fp/old/Exercise6_Java_HigherOrderFunctions.java
1566
package java.com.dubswcraft.fp.old; import java.util.ArrayList; import java.util.List; // Exercise 6: The following violates the Open Closed principle, see how you can write this using higher order functions public class Exercise6_Java_HigherOrderFunctions { void processUbsCommission(Trade trade) { // side effecting - just for exercise purposes System.out.println("Commission UBS " + trade.amount * 0.25); } void processCitiCommission(Trade trade) { // side effecting - just for exercise purposes System.out.println("Commission Citi " + trade.amount * 0.15); } void processJPMorganCommission(Trade trade) { System.out.println("Commission JP Morgan " + trade.amount * 0.10); } void processTrades(ArrayList<Trade> trades) { for (Trade trade : trades) { if (trade.bankName == "UBS") processUbsCommission(trade); else if (trade.bankName == "CITI") processCitiCommission(trade); else processJPMorganCommission(trade); } } public static void main(String[] args) { ArrayList<Trade> trades = new ArrayList<Trade>(); trades.add(new Trade("UBS", 1000)); trades.add(new Trade("JP", 300)); trades.add(new Trade("CITI", 1001)); new Exercise6_Java_HigherOrderFunctions().processTrades(trades); } } class Trade { public final String bankName; public final Integer amount; public Trade(String name, Integer amount) { this.bankName = name; this.amount = amount; } }
apache-2.0
infinityb/webplayer
src/foreign_auth/google.rs
2273
use hyper; use hyper::net::HttpsConnector; use hyper_native_tls::NativeTlsClient; use uuid::Uuid; use serde_json; use super::{ Provider, ForeignAccount, ForeignAuthProvider, AuthError, AuthErrorKind, }; const GOOGLE_AUTH_PROVIDER: &'static Provider = &Provider { id: "ba946dd1-94a0-4eae-8260-7bb1f127f286", name: "google", }; pub struct GoogleAuthProvider { expect_audience: String, } impl GoogleAuthProvider { pub fn new(audience: &str) -> GoogleAuthProvider { GoogleAuthProvider { expect_audience: audience.into(), } } } impl GoogleAuthProvider { fn provider(&self) -> &'static Provider { GOOGLE_AUTH_PROVIDER } } pub struct GoogleAuthToken(pub String); #[derive(Serialize, Deserialize, Debug)] struct GoogleAuthResponse { iss: String, aud: String, sub: String, given_name: String, family_name: String, } impl ForeignAuthProvider for GoogleAuthProvider { type Token = GoogleAuthToken; fn authenticate(&self, token: &Self::Token) -> Result<ForeignAccount, AuthError> { let prov_id = self.provider(); let ssl = NativeTlsClient::new().unwrap(); let connector = HttpsConnector::new(ssl); let hycli = hyper::Client::with_connector(connector); let url = format!("https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={}", token.0); let mut resp = try!(hycli.get(&url).send()); if resp.status != hyper::Ok { return Err(AuthError { kind: AuthErrorKind::RemoteServiceError, message: format!("bad status code: {}", resp.status), }); } let aresp: GoogleAuthResponse = try!(serde_json::from_reader(&mut resp) .map_err(|e| AuthError { kind: AuthErrorKind::RemoteServiceError, message: format!("deserialization error: {}", e), })); if aresp.aud != self.expect_audience { return Err(AuthError { kind: AuthErrorKind::InvalidToken, message: "Unexpected audience".into(), }); } Ok(ForeignAccount { provider: prov_id, account_id: aresp.sub.into(), }) } }
apache-2.0
Traderlynk/Etherlynk
communicator/extension/webcam/elements/js/wb-cam-app.63d34b8d-8.js
365
Polymer({ is: "iron-pages", behaviors: [Polymer.IronResizableBehavior, Polymer.IronSelectableBehavior], properties: { activateEvent: { type: String, value: null } }, observers: ["_selectedPageChanged(selected)"], _selectedPageChanged: function(e, a) { this.async(this.notifyResize) } });
apache-2.0
lyg123/sharding-jdbc
sharding-jdbc-example/sharding-jdbc-example-config-spring/src/main/java/com/dangdang/ddframe/rdb/sharding/example/config/spring/SpringNamespaceWithDefaultDataSourceMain.java
1467
/* * Copyright 1999-2015 dangdang.com. * <p> * 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. * </p> */ package com.dangdang.ddframe.rdb.sharding.example.config.spring; import com.dangdang.ddframe.rdb.sharding.example.config.spring.service.OrderService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.sql.SQLException; public final class SpringNamespaceWithDefaultDataSourceMain { // CHECKSTYLE:OFF public static void main(final String[] args) throws SQLException { // CHECKSTYLE:ON ApplicationContext applicationContext = new ClassPathXmlApplicationContext("META-INF/applicationContextWithDefaultDataSource.xml"); OrderService orderService = applicationContext.getBean(OrderService.class); orderService.insert(); orderService.select(); orderService.delete(); orderService.select(); } }
apache-2.0
CBSAdvisor/Xdore
Xdore.Data/XdoreDbInitializer.cs
761
using Xdore.Core; using System; using System.Collections.Generic; using System.Data.Entity; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Xdore.Core.Infrastructure; using Xdore.Migrations; namespace Xdore.Data { internal class XdoreDbInitializer : CreateAndMigrateDatabaseInitializer<XdoreDbCtx, Configuration> { public XdoreDbInitializer() : base() { } protected override void Seed(XdoreDbCtx context) { try { } catch(Exception ex) { ILogger logger = ServiceLocator.Resolve<ILogger>(); logger.Error(ex); } } } }
apache-2.0
artem-aliev/tinkerpop
tinkergraph-gremlin/src/main/java/org/apache/tinkerpop/gremlin/tinkergraph/process/traversal/step/sideEffect/TinkerGraphStep.java
6627
/* * 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.tinkerpop.gremlin.tinkergraph.process.traversal.step.sideEffect; import org.apache.tinkerpop.gremlin.process.traversal.Compare; import org.apache.tinkerpop.gremlin.process.traversal.P; import org.apache.tinkerpop.gremlin.process.traversal.step.HasContainerHolder; import org.apache.tinkerpop.gremlin.process.traversal.step.map.GraphStep; import org.apache.tinkerpop.gremlin.process.traversal.step.util.HasContainer; import org.apache.tinkerpop.gremlin.process.traversal.util.AndP; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Element; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.apache.tinkerpop.gremlin.structure.util.StringFactory; import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph; import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerHelper; import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.stream.Collectors; /** * @author Marko A. Rodriguez (http://markorodriguez.com) * @author Pieter Martin */ public final class TinkerGraphStep<S, E extends Element> extends GraphStep<S, E> implements HasContainerHolder { private final List<HasContainer> hasContainers = new ArrayList<>(); public TinkerGraphStep(final GraphStep<S, E> originalGraphStep) { super(originalGraphStep.getTraversal(), originalGraphStep.getReturnClass(), originalGraphStep.isStartStep(), originalGraphStep.getIds()); originalGraphStep.getLabels().forEach(this::addLabel); // we used to only setIteratorSupplier() if there were no ids OR the first id was instanceof Element, // but that allowed the filter in g.V(v).has('k','v') to be ignored. this created problems for // PartitionStrategy which wants to prevent someone from passing "v" from one TraversalSource to // another TraversalSource using a different partition this.setIteratorSupplier(() -> (Iterator<E>) (Vertex.class.isAssignableFrom(this.returnClass) ? this.vertices() : this.edges())); } private Iterator<? extends Edge> edges() { final TinkerGraph graph = (TinkerGraph) this.getTraversal().getGraph().get(); final HasContainer indexedContainer = getIndexKey(Edge.class); // ids are present, filter on them first if (null == this.ids) return Collections.emptyIterator(); else if (this.ids.length > 0) return this.iteratorList(graph.edges(this.ids)); else return null == indexedContainer ? this.iteratorList(graph.edges()) : TinkerHelper.queryEdgeIndex(graph, indexedContainer.getKey(), indexedContainer.getPredicate().getValue()).stream() .filter(edge -> HasContainer.testAll(edge, this.hasContainers)) .collect(Collectors.<Edge>toList()).iterator(); } private Iterator<? extends Vertex> vertices() { final TinkerGraph graph = (TinkerGraph) this.getTraversal().getGraph().get(); final HasContainer indexedContainer = getIndexKey(Vertex.class); // ids are present, filter on them first if (null == this.ids) return Collections.emptyIterator(); else if (this.ids.length > 0) return this.iteratorList(graph.vertices(this.ids)); else return null == indexedContainer ? this.iteratorList(graph.vertices()) : IteratorUtils.filter(TinkerHelper.queryVertexIndex(graph, indexedContainer.getKey(), indexedContainer.getPredicate().getValue()).iterator(), vertex -> HasContainer.testAll(vertex, this.hasContainers)); } private HasContainer getIndexKey(final Class<? extends Element> indexedClass) { final Set<String> indexedKeys = ((TinkerGraph) this.getTraversal().getGraph().get()).getIndexedKeys(indexedClass); final Iterator<HasContainer> itty = IteratorUtils.filter(hasContainers.iterator(), c -> c.getPredicate().getBiPredicate() == Compare.eq && indexedKeys.contains(c.getKey())); return itty.hasNext() ? itty.next() : null; } @Override public String toString() { if (this.hasContainers.isEmpty()) return super.toString(); else return 0 == this.ids.length ? StringFactory.stepString(this, this.returnClass.getSimpleName().toLowerCase(), this.hasContainers) : StringFactory.stepString(this, this.returnClass.getSimpleName().toLowerCase(), Arrays.toString(this.ids), this.hasContainers); } private <E extends Element> Iterator<E> iteratorList(final Iterator<E> iterator) { final List<E> list = new ArrayList<>(); while (iterator.hasNext()) { final E e = iterator.next(); if (HasContainer.testAll(e, this.hasContainers)) list.add(e); } return list.iterator(); } @Override public List<HasContainer> getHasContainers() { return Collections.unmodifiableList(this.hasContainers); } @Override public void addHasContainer(final HasContainer hasContainer) { if (hasContainer.getPredicate() instanceof AndP) { for (final P<?> predicate : ((AndP<?>) hasContainer.getPredicate()).getPredicates()) { this.addHasContainer(new HasContainer(hasContainer.getKey(), predicate)); } } else this.hasContainers.add(hasContainer); } @Override public int hashCode() { return super.hashCode() ^ this.hasContainers.hashCode(); } }
apache-2.0
xtwxy/actor-editor
plugins/com.wincom.actor.editor.test2/src/com/wincom/actor/editor/test2/policies/ActorContainerHighlightEditPolicy.java
2074
package com.wincom.actor.editor.test2.policies; import org.eclipse.draw2d.IFigure; import org.eclipse.gef.EditPart; import org.eclipse.gef.GraphicalEditPart; import org.eclipse.gef.Request; import org.eclipse.gef.RequestConstants; import org.eclipse.gef.editpolicies.GraphicalEditPolicy; import org.eclipse.swt.graphics.Color; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ActorContainerHighlightEditPolicy extends GraphicalEditPolicy { Logger log = LoggerFactory.getLogger(this.getClass()); private Color revertColor; private static Color highLightColor = new Color(null, 200, 200, 240); /** * @see org.eclipse.gef.EditPolicy#eraseTargetFeedback(org.eclipse.gef.Request) */ public void eraseTargetFeedback(Request request) { log.info("check"); if (revertColor != null) { setContainerBackground(revertColor); revertColor = null; } } private Color getContainerBackground() { log.info("check"); return getContainerFigure().getBackgroundColor(); } private IFigure getContainerFigure() { log.info("check"); return ((GraphicalEditPart) getHost()).getFigure(); } /** * @see org.eclipse.gef.EditPolicy#getTargetEditPart(org.eclipse.gef.Request) */ public EditPart getTargetEditPart(Request request) { log.info("check"); return request.getType().equals(RequestConstants.REQ_SELECTION_HOVER) ? getHost() : null; } private void setContainerBackground(Color c) { log.info("check"); getContainerFigure().setBackgroundColor(c); } /** * Changes the background color of the container to the highlight color */ protected void showHighlight() { log.info("check"); if (revertColor == null) { revertColor = getContainerBackground(); setContainerBackground(highLightColor); } } /** * @see org.eclipse.gef.EditPolicy#showTargetFeedback(org.eclipse.gef.Request) */ public void showTargetFeedback(Request request) { log.info("check"); if (request.getType().equals(RequestConstants.REQ_CREATE) || request.getType().equals(RequestConstants.REQ_ADD)) showHighlight(); } }
apache-2.0
meteorcloudy/bazel
src/main/java/com/google/devtools/build/lib/rules/objc/ObjcImport.java
3741
// Copyright 2014 The Bazel 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 com.google.devtools.build.lib.rules.objc; import com.google.common.collect.ImmutableList; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.actions.MutableActionGraph.ActionConflictException; import com.google.devtools.build.lib.analysis.ConfiguredTarget; import com.google.devtools.build.lib.analysis.RuleConfiguredTargetFactory; import com.google.devtools.build.lib.analysis.RuleContext; import com.google.devtools.build.lib.collect.nestedset.NestedSet; import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder; import com.google.devtools.build.lib.packages.Type; import com.google.devtools.build.lib.rules.cpp.CcInfo; import com.google.devtools.build.lib.rules.cpp.CppSemantics; import java.util.Map; import java.util.TreeMap; /** * Implementation for {@code objc_import}. */ public class ObjcImport implements RuleConfiguredTargetFactory { private final CppSemantics cppSemantics; protected ObjcImport(CppSemantics cppSemantics) { this.cppSemantics = cppSemantics; } @Override public ConfiguredTarget create(RuleContext ruleContext) throws InterruptedException, RuleErrorException, ActionConflictException { CompilationAttributes compilationAttributes = CompilationAttributes.Builder.fromRuleContext(ruleContext).build(); IntermediateArtifacts intermediateArtifacts = ObjcRuleClasses.intermediateArtifacts(ruleContext); CompilationArtifacts compilationArtifacts = new CompilationArtifacts.Builder().build(); ObjcCommon common = new ObjcCommon.Builder(ObjcCommon.Purpose.COMPILE_AND_LINK, ruleContext) .setCompilationArtifacts(compilationArtifacts) .setCompilationAttributes(compilationAttributes) .addDeps(ruleContext.getPrerequisites("deps")) .setIntermediateArtifacts(intermediateArtifacts) .setAlwayslink(ruleContext.attributes().get("alwayslink", Type.BOOLEAN)) .setHasModuleMap() .addExtraImportLibraries(ruleContext.getPrerequisiteArtifacts("archives").list()) .build(); NestedSetBuilder<Artifact> filesToBuild = NestedSetBuilder.stableOrder(); Map<String, NestedSet<Artifact>> outputGroupCollector = new TreeMap<>(); ImmutableList.Builder<Artifact> objectFilesCollector = ImmutableList.builder(); CompilationSupport compilationSupport = new CompilationSupport.Builder(ruleContext, cppSemantics) .setOutputGroupCollector(outputGroupCollector) .setObjectFilesCollector(objectFilesCollector) .build(); compilationSupport.registerCompileAndArchiveActions(common).validateAttributes(); return ObjcRuleClasses.ruleConfiguredTarget(ruleContext, filesToBuild.build()) .addNativeDeclaredProvider(common.getObjcProvider()) .addNativeDeclaredProvider( CcInfo.builder() .setCcCompilationContext(compilationSupport.getCcCompilationContext()) .build()) .addStarlarkTransitiveInfo(ObjcProvider.STARLARK_NAME, common.getObjcProvider()) .build(); } }
apache-2.0
Wattos/JiraSVN
src/JiraSVN.Common/Interfaces/IIdentifiable.cs
1072
#region Copyright 2010 by Roger Knapp, Licensed under the Apache License, Version 2.0 /* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion namespace JiraSVN.Common.Interfaces { /// <summary> /// Represents a displayable and identifiable thing within the issue tracking system. /// </summary> [System.Runtime.InteropServices.ComVisible(false)] public interface IIdentifiable { /// <summary> A unique identifier/name of the item </summary> string Id { get; } /// <summary> The display name of the item </summary> string Name { get; } } }
apache-2.0
motazsaad/tweets-collector
json2xls.py
1721
import xlsxwriter import tweet_cleaner import json import argparse parser = argparse.ArgumentParser(description='extract tweet from json and write them into xls file') parser.add_argument('-i', '--json-file', type=argparse.FileType(mode='r', encoding='utf-8'), help='input json file.', required=True) parser.add_argument('-o', '--out-file', type=str, help='the output file.', required=True) def process_json(json_file, xls_file): workbook = xlsxwriter.Workbook(xls_file) worksheet = workbook.add_worksheet() # Start from the first cell. Rows and columns are zero indexed. row = 0 col = 0 worksheet.write(row, 0, 'id') worksheet.write(row, 1, 'created_at') worksheet.write(row, 2, 'full_text') worksheet.write(row, 3, 'clean_text') row += 1 lines = json_file.readlines() for line in lines: json_tweet = json.loads(line) if 'retweeted_status' in json_tweet: text = json_tweet['retweeted_status']['full_text'] else: text = json_tweet['full_text'] clean_text = tweet_cleaner.clean_tweet(text) clean_text = tweet_cleaner.normalize_arabic(clean_text) clean_text = tweet_cleaner.remove_repeating_char(clean_text) clean_text = tweet_cleaner.keep_only_arabic(clean_text.split()) worksheet.write(row, col, json_tweet['id_str']) worksheet.write(row, col + 1, json_tweet['created_at']) worksheet.write(row, col + 2, text) worksheet.write(row, col + 3, clean_text) row += 1 workbook.close() if __name__ == '__main__': args = parser.parse_args() json_file = args.json_file xls_file = args.out_file process_json(json_file, xls_file)
apache-2.0
findmypast-oss/jackal
cli/reporter/lib/map-results-to-consumer.js
207
'use strict' module.exports = (results) => { return results.reduce((acc, result) => { acc[result.consumer] = acc[result.consumer] || [] acc[result.consumer].push(result) return acc }, {}) }
apache-2.0
vbehar/openshift-flowdock-notifier
Godeps/_workspace/src/github.com/openshift/origin/pkg/cmd/cli/describe/helpers.go
7425
package describe import ( "bytes" "fmt" "regexp" "strings" "text/tabwriter" "time" "github.com/docker/docker/pkg/units" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/util/sets" buildapi "github.com/openshift/origin/pkg/build/api" "github.com/openshift/origin/pkg/client" imageapi "github.com/openshift/origin/pkg/image/api" ) const emptyString = "<none>" func tabbedString(f func(*tabwriter.Writer) error) (string, error) { out := new(tabwriter.Writer) buf := &bytes.Buffer{} out.Init(buf, 0, 8, 1, '\t', 0) err := f(out) if err != nil { return "", err } out.Flush() str := string(buf.String()) return str, nil } func toString(v interface{}) string { value := fmt.Sprintf("%v", v) if len(value) == 0 { value = emptyString } return value } func bold(v interface{}) string { return "\033[1m" + toString(v) + "\033[0m" } func convertEnv(env []api.EnvVar) map[string]string { result := make(map[string]string, len(env)) for _, e := range env { result[e.Name] = toString(e.Value) } return result } func formatEnv(env api.EnvVar) string { if env.ValueFrom != nil && env.ValueFrom.FieldRef != nil { return fmt.Sprintf("%s=<%s>", env.Name, env.ValueFrom.FieldRef.FieldPath) } return fmt.Sprintf("%s=%s", env.Name, env.Value) } func formatString(out *tabwriter.Writer, label string, v interface{}) { fmt.Fprintf(out, fmt.Sprintf("%s:\t%s\n", label, toString(v))) } func formatTime(out *tabwriter.Writer, label string, t time.Time) { fmt.Fprintf(out, fmt.Sprintf("%s:\t%s ago\n", label, formatRelativeTime(t))) } func formatLabels(labelMap map[string]string) string { return labels.Set(labelMap).String() } func extractAnnotations(annotations map[string]string, keys ...string) ([]string, map[string]string) { extracted := make([]string, len(keys)) remaining := make(map[string]string) for k, v := range annotations { remaining[k] = v } for i, key := range keys { extracted[i] = remaining[key] delete(remaining, key) } return extracted, remaining } func formatMapStringString(out *tabwriter.Writer, label string, items map[string]string) { keys := sets.NewString() for k := range items { keys.Insert(k) } if keys.Len() == 0 { formatString(out, label, "") return } for i, key := range keys.List() { if i == 0 { formatString(out, label, fmt.Sprintf("%s=%s", key, items[key])) } else { fmt.Fprintf(out, "%s\t%s=%s\n", "", key, items[key]) } } } func formatAnnotations(out *tabwriter.Writer, m api.ObjectMeta, prefix string) { values, annotations := extractAnnotations(m.Annotations, "description") if len(values[0]) > 0 { formatString(out, prefix+"Description", values[0]) } formatMapStringString(out, prefix+"Annotations", annotations) } var timeNowFn = func() time.Time { return time.Now() } func formatRelativeTime(t time.Time) string { return units.HumanDuration(timeNowFn().Sub(t)) } // FormatRelativeTime converts a time field into a human readable age string (hours, minutes, days). func FormatRelativeTime(t time.Time) string { return formatRelativeTime(t) } func formatMeta(out *tabwriter.Writer, m api.ObjectMeta) { formatString(out, "Name", m.Name) if !m.CreationTimestamp.IsZero() { formatTime(out, "Created", m.CreationTimestamp.Time) } formatString(out, "Labels", formatLabels(m.Labels)) formatAnnotations(out, m, "") } // webhookURL assembles map with of webhook type as key and webhook url and value func webhookURL(c *buildapi.BuildConfig, cli client.BuildConfigsNamespacer) map[string]string { result := map[string]string{} for _, trigger := range c.Spec.Triggers { whTrigger := "" switch trigger.Type { case buildapi.GitHubWebHookBuildTriggerType: whTrigger = trigger.GitHubWebHook.Secret case buildapi.GenericWebHookBuildTriggerType: whTrigger = trigger.GenericWebHook.Secret } if len(whTrigger) == 0 { continue } out := "" url, err := cli.BuildConfigs(c.Namespace).WebHookURL(c.Name, &trigger) if err != nil { out = fmt.Sprintf("<error: %s>", err.Error()) } else { out = url.String() } result[string(trigger.Type)] = out } return result } var reLongImageID = regexp.MustCompile(`[a-f0-9]{60,}$`) // shortenImagePullSpec returns a version of the pull spec intended for display, which may // result in the image not being usable via cut-and-paste for users. func shortenImagePullSpec(spec string) string { if reLongImageID.MatchString(spec) { return spec[:len(spec)-50] + "..." } return spec } func formatImageStreamTags(out *tabwriter.Writer, stream *imageapi.ImageStream) { if len(stream.Status.Tags) == 0 && len(stream.Spec.Tags) == 0 { fmt.Fprintf(out, "Tags:\t<none>\n") return } fmt.Fprint(out, "\nTag\tSpec\tCreated\tPullSpec\tImage\n") sortedTags := []string{} for k := range stream.Status.Tags { sortedTags = append(sortedTags, k) } for k := range stream.Spec.Tags { if _, ok := stream.Status.Tags[k]; !ok { sortedTags = append(sortedTags, k) } } imageapi.PrioritizeTags(sortedTags) for _, tag := range sortedTags { tagRef, ok := stream.Spec.Tags[tag] specTag := "" if ok { if tagRef.From != nil { namePair := "" if len(tagRef.From.Namespace) > 0 && tagRef.From.Namespace != stream.Namespace { namePair = fmt.Sprintf("%s/%s", tagRef.From.Namespace, tagRef.From.Name) } else { namePair = tagRef.From.Name } switch tagRef.From.Kind { case "ImageStreamTag", "ImageStreamImage": specTag = namePair case "DockerImage": specTag = tagRef.From.Name default: specTag = fmt.Sprintf("<unknown %s> %s", tagRef.From.Kind, namePair) } } } else { specTag = "<pushed>" } if taglist, ok := stream.Status.Tags[tag]; ok { if len(taglist.Conditions) > 0 { var lastTime time.Time summary := []string{} for _, condition := range taglist.Conditions { if condition.LastTransitionTime.After(lastTime) { lastTime = condition.LastTransitionTime.Time } switch condition.Type { case imageapi.ImportSuccess: if condition.Status == api.ConditionFalse { summary = append(summary, fmt.Sprintf("import failed: %s", condition.Message)) } default: summary = append(summary, string(condition.Type)) } } if len(summary) > 0 { description := strings.Join(summary, ", ") if len(description) > 70 { description = strings.TrimSpace(description[:70-3]) + "..." } d := timeNowFn().Sub(lastTime) fmt.Fprintf(out, "%s\t%s\t%s ago\t%s\t%v\n", tag, shortenImagePullSpec(specTag), units.HumanDuration(d), "", description) } } for i, event := range taglist.Items { d := timeNowFn().Sub(event.Created.Time) image := event.Image ref, err := imageapi.ParseDockerImageReference(event.DockerImageReference) if err == nil { if ref.ID == image { image = "<same>" } } pullSpec := event.DockerImageReference if pullSpec == specTag { pullSpec = "<same>" } else { pullSpec = shortenImagePullSpec(pullSpec) } specTag = shortenImagePullSpec(specTag) if i != 0 { tag, specTag = "", "" } fmt.Fprintf(out, "%s\t%s\t%s ago\t%s\t%v\n", tag, specTag, units.HumanDuration(d), pullSpec, image) } } else { fmt.Fprintf(out, "%s\t%s\t\t<not available>\t<not available>\n", tag, specTag) } } }
apache-2.0
cniweb/ant-contrib
ant-contrib/src/main/java/net/sf/antcontrib/logic/TimestampSelector.java
7058
/* * Copyright (c) 2001-2004 Ant-Contrib project. 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 net.sf.antcontrib.logic; import java.io.File; import java.util.Vector; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.types.Reference; /*** * Task definition for the foreach task. The foreach task iterates over a list, * a list of filesets, or both. * * <pre> * * Usage: * * Task declaration in the project: * <code> * &lt;taskdef name="latesttimestamp" classname="net.sf.antcontrib.logic.TimestampSelector" /&gt; * </code> * * Call Syntax: * <code> * &lt;timestampselector * [property="prop" | outputsetref="id"] * [count="num"] * [age="eldest|youngest"] * [pathSep=","] * [pathref="ref"] &gt; * &lt;path&gt; * ... * &lt;/path&gt; * &lt;/latesttimestamp&gt; * </code> * * Attributes: * outputsetref --> The reference of the output Path set which will contain the * files with the latest timestamps. * property --> The name of the property to set with file having the latest * timestamp. If you specify the "count" attribute, you will get * the lastest N files. These will be the absolute pathnames * count --> How many of the latest files do you wish to find * pathSep --> What to use as the path separator when using the "property" * attribute, in conjunction with the "count" attribute * pathref --> The reference of the path which is the input set of files. * * </pre> * * @author <a href="mailto:mattinger@yahoo.com">Matthew Inger</a> */ public class TimestampSelector extends Task { private static final String AGE_ELDEST = "eldest"; private static final String AGE_YOUNGEST = "youngest"; private String property; private Path path; private String outputSetId; private int count = 1; private char pathSep = ','; private String age = AGE_YOUNGEST; /*** * Default Constructor */ public TimestampSelector() { super(); } public void doFileSetExecute(String paths[]) throws BuildException { } // Sorts entire array public void sort(Vector array) { sort(array, 0, array.size() - 1); } // Sorts partial array protected void sort(Vector array, int start, int end) { int p; if (end > start) { p = partition(array, start, end); sort(array, start, p - 1); sort(array, p + 1, end); } } protected int compare(File a, File b) { if (age.equalsIgnoreCase(AGE_ELDEST)) return new Long(a.lastModified()).compareTo(new Long(b.lastModified())); else return new Long(b.lastModified()).compareTo(new Long(a.lastModified())); } protected int partition(Vector array, int start, int end) { int left, right; File partitionElement; partitionElement = (File) array.elementAt(end); left = start - 1; right = end; for (;;) { while (compare(partitionElement, (File) array.elementAt(++left)) == 1) { if (left == end) break; } while (compare(partitionElement, (File) array.elementAt(--right)) == -1) { if (right == start) break; } if (left >= right) break; swap(array, left, right); } swap(array, left, end); return left; } protected void swap(Vector array, int i, int j) { Object temp; temp = array.elementAt(i); array.setElementAt(array.elementAt(j), i); array.setElementAt(temp, j); } public void execute() throws BuildException { if (property == null && outputSetId == null) throw new BuildException("Property or OutputSetId must be specified."); if (path == null) throw new BuildException("A path element or pathref attribute must be specified."); // Figure out the list of existing file elements // from the designated path String s[] = path.list(); Vector v = new Vector(); for (int i = 0; i < s.length; i++) { File f = new File(s[i]); if (f.exists()) v.addElement(f); } // Sort the vector, need to make java 1.1 compliant sort(v); // Pull off the first N items Vector v2 = new Vector(); int sz = v.size(); for (int i = 0; i < sz && i < count; i++) v2.add(v.elementAt(i)); // Build the resulting Path object Path path = new Path(getProject()); sz = v2.size(); for (int i = 0; i < sz; i++) { File f = (File) (v.elementAt(i)); Path p = new Path(getProject(), f.getAbsolutePath()); path.addExisting(p); } if (outputSetId != null) { // Add the reference to the project getProject().addReference(outputSetId, path); } else { // Concat the paths, and put them in a property // which is separated list of the files, using the // "pathSep" attribute as the separator String paths[] = path.list(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < paths.length; i++) { if (i != 0) sb.append(pathSep); sb.append(paths[i]); } if (paths.length != 0) getProject().setProperty(property, sb.toString()); } } public void setProperty(String property) { if (outputSetId != null) throw new BuildException("Cannot set both Property and OutputSetId."); this.property = property; } public void setCount(int count) { this.count = count; } public void setAge(String age) { if (age.equalsIgnoreCase(AGE_ELDEST) || age.equalsIgnoreCase(AGE_YOUNGEST)) this.age = age; else throw new BuildException("Invalid age: " + age); } public void setPathSep(char pathSep) { this.pathSep = pathSep; } public void setOutputSetId(String outputSetId) { if (property != null) throw new BuildException("Cannot set both Property and OutputSetId."); this.outputSetId = outputSetId; } public void setPathRef(Reference ref) throws BuildException { if (path == null) { path = new Path(getProject()); path.setRefid(ref); } else { throw new BuildException("Path element already specified."); } } public Path createPath() throws BuildException { if (path == null) path = new Path(getProject()); else throw new BuildException("Path element already specified."); return path; } }
apache-2.0
csgordon/SJS
sjsc/src/test/resources/testinput/constraints/constructor7.js
140
function C() { this.f = function() { this.g = "hello"; } } var x = new C(); console.log(x.g + ""); // error: g does not exist on C
apache-2.0
hanyahui88/swifts
src/main/java/com/swifts/frame/modules/act/utils/DateConverter.java
2644
/** * Copyright &copy; 2015-2016 <a href="https://github.com/hanyahui88/swifts">swifts</a> All rights reserved. */ package com.swifts.frame.modules.act.utils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.commons.beanutils.Converter; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.time.DateUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 日期转换类 * @author ThinkGem * @version 2013-11-03 */ public class DateConverter implements Converter { private static final Logger logger = LoggerFactory.getLogger(DateConverter.class); private static final String DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss"; private static final String DATETIME_PATTERN_NO_SECOND = "yyyy-MM-dd HH:mm"; private static final String DATE_PATTERN = "yyyy-MM-dd"; private static final String MONTH_PATTERN = "yyyy-MM"; @SuppressWarnings({ "rawtypes", "unchecked" }) public Object convert(Class type, Object value) { Object result = null; if (type == Date.class) { try { result = doConvertToDate(value); } catch (ParseException e) { e.printStackTrace(); } } else if (type == String.class) { result = doConvertToString(value); } return result; } /** * Convert String to Date * * @param value * @return * @throws ParseException */ private Date doConvertToDate(Object value) throws ParseException { Date result = null; if (value instanceof String) { result = DateUtils.parseDate((String) value, new String[] { DATE_PATTERN, DATETIME_PATTERN, DATETIME_PATTERN_NO_SECOND, MONTH_PATTERN }); // all patterns failed, try a milliseconds constructor if (result == null && StringUtils.isNotEmpty((String) value)) { try { result = new Date(new Long((String) value).longValue()); } catch (Exception e) { logger.error("Converting from milliseconds to Date fails!"); e.printStackTrace(); } } } else if (value instanceof Object[]) { // let's try to convert the first element only Object[] array = (Object[]) value; if (array.length >= 1) { value = array[0]; result = doConvertToDate(value); } } else if (Date.class.isAssignableFrom(value.getClass())) { result = (Date) value; } return result; } /** * Convert Date to String * * @param value * @return */ private String doConvertToString(Object value) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATETIME_PATTERN); String result = null; if (value instanceof Date) { result = simpleDateFormat.format(value); } return result; } }
apache-2.0
vlorc/gioc
module/operation/declare.go
2692
// Copyright 2017 Granitic. All rights reserved. // Use of this source code is governed by an Apache 2.0 license that can be found in the LICENSE file at the root of this project. package operation import ( "github.com/vlorc/gioc/factory" "github.com/vlorc/gioc/module" "github.com/vlorc/gioc/types" "github.com/vlorc/gioc/utils" ) type DeclareHandle func(*DeclareContext) func Declare(handle ...DeclareHandle) module.ModuleInitHandle { return declare(currentRegister, toDeclare, handle) } func Export(handle ...DeclareHandle) module.ModuleInitHandle { return declare(parentRegister, toExport, handle) } func Primary(handle ...DeclareHandle) module.ModuleInitHandle { return PrimaryWith(parentRegister, handle...) } func Miss(handle ...DeclareHandle) module.ModuleInitHandle { return MissWith(parentRegister, handle...) } func PrimaryWith(register func(*module.ModuleInitContext) types.Register, handle ...DeclareHandle) module.ModuleInitHandle { return declare(register, toPrimary, handle) } func MissWith(register func(*module.ModuleInitContext) types.Register, handle ...DeclareHandle) module.ModuleInitHandle { return declare(register, toMiss, handle) } func declare(register func(*module.ModuleInitContext) types.Register, done func(*DeclareContext), handle []DeclareHandle) module.ModuleInitHandle { return func(ctx *module.ModuleInitContext) { dc := &DeclareContext{done: done, register: register, Context: ctx} for _, v := range handle { v(dc) } dc.Reset() } } func currentRegister(ctx *module.ModuleInitContext) types.Register { return ctx.Container().AsRegister() } func parentRegister(ctx *module.ModuleInitContext) types.Register { return ctx.Parent().AsRegister() } func toDeclare(ctx *DeclareContext) { ctx.register(ctx.Context).Factory(ctx.Factory, ctx.Type, ctx.Name) } func toExport(ctx *DeclareContext) { var bean types.BeanFactory if nil != ctx.Dependency { bean = factory.NewExportFactory(ctx.Factory, lazyProvider(ctx.Context.Container)) } else { bean = ctx.Factory } ctx.register(ctx.Context).Factory(bean, ctx.Type, ctx.Name) } func toPrimary(ctx *DeclareContext) { var bean types.BeanFactory if nil != ctx.Dependency { bean = factory.NewExportFactory(ctx.Factory, lazyProvider(ctx.Context.Container)) } else { bean = ctx.Factory } ctx.register(ctx.Context).Selector().Set(utils.TypeOf(ctx.Type), ctx.Name, bean) } func toMiss(ctx *DeclareContext) { var bean types.BeanFactory if nil != ctx.Dependency { bean = factory.NewExportFactory(ctx.Factory, lazyProvider(ctx.Context.Container)) } else { bean = ctx.Factory } ctx.register(ctx.Context).Selector().Put(utils.TypeOf(ctx.Type), ctx.Name, bean) }
apache-2.0
zhangzuoqiang/summer
src/main/java/cn/limw/summer/dubbo/common/util/UrlUtil.java
1197
package cn.limw.summer.dubbo.common.util; import com.alibaba.dubbo.common.URL; /** * @author li * @version 1 (2015年6月1日 上午9:49:01) * @since Java7 */ public class UrlUtil { /** * @see com.alibaba.dubbo.common.URL#buildString(boolean, boolean, boolean, boolean, String...) */ public static String toSimpleString(URL url) { StringBuilder buf = new StringBuilder(); if (url.getProtocol() != null && url.getProtocol().length() > 0) { buf.append(url.getProtocol()); buf.append("://"); } String host = url.getIp(); if (host != null && host.length() > 0) { buf.append(host); if (url.getPort() > 0) { buf.append(":"); buf.append(url.getPort()); } } String path; // if (useService) { // path = url.getServiceKey(); // } else { path = url.getPath(); // } if (path != null && path.length() > 0) { buf.append("/"); buf.append(path); } return buf.toString(); } }
apache-2.0
TomaszMolenda/mediciline
src/main/webapp/WEB-INF/resources/js/user/functions.js
2095
var name, email, confirmEmail, password, confirmPassword, isValidate function sendRegister() { name = $('#name').val(); email = $('#email').val(); confirmEmail = $('#confirmEmail').val(); password = $('#password').val(); confirmPassword = $('#confirmPassword').val(); isValidate = true; $('#error').html(''); validate(); if(isValidate) { var json = {"name" : name, "email" : email, "confirmEmail" : confirmEmail, "password" : password, "confirmPassword" : confirmPassword}; $.ajax({ url: '/api/register', data: JSON.stringify(json), type: 'POST', beforeSend: function(xhr) { $('#addModalError').html(''); xhr.setRequestHeader("Accept", "application/json"); xhr.setRequestHeader("Content-Type", "application/json"); $('#loading').prop('hidden', false); $('#button').prop('disabled', true); }, success: function(data){ $('input').val(''); $('#info').append(/*[[#{SendedRegistrationLink}]]*/ + "").show(); $('#loading').prop('hidden', true); $('#button').prop('disabled', false); },// error: function(xhr) { console.log(xhr) var json = JSON.parse(xhr.responseJSON); $.each(json.errors, function(index, e) { $('#error').append(e.message + "<br>"); }); $('#error').show().delay(5000).fadeOut(); $('#loading').prop('hidden', true); $('#button').prop('disabled', false); }, complete: function(data){ } }); } else $('#error').show().delay(5000).fadeOut(); } function validate() { if(name == '') { $('#error').append(/*[[#{NameEmpty}]]*/ + "<br>"); isValidate = false; } if(email == '') { $('#error').append(/*[[#{EmailEmpty}]]*/ + "<br>"); isValidate = false; } if(password == '') { $('#error').append(/*[[#{PasswordEmpty}]]*/ + "<br>"); isValidate = false; } if(email != confirmEmail) { $('#error').append(/*[[#{EmailNotTheSame}]]*/ + "<br>"); isValidate = false; } if(password != confirmPassword) { $('#error').append(/*[[#{PasswordNotTheSame}]]*/ + "<br>"); isValidate = false; } }
apache-2.0
seirion/code
short/gcd.cpp
130
int gcd(int a, int b) { return (a % b == 0) ? b : gcd(b, a % b); } int lcm(int a, int b) { return a * b / gcd(a, b); }
apache-2.0
RepIR/RepIRProximity
src/main/java/io/github/repir/Strategy/SpeedAnalyzerPLM.java
1130
package io.github.repir.Strategy; import io.github.repir.Strategy.Operator.Analyzer; import io.github.repir.Retriever.Query; import io.github.repir.Retriever.Retriever; import io.github.repir.Strategy.Collector.CollectorDocumentSpeed; import io.github.repir.Strategy.Collector.SpeedCollector; import io.github.htools.lib.Log; /** * Measures the retrieval speed by setting up a SpeedCollector. * <p/> * @author jeroen */ public class SpeedAnalyzerPLM extends PLMRetrievalModel implements Analyzer { public static Log log = new Log(SpeedAnalyzerPLM.class); public SpeedCollector collector; public SpeedAnalyzerPLM(Retriever retriever) { super(retriever); } @Override public void setCollector() { new CollectorDocumentSpeed(this); collector = new SpeedCollector(this); } @Override public void prepareWriteReduce(Query q) { } @Override public void writeReduce(Query q) { } @Override public void finishWriteReduce() { } @Override public final void prepareRetrieval() { log.sleepRnd(5000); super.prepareRetrieval(); } }
apache-2.0
BBCVisualJournalism/newsspec_7166
source/js/app.js
364
define(['lib/news_special/bootstrap', 'lib/news_special/share_tools/controller'], function (news, shareTools) { return { init: function (storyPageUrl) { news.$('.main select').on('change', function () { var url = news.$(this).val(); window.parent.location.href = url; }); } }; });
apache-2.0
mcculls/bnd
biz.aQute.bndlib/src/aQute/bnd/osgi/Descriptors.java
14512
package aQute.bnd.osgi; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.osgi.annotation.versioning.ProviderType; import aQute.libg.generics.Create; public class Descriptors { Map<String,TypeRef> typeRefCache = Create.map(); Map<String,Descriptor> descriptorCache = Create.map(); Map<String,PackageRef> packageCache = Create.map(); // MUST BE BEFORE PRIMITIVES, THEY USE THE DEFAULT PACKAGE!! final static PackageRef DEFAULT_PACKAGE = new PackageRef(); final static PackageRef PRIMITIVE_PACKAGE = new PackageRef(); final static TypeRef VOID = new ConcreteRef("V", "void", PRIMITIVE_PACKAGE); final static TypeRef BOOLEAN = new ConcreteRef("Z", "boolean", PRIMITIVE_PACKAGE); final static TypeRef BYTE = new ConcreteRef("B", "byte", PRIMITIVE_PACKAGE); final static TypeRef CHAR = new ConcreteRef("C", "char", PRIMITIVE_PACKAGE); final static TypeRef SHORT = new ConcreteRef("S", "short", PRIMITIVE_PACKAGE); final static TypeRef INTEGER = new ConcreteRef("I", "int", PRIMITIVE_PACKAGE); final static TypeRef LONG = new ConcreteRef("J", "long", PRIMITIVE_PACKAGE); final static TypeRef DOUBLE = new ConcreteRef("D", "double", PRIMITIVE_PACKAGE); final static TypeRef FLOAT = new ConcreteRef("F", "float", PRIMITIVE_PACKAGE); public enum SignatureType { TYPEVAR, METHOD, FIELD; } public class Signature { public Map<String,Signature> typevariables = new HashMap<>(); public Signature type; public List<Signature> parameters; } { packageCache.put("", DEFAULT_PACKAGE); } @ProviderType public interface TypeRef extends Comparable<TypeRef> { String getBinary(); String getShorterName(); String getFQN(); String getPath(); boolean isPrimitive(); TypeRef getComponentTypeRef(); TypeRef getClassRef(); PackageRef getPackageRef(); String getShortName(); boolean isJava(); boolean isObject(); String getSourcePath(); String getDottedOnly(); } public static class PackageRef implements Comparable<PackageRef> { final String binaryName; final String fqn; final boolean java; PackageRef(String binaryName) { this.binaryName = fqnToBinary(binaryName); this.fqn = binaryToFQN(binaryName); this.java = this.fqn.startsWith("java."); // && // !this.fqn.equals("java.sql)" // For some reason I excluded java.sql but the classloader will // delegate anyway. So lost the understanding why I did it?? } PackageRef() { this.binaryName = ""; this.fqn = "."; this.java = false; } public PackageRef getDuplicate() { return new PackageRef(binaryName + Constants.DUPLICATE_MARKER); } public String getFQN() { return fqn; } public String getBinary() { return binaryName; } public String getPath() { return binaryName; } public boolean isJava() { return java; } @Override public String toString() { return fqn; } boolean isDefaultPackage() { return this.fqn.equals("."); } boolean isPrimitivePackage() { return this == PRIMITIVE_PACKAGE; } public int compareTo(PackageRef other) { return fqn.compareTo(other.fqn); } @Override public boolean equals(Object o) { assert o instanceof PackageRef; return o == this; } @Override public int hashCode() { return super.hashCode(); } /** * Decide if the package is a metadata package. * */ public boolean isMetaData() { if (isDefaultPackage()) return true; for (int i = 0; i < Constants.METAPACKAGES.length; i++) { if (fqn.startsWith(Constants.METAPACKAGES[i])) return true; } return false; } } // We "intern" the private static class ConcreteRef implements TypeRef { final String binaryName; final String fqn; final boolean primitive; final PackageRef packageRef; ConcreteRef(PackageRef packageRef, String binaryName) { this.binaryName = binaryName; this.fqn = binaryToFQN(binaryName); this.primitive = false; this.packageRef = packageRef; } ConcreteRef(String binaryName, String fqn, PackageRef pref) { this.binaryName = binaryName; this.fqn = fqn; this.primitive = true; this.packageRef = pref; } public String getBinary() { return binaryName; } public String getPath() { return binaryName + ".class"; } public String getSourcePath() { return binaryName + ".java"; } public String getFQN() { return fqn; } public String getDottedOnly() { return fqn.replace('$', '.'); } public boolean isPrimitive() { return primitive; } public TypeRef getComponentTypeRef() { return null; } public TypeRef getClassRef() { return this; } public PackageRef getPackageRef() { return packageRef; } public String getShortName() { int n = binaryName.lastIndexOf('/'); return binaryName.substring(n + 1); } @Override public String getShorterName() { String name = getShortName(); int n = name.lastIndexOf('$'); if (n <= 0) return name; return name.substring(n + 1); } public boolean isJava() { return packageRef.isJava(); } @Override public String toString() { return fqn; } public boolean isObject() { return fqn.equals("java.lang.Object"); } @Override public boolean equals(Object other) { assert other instanceof TypeRef; return this == other; } public int compareTo(TypeRef other) { if (this == other) return 0; return fqn.compareTo(other.getFQN()); } @Override public int hashCode() { return super.hashCode(); } } private static class ArrayRef implements TypeRef { final TypeRef component; ArrayRef(TypeRef component) { this.component = component; } public String getBinary() { return "[" + component.getBinary(); } public String getFQN() { return component.getFQN() + "[]"; } public String getPath() { return component.getPath(); } public String getSourcePath() { return component.getSourcePath(); } public boolean isPrimitive() { return false; } public TypeRef getComponentTypeRef() { return component; } public TypeRef getClassRef() { return component.getClassRef(); } @Override public boolean equals(Object other) { if (other == null || other.getClass() != getClass()) return false; return component.equals(((ArrayRef) other).component); } public PackageRef getPackageRef() { return component.getPackageRef(); } public String getShortName() { return component.getShortName() + "[]"; } public boolean isJava() { return component.isJava(); } @Override public String toString() { return component.toString() + "[]"; } public boolean isObject() { return false; } public String getDottedOnly() { return component.getDottedOnly(); } public int compareTo(TypeRef other) { if (this == other) return 0; return getFQN().compareTo(other.getFQN()); } @Override public int hashCode() { return super.hashCode(); } @Override public String getShorterName() { String name = getShortName(); int n = name.lastIndexOf('$'); if (n <= 0) return name; return name.substring(n + 1); } } public TypeRef getTypeRef(String binaryClassName) { assert !binaryClassName.endsWith(".class"); TypeRef ref = typeRefCache.get(binaryClassName); if (ref != null) return ref; if (binaryClassName.startsWith("[")) { ref = getTypeRef(binaryClassName.substring(1)); ref = new ArrayRef(ref); } else { if (binaryClassName.length() == 1) { switch (binaryClassName.charAt(0)) { case 'V' : return VOID; case 'B' : return BYTE; case 'C' : return CHAR; case 'I' : return INTEGER; case 'S' : return SHORT; case 'D' : return DOUBLE; case 'F' : return FLOAT; case 'J' : return LONG; case 'Z' : return BOOLEAN; } // falls trough for other 1 letter class names } if (binaryClassName.startsWith("L") && binaryClassName.endsWith(";")) { binaryClassName = binaryClassName.substring(1, binaryClassName.length() - 1); } ref = typeRefCache.get(binaryClassName); if (ref != null) return ref; PackageRef pref; int n = binaryClassName.lastIndexOf('/'); if (n < 0) pref = DEFAULT_PACKAGE; else pref = getPackageRef(binaryClassName.substring(0, n)); ref = new ConcreteRef(pref, binaryClassName); } typeRefCache.put(binaryClassName, ref); return ref; } public PackageRef getPackageRef(String binaryPackName) { if (binaryPackName.indexOf('.') >= 0) { binaryPackName = binaryPackName.replace('.', '/'); } PackageRef ref = packageCache.get(binaryPackName); if (ref != null) return ref; // // Check here if a package is actually a nested class // com.example.Foo.Bar should have package com.example, // not com.example.Foo. // ref = new PackageRef(binaryPackName); packageCache.put(binaryPackName, ref); return ref; } public Descriptor getDescriptor(String descriptor) { Descriptor d = descriptorCache.get(descriptor); if (d != null) return d; d = new Descriptor(descriptor); descriptorCache.put(descriptor, d); return d; } public class Descriptor { final TypeRef type; final TypeRef[] prototype; final String descriptor; Descriptor(String descriptor) { this.descriptor = descriptor; int index = 0; List<TypeRef> types = Create.list(); if (descriptor.charAt(index) == '(') { index++; while (descriptor.charAt(index) != ')') { index = parse(types, descriptor, index); } index++; // skip ) prototype = types.toArray(new TypeRef[0]); types.clear(); } else prototype = null; index = parse(types, descriptor, index); type = types.get(0); } int parse(List<TypeRef> types, String descriptor, int index) { char c; StringBuilder sb = new StringBuilder(); while ((c = descriptor.charAt(index++)) == '[') { sb.append('['); } switch (c) { case 'L' : while ((c = descriptor.charAt(index++)) != ';') { // TODO sb.append(c); } break; case 'V' : case 'B' : case 'C' : case 'I' : case 'S' : case 'D' : case 'F' : case 'J' : case 'Z' : sb.append(c); break; default : throw new IllegalArgumentException( "Invalid type in descriptor: " + c + " from " + descriptor + "[" + index + "]"); } types.add(getTypeRef(sb.toString())); return index; } public TypeRef getType() { return type; } public TypeRef[] getPrototype() { return prototype; } @Override public boolean equals(Object other) { if (other == null || other.getClass() != getClass()) return false; return Arrays.equals(prototype, ((Descriptor) other).prototype) && type == ((Descriptor) other).type; } @Override public int hashCode() { final int prime = 31; int result = prime + type.hashCode(); result = prime * result + ((prototype == null) ? 0 : Arrays.hashCode(prototype)); return result; } @Override public String toString() { return descriptor; } } /** * Return the short name of a FQN */ public static String getShortName(String fqn) { assert fqn.indexOf('/') < 0; int n = fqn.lastIndexOf('.'); if (n >= 0) { return fqn.substring(n + 1); } return fqn; } public static String binaryToFQN(String binary) { StringBuilder sb = new StringBuilder(); for (int i = 0, l = binary.length(); i < l; i++) { char c = binary.charAt(i); if (c == '/') sb.append('.'); else sb.append(c); } String result = sb.toString(); assert result.length() > 0; return result; } public static String fqnToBinary(String binary) { return binary.replace('.', '/'); } public static String getPackage(String binaryNameOrFqn) { int n = binaryNameOrFqn.lastIndexOf('/'); if (n >= 0) return binaryNameOrFqn.substring(0, n).replace('/', '.'); n = binaryNameOrFqn.lastIndexOf('.'); if (n >= 0) return binaryNameOrFqn.substring(0, n); return "."; } public static String fqnToPath(String s) { return fqnToBinary(s) + ".class"; } public TypeRef getTypeRefFromFQN(String fqn) { if (fqn.equals("boolean")) return BOOLEAN; if (fqn.equals("byte")) return BOOLEAN; if (fqn.equals("char")) return CHAR; if (fqn.equals("short")) return SHORT; if (fqn.equals("int")) return INTEGER; if (fqn.equals("long")) return LONG; if (fqn.equals("float")) return FLOAT; if (fqn.equals("double")) return DOUBLE; return getTypeRef(fqnToBinary(fqn)); } public TypeRef getTypeRefFromPath(String path) { assert path.endsWith(".class"); return getTypeRef(path.substring(0, path.length() - 6)); } // static class Rover { // int n = 0; // String string; // Rover(String string) { // this.string = string; // // } // // boolean at( String s) { // if ( n + s.length() > string.length()) // return false; // // for ( int i=0; i<s.length(); i++) { // if ( string.charAt(n+i) != s.charAt(n+i)) // return false; // } // // n += s.length(); // return true; // } // // String upTo(char c) { // for ( int i=n; i < string.length(); i++) { // if ( string.charAt(i) == c) { // String s = string.substring(n,i); // n = i; // return s; // } // } // throw new IllegalArgumentException("Looking for " + c + " in " + string + // " from " + n); // } // // } // public Signature getSignature(String signature) { // Signature s = new Signature(); // Rover r = new Rover(signature); // // // int n = parseTypeVarsDecl(s, rover); // n = parseParameters(s, descriptor, n); // n = parseTypeVarsDecl(s, descriptor, n); // // assert n == descriptor.length(); // return s; // } // // private int parseParameters(Signature s, String descriptor, int n) { // // TODO Auto-generated method stub // return 0; // } // // /** // * <X::Ljava/util/List<Ljava/lang/String;>;Y:Ljava/lang/Object;>(TY;)TX; // */ // private void parseTypeVarsDecl(Signature s, Rover rover) { // if ( rover.at("<")) { // while ( !rover.at(">")) { // String name = rover.upTo(':'); // rover.n++; // do { // Signature tr = parseTypeReference(s, rover); // s.typevariables.put(name, tr); // } while( rover.at(":")); // } // } // } // // private TypeRef parseTypeReference(String descriptor, int i) { // // TODO Auto-generated method stub // return null; // } }
apache-2.0
arst/SimplCommerce
src/Modules/SimplCommerce.Module.Vendors/ViewModels/VendorForm.cs
548
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace SimplCommerce.Module.Vendors.ViewModels { public class VendorForm { public long Id { get; set; } [Required] public string Name { get; set; } [EmailAddress] [Required] public string Email { get; set; } public string Description { get; set; } public bool IsActive { get; set; } public IList<VendorManager> Managers { get; set; } = new List<VendorManager>(); } }
apache-2.0
googleads/googleads-php-lib
src/Google/AdsApi/AdManager/v202108/MobileApplicationPlatform.php
403
<?php namespace Google\AdsApi\AdManager\v202108; /** * This file was generated from WSDL. DO NOT EDIT. */ class MobileApplicationPlatform { const UNKNOWN = 'UNKNOWN'; const ANDROID = 'ANDROID'; const IOS = 'IOS'; const ROKU = 'ROKU'; const AMAZON_FIRETV = 'AMAZON_FIRETV'; const PLAYSTATION = 'PLAYSTATION'; const XBOX = 'XBOX'; const SAMSUNG_TV = 'SAMSUNG_TV'; }
apache-2.0
pwittchen/ReactiveWiFi
library/src/main/java/com/github/pwittchen/reactivewifi/ReactiveWifi.java
13240
/* * Copyright (C) 2016 Piotr Wittchen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pwittchen.reactivewifi; import android.annotation.SuppressLint; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.wifi.ScanResult; import android.net.wifi.SupplicantState; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Looper; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.RequiresPermission; import io.reactivex.Observable; import io.reactivex.ObservableEmitter; import io.reactivex.ObservableOnSubscribe; import io.reactivex.Scheduler; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.disposables.Disposables; import io.reactivex.functions.Action; import io.reactivex.functions.Function; import java.util.List; import static android.Manifest.permission.ACCESS_COARSE_LOCATION; import static android.Manifest.permission.ACCESS_FINE_LOCATION; import static android.Manifest.permission.ACCESS_WIFI_STATE; import static android.Manifest.permission.CHANGE_WIFI_STATE; /** * ReactiveWiFi is an Android library * listening available WiFi Access Points change of the WiFi signal strength * with RxJava Observables. It can be easily used with RxAndroid. */ public class ReactiveWifi { private final static String LOG_TAG = "ReactiveWifi"; private ReactiveWifi() { } /** * Observes WiFi Access Points. * Returns fresh list of Access Points * whenever WiFi signal strength changes. * * @param context Context of the activity or an application * @return RxJava Observable with list of WiFi scan results */ @SuppressLint("MissingPermission") @RequiresPermission(allOf = { ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION, CHANGE_WIFI_STATE, ACCESS_WIFI_STATE }) public static Observable<List<ScanResult>> observeWifiAccessPoints(final Context context) { @SuppressLint("WifiManagerPotentialLeak") final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (wifiManager != null) { wifiManager.startScan(); // without starting scan, we may never receive any scan results } else { Log.w(LOG_TAG, "WifiManager was null, so WiFi scan was not started"); } final IntentFilter filter = new IntentFilter(); filter.addAction(WifiManager.RSSI_CHANGED_ACTION); filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); return Observable.create(new ObservableOnSubscribe<List<ScanResult>>() { @Override public void subscribe(final ObservableEmitter<List<ScanResult>> emitter) throws Exception { final BroadcastReceiver receiver = createWifiScanResultsReceiver(emitter, wifiManager); if (wifiManager != null) { context.registerReceiver(receiver, filter); } else { emitter.onError(new RuntimeException( "WifiManager was null, so BroadcastReceiver for Wifi scan results " + "cannot be registered")); } Disposable disposable = disposeInUiThread(new Action() { @Override public void run() { tryToUnregisterReceiver(context, receiver); } }); emitter.setDisposable(disposable); } }); } @NonNull protected static BroadcastReceiver createWifiScanResultsReceiver( final ObservableEmitter<List<ScanResult>> emitter, final WifiManager wifiManager) { return new BroadcastReceiver() { @Override public void onReceive(Context context1, Intent intent) { wifiManager.startScan(); // we need to start scan again to get fresh results ASAP emitter.onNext(wifiManager.getScanResults()); } }; } /** * Observes WiFi signal level with predefined max num levels. * Returns WiFi signal level as enum with information about current level * * @param context Context of the activity or an application * @return WifiSignalLevel as an enum */ @RequiresPermission(ACCESS_WIFI_STATE) public static Observable<WifiSignalLevel> observeWifiSignalLevel(final Context context) { return observeWifiSignalLevel(context, WifiSignalLevel.getMaxLevel()).map( new Function<Integer, WifiSignalLevel>() { @Override public WifiSignalLevel apply(Integer level) throws Exception { return WifiSignalLevel.fromLevel(level); } }); } /** * Observes WiFi signal level. * Returns WiFi signal level as an integer * * @param context Context of the activity or an application * @param numLevels The number of levels to consider in the calculated level as Integer * @return RxJava Observable with WiFi signal level */ @RequiresPermission(ACCESS_WIFI_STATE) public static Observable<Integer> observeWifiSignalLevel( final Context context, final int numLevels) { final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); final IntentFilter filter = new IntentFilter(); filter.addAction(WifiManager.RSSI_CHANGED_ACTION); return Observable.create(new ObservableOnSubscribe<Integer>() { @Override public void subscribe(final ObservableEmitter<Integer> emitter) throws Exception { final BroadcastReceiver receiver = createSignalLevelReceiver(emitter, wifiManager, numLevels); if (wifiManager != null) { context.registerReceiver(receiver, filter); } else { emitter.onError(new RuntimeException( "WifiManager is null, so BroadcastReceiver for Wifi signal level " + "cannot be registered")); } Disposable disposable = disposeInUiThread(new Action() { @Override public void run() { tryToUnregisterReceiver(context, receiver); } }); emitter.setDisposable(disposable); } }).defaultIfEmpty(0); } @NonNull protected static BroadcastReceiver createSignalLevelReceiver( final ObservableEmitter<Integer> emitter, final WifiManager wifiManager, final int numLevels) { return new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final int rssi = wifiManager.getConnectionInfo().getRssi(); final int level = WifiManager.calculateSignalLevel(rssi, numLevels); emitter.onNext(level); } }; } /** * Observes the current WPA supplicant state. * Returns the current WPA supplicant as a member of the {@link SupplicantState} enumeration, * returning {@link SupplicantState#UNINITIALIZED} if WiFi is not enabled. * * @param context Context of the activity or an application * @return RxJava Observable with SupplicantState */ @RequiresPermission(ACCESS_WIFI_STATE) public static Observable<SupplicantState> observeSupplicantState(final Context context) { final IntentFilter filter = new IntentFilter(); filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION); return Observable.create(new ObservableOnSubscribe<SupplicantState>() { @Override public void subscribe(final ObservableEmitter<SupplicantState> emitter) throws Exception { final BroadcastReceiver receiver = createSupplicantStateReceiver(emitter); context.registerReceiver(receiver, filter); Disposable disposable = disposeInUiThread(new Action() { @Override public void run() { tryToUnregisterReceiver(context, receiver); } }); emitter.setDisposable(disposable); } }).defaultIfEmpty(SupplicantState.UNINITIALIZED); } @NonNull protected static BroadcastReceiver createSupplicantStateReceiver( final ObservableEmitter<SupplicantState> emitter) { return new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { SupplicantState supplicantState = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE); if ((supplicantState != null) && SupplicantState.isValidState(supplicantState)) { emitter.onNext(supplicantState); } } }; } /** * Observes the WiFi network the device is connected to. * Returns the current WiFi network information as a {@link WifiInfo} object. * * @param context Context of the activity or an application * @return RxJava Observable with WifiInfo */ @RequiresPermission(ACCESS_WIFI_STATE) public static Observable<WifiInfo> observeWifiAccessPointChanges(final Context context) { final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); final IntentFilter filter = new IntentFilter(); filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION); return Observable.create(new ObservableOnSubscribe<WifiInfo>() { @Override public void subscribe(final ObservableEmitter<WifiInfo> emitter) throws Exception { final BroadcastReceiver receiver = createAccessPointChangesReceiver(emitter, wifiManager); context.registerReceiver(receiver, filter); Disposable disposable = disposeInUiThread(new Action() { @Override public void run() { tryToUnregisterReceiver(context, receiver); } }); emitter.setDisposable(disposable); } }); } @NonNull protected static BroadcastReceiver createAccessPointChangesReceiver( final ObservableEmitter<WifiInfo> emitter, final WifiManager wifiManager) { return new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { SupplicantState supplicantState = intent.getParcelableExtra(WifiManager.EXTRA_NEW_STATE); if (supplicantState == SupplicantState.COMPLETED) { emitter.onNext(wifiManager.getConnectionInfo()); } } }; } /** * Observes WiFi State Change Action * Returns wifi state * whenever WiFi state changes such like enable,disable,enabling,disabling or Unknown * * @param context Context of the activity or an application * @return RxJava Observable with different state change */ @RequiresPermission(ACCESS_WIFI_STATE) public static Observable<WifiState> observeWifiStateChange( final Context context) { final IntentFilter filter = new IntentFilter(); filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); return Observable.create(new ObservableOnSubscribe<WifiState>() { @Override public void subscribe(final ObservableEmitter<WifiState> emitter) throws Exception { final BroadcastReceiver receiver = createWifiStateChangeReceiver(emitter); context.registerReceiver(receiver, filter); Disposable disposable = disposeInUiThread(new Action() { @Override public void run() { tryToUnregisterReceiver(context, receiver); } }); emitter.setDisposable(disposable); } }); } @NonNull protected static BroadcastReceiver createWifiStateChangeReceiver( final ObservableEmitter<WifiState> emitter) { return new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { //we receive whenever the wifi state is change int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN); emitter.onNext(WifiState.fromState(wifiState)); } }; } protected static void tryToUnregisterReceiver(final Context context, final BroadcastReceiver receiver) { try { context.unregisterReceiver(receiver); } catch (Exception exception) { onError("receiver was already unregistered", exception); } } protected static void onError(final String message, final Exception exception) { Log.e(LOG_TAG, message, exception); } private static Disposable disposeInUiThread(final Action action) { return Disposables.fromAction(new Action() { @Override public void run() throws Exception { if (Looper.getMainLooper() == Looper.myLooper()) { action.run(); } else { final Scheduler.Worker inner = AndroidSchedulers.mainThread().createWorker(); inner.schedule(new Runnable() { @Override public void run() { try { action.run(); } catch (Exception e) { onError("Could not unregister receiver in UI Thread", e); } inner.dispose(); } }); } } }); } }
apache-2.0
gerrit-review/gerrit
java/com/google/gerrit/server/events/EventTypes.java
2405
// Copyright (C) 2014 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.server.events; import java.util.HashMap; import java.util.Map; /** Class for registering event types */ public class EventTypes { private static final Map<String, Class<?>> typesByString = new HashMap<>(); static { register(AssigneeChangedEvent.TYPE, AssigneeChangedEvent.class); register(ChangeAbandonedEvent.TYPE, ChangeAbandonedEvent.class); register(ChangeMergedEvent.TYPE, ChangeMergedEvent.class); register(ChangeRestoredEvent.TYPE, ChangeRestoredEvent.class); register(CommentAddedEvent.TYPE, CommentAddedEvent.class); register(CommitReceivedEvent.TYPE, CommitReceivedEvent.class); register(HashtagsChangedEvent.TYPE, HashtagsChangedEvent.class); register(PatchSetCreatedEvent.TYPE, PatchSetCreatedEvent.class); register(ProjectCreatedEvent.TYPE, ProjectCreatedEvent.class); register(RefReceivedEvent.TYPE, RefReceivedEvent.class); register(RefUpdatedEvent.TYPE, RefUpdatedEvent.class); register(ReviewerAddedEvent.TYPE, ReviewerAddedEvent.class); register(ReviewerDeletedEvent.TYPE, ReviewerDeletedEvent.class); register(TopicChangedEvent.TYPE, TopicChangedEvent.class); register(VoteDeletedEvent.TYPE, VoteDeletedEvent.class); } /** * Register an event type and associated class. * * @param eventType The event type to register. * @param eventClass The event class to register. */ public static void register(String eventType, Class<? extends Event> eventClass) { typesByString.put(eventType, eventClass); } /** * Get the class for an event type. * * @param type The type. * @return The event class, or null if no class is registered with the given type */ public static Class<?> getClass(String type) { return typesByString.get(type); } }
apache-2.0
greensnow25/javaaz
chapter3/Control_Task/src/main/java/com/greensnow25/searchWithEnum/Librery/FindByRegExp.java
657
package com.greensnow25.searchWithEnum.Librery; import java.io.File; import java.io.PrintWriter; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * public class FindByRegExp. * * @author greensnow25. * @since 17.03.2017. * @version 1. */ public class FindByRegExp implements Find { @Override public void search(PrintWriter fileWriter, File file, String regExp) { Pattern pattern = Pattern.compile(regExp); Matcher matcher = pattern.matcher(file.getName()); boolean write; write = matcher.find(); if (write) { fileWriter.println(file.getAbsolutePath()); } } }
apache-2.0
dtynn/grpcproxy
example/gproxy/foo/service.go
884
package foo import ( "fmt" "log" "net" "strings" "golang.org/x/net/context" "google.golang.org/grpc" "github.com/dtynn/grpcproxy/example/rpc" ) var _ rpc.FooServer = &Service{} type Service struct { Port int } func (this *Service) Chat(ctx context.Context, req *rpc.FooReq) (*rpc.FooResp, error) { log.Printf("chat requested: %s", req.Hello) if strings.Contains(req.Hello, "error") { return nil, fmt.Errorf("[FOO ON %d]foo.Chat: got chat error %s", this.Port, req.Hello) } return &rpc.FooResp{ World: fmt.Sprintf("[FOO ON %d]foo.Chat: Hello %s World", this.Port, req.Hello), }, nil } func (this *Service) Run() error { addr := fmt.Sprintf(":%d", this.Port) lis, err := net.Listen("tcp", addr) if err != nil { return err } server := grpc.NewServer() rpc.RegisterFooServer(server, this) log.Printf("listen on %s", addr) return server.Serve(lis) }
apache-2.0
bitpew/ratpack-webapp-template
src/main/java/template/web/ratpack/handler/api/HelloWorldApiHandler.java
286
package template.web.ratpack.handler.api; import ratpack.handling.Context; import ratpack.handling.Handler; public class HelloWorldApiHandler implements Handler { @Override public void handle(Context context) throws Exception { context.render("Hello World"); } }
apache-2.0
taktos/ea2ddl
ea2ddl-dao/src/main/java/jp/sourceforge/ea2ddl/dao/cbean/cq/bs/BsTTasksCQ.java
10933
package jp.sourceforge.ea2ddl.dao.cbean.cq.bs; import java.util.Map; import org.seasar.dbflute.cbean.*; import org.seasar.dbflute.cbean.cvalue.ConditionValue; import org.seasar.dbflute.cbean.sqlclause.SqlClause; import jp.sourceforge.ea2ddl.dao.cbean.cq.ciq.*; import jp.sourceforge.ea2ddl.dao.cbean.*; import jp.sourceforge.ea2ddl.dao.cbean.cq.*; /** * The base condition-query of t_tasks. * @author DBFlute(AutoGenerator) */ public class BsTTasksCQ extends AbstractBsTTasksCQ { // =================================================================================== // Attribute // ========= protected TTasksCIQ _inlineQuery; // =================================================================================== // Constructor // =========== public BsTTasksCQ(ConditionQuery childQuery, SqlClause sqlClause, String aliasName, int nestLevel) { super(childQuery, sqlClause, aliasName, nestLevel); } // =================================================================================== // Inline // ====== /** * Prepare inline query. <br /> * {select ... from ... left outer join (select * from t_tasks) where abc = [abc] ...} * @return Inline query. (NotNull) */ public TTasksCIQ inline() { if (_inlineQuery == null) { _inlineQuery = new TTasksCIQ(getChildQuery(), getSqlClause(), getAliasName(), getNestLevel(), this); } _inlineQuery.xsetOnClauseInline(false); return _inlineQuery; } /** * Prepare on-clause query. <br /> * {select ... from ... left outer join t_tasks on ... and abc = [abc] ...} * @return On-clause query. (NotNull) */ public TTasksCIQ on() { if (isBaseQuery(this)) { throw new UnsupportedOperationException("Unsupported on-clause for local table!"); } TTasksCIQ inlineQuery = inline(); inlineQuery.xsetOnClauseInline(true); return inlineQuery; } // =================================================================================== // Query // ===== protected ConditionValue _taskid; public ConditionValue getTaskid() { if (_taskid == null) { _taskid = new ConditionValue(); } return _taskid; } protected ConditionValue getCValueTaskid() { return getTaskid(); } public BsTTasksCQ addOrderBy_Taskid_Asc() { regOBA("TaskID"); return this; } public BsTTasksCQ addOrderBy_Taskid_Desc() { regOBD("TaskID"); return this; } protected ConditionValue _name; public ConditionValue getName() { if (_name == null) { _name = new ConditionValue(); } return _name; } protected ConditionValue getCValueName() { return getName(); } public BsTTasksCQ addOrderBy_Name_Asc() { regOBA("Name"); return this; } public BsTTasksCQ addOrderBy_Name_Desc() { regOBD("Name"); return this; } protected ConditionValue _tasktype; public ConditionValue getTasktype() { if (_tasktype == null) { _tasktype = new ConditionValue(); } return _tasktype; } protected ConditionValue getCValueTasktype() { return getTasktype(); } public BsTTasksCQ addOrderBy_Tasktype_Asc() { regOBA("TaskType"); return this; } public BsTTasksCQ addOrderBy_Tasktype_Desc() { regOBD("TaskType"); return this; } protected ConditionValue _notes; public ConditionValue getNotes() { if (_notes == null) { _notes = new ConditionValue(); } return _notes; } protected ConditionValue getCValueNotes() { return getNotes(); } public BsTTasksCQ addOrderBy_Notes_Asc() { regOBA("NOTES"); return this; } public BsTTasksCQ addOrderBy_Notes_Desc() { regOBD("NOTES"); return this; } protected ConditionValue _priority; public ConditionValue getPriority() { if (_priority == null) { _priority = new ConditionValue(); } return _priority; } protected ConditionValue getCValuePriority() { return getPriority(); } public BsTTasksCQ addOrderBy_Priority_Asc() { regOBA("Priority"); return this; } public BsTTasksCQ addOrderBy_Priority_Desc() { regOBD("Priority"); return this; } protected ConditionValue _status; public ConditionValue getStatus() { if (_status == null) { _status = new ConditionValue(); } return _status; } protected ConditionValue getCValueStatus() { return getStatus(); } public BsTTasksCQ addOrderBy_Status_Asc() { regOBA("Status"); return this; } public BsTTasksCQ addOrderBy_Status_Desc() { regOBD("Status"); return this; } protected ConditionValue _owner; public ConditionValue getOwner() { if (_owner == null) { _owner = new ConditionValue(); } return _owner; } protected ConditionValue getCValueOwner() { return getOwner(); } public BsTTasksCQ addOrderBy_Owner_Asc() { regOBA("Owner"); return this; } public BsTTasksCQ addOrderBy_Owner_Desc() { regOBD("Owner"); return this; } protected ConditionValue _startdate; public ConditionValue getStartdate() { if (_startdate == null) { _startdate = new ConditionValue(); } return _startdate; } protected ConditionValue getCValueStartdate() { return getStartdate(); } public BsTTasksCQ addOrderBy_Startdate_Asc() { regOBA("StartDate"); return this; } public BsTTasksCQ addOrderBy_Startdate_Desc() { regOBD("StartDate"); return this; } protected ConditionValue _enddate; public ConditionValue getEnddate() { if (_enddate == null) { _enddate = new ConditionValue(); } return _enddate; } protected ConditionValue getCValueEnddate() { return getEnddate(); } public BsTTasksCQ addOrderBy_Enddate_Asc() { regOBA("EndDate"); return this; } public BsTTasksCQ addOrderBy_Enddate_Desc() { regOBD("EndDate"); return this; } protected ConditionValue _phase; public ConditionValue getPhase() { if (_phase == null) { _phase = new ConditionValue(); } return _phase; } protected ConditionValue getCValuePhase() { return getPhase(); } public BsTTasksCQ addOrderBy_Phase_Asc() { regOBA("Phase"); return this; } public BsTTasksCQ addOrderBy_Phase_Desc() { regOBD("Phase"); return this; } protected ConditionValue _history; public ConditionValue getHistory() { if (_history == null) { _history = new ConditionValue(); } return _history; } protected ConditionValue getCValueHistory() { return getHistory(); } public BsTTasksCQ addOrderBy_History_Asc() { regOBA("History"); return this; } public BsTTasksCQ addOrderBy_History_Desc() { regOBD("History"); return this; } protected ConditionValue _percent; public ConditionValue getPercent() { if (_percent == null) { _percent = new ConditionValue(); } return _percent; } protected ConditionValue getCValuePercent() { return getPercent(); } public BsTTasksCQ addOrderBy_Percent_Asc() { regOBA("Percent"); return this; } public BsTTasksCQ addOrderBy_Percent_Desc() { regOBD("Percent"); return this; } protected ConditionValue _totaltime; public ConditionValue getTotaltime() { if (_totaltime == null) { _totaltime = new ConditionValue(); } return _totaltime; } protected ConditionValue getCValueTotaltime() { return getTotaltime(); } public BsTTasksCQ addOrderBy_Totaltime_Asc() { regOBA("TotalTime"); return this; } public BsTTasksCQ addOrderBy_Totaltime_Desc() { regOBD("TotalTime"); return this; } protected ConditionValue _actualtime; public ConditionValue getActualtime() { if (_actualtime == null) { _actualtime = new ConditionValue(); } return _actualtime; } protected ConditionValue getCValueActualtime() { return getActualtime(); } public BsTTasksCQ addOrderBy_Actualtime_Asc() { regOBA("ActualTime"); return this; } public BsTTasksCQ addOrderBy_Actualtime_Desc() { regOBD("ActualTime"); return this; } protected ConditionValue _assignedto; public ConditionValue getAssignedto() { if (_assignedto == null) { _assignedto = new ConditionValue(); } return _assignedto; } protected ConditionValue getCValueAssignedto() { return getAssignedto(); } public BsTTasksCQ addOrderBy_Assignedto_Asc() { regOBA("AssignedTo"); return this; } public BsTTasksCQ addOrderBy_Assignedto_Desc() { regOBD("AssignedTo"); return this; } // =================================================================================== // Specified Derived OrderBy // ========================= public BsTTasksCQ addSpecifiedDerivedOrderBy_Asc(String aliasName) { registerSpecifiedDerivedOrderBy_Asc(aliasName); return this; } public BsTTasksCQ addSpecifiedDerivedOrderBy_Desc(String aliasName) { registerSpecifiedDerivedOrderBy_Desc(aliasName); return this; } // =================================================================================== // Union Query // =========== protected void reflectRelationOnUnionQuery(ConditionQuery baseQueryAsSuper, ConditionQuery unionQueryAsSuper) { } // =================================================================================== // Foreign Query // ============= // =================================================================================== // Very Internal // ============= // Very Internal (for Suppressing Warn about 'Not Use Import') String xCB() { return TTasksCB.class.getName(); } String xCQ() { return TTasksCQ.class.getName(); } String xMap() { return Map.class.getName(); } }
apache-2.0
knative/test-infra
pkg/clustermanager/perf-tests/pkg/cluster_test.go
14149
/* Copyright 2019 The Knative Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package pkg import ( "fmt" "strings" "testing" "github.com/google/go-cmp/cmp" container "google.golang.org/api/container/v1beta1" "knative.dev/test-infra/pkg/gke" gkeFake "knative.dev/test-infra/pkg/gke/fake" ) const ( fakeProject = "p" fakeRepository = "r" testBenchmarkRoot = "testdir" ) func setupFakeGKEClient() Client { return Client{ ops: gkeFake.NewGKESDKClient(), } } func TestRecreateClusters(t *testing.T) { allExpectedClusters := map[string]ClusterConfig{ clusterNameForBenchmark("test-benchmark1", fakeRepository): clusterConfigForBenchmark("test-benchmark1", testBenchmarkRoot), clusterNameForBenchmark("test-benchmark2", fakeRepository): clusterConfigForBenchmark("test-benchmark2", testBenchmarkRoot), clusterNameForBenchmark("test-benchmark3", fakeRepository): clusterConfigForBenchmark("test-benchmark3", testBenchmarkRoot), clusterNameForBenchmark("test-benchmark4", fakeRepository): clusterConfigForBenchmark("test-benchmark4", testBenchmarkRoot), } testCases := []struct { testName string benchmarkRoot string precreatedClusters map[string]ClusterConfig expectedClusters map[string]ClusterConfig }{ // all clusters will be created if there is no cluster at the beginning { testName: "all clusters will be created if there is no cluster at the beginning", benchmarkRoot: testBenchmarkRoot, precreatedClusters: make(map[string]ClusterConfig), expectedClusters: allExpectedClusters, }, // clusters that do not belong to this repo will not be touched { testName: "clusters that do not belong to this repo will not be touched", benchmarkRoot: testBenchmarkRoot, precreatedClusters: map[string]ClusterConfig{ "unrelated-cluster": { Location: "us-central1", NodeCount: 3, NodeType: "n1-standard-4", }, }, expectedClusters: combineClusterMaps(map[string]ClusterConfig{ "unrelated-cluster": { Location: "us-central1", NodeCount: 3, NodeType: "n1-standard-4", }, }, allExpectedClusters), }, // clusters that belong to this repo, but have no corresponding benchmark, will be deleted { testName: "clusters that belong to this repo, but have no corresponding benchmark, will be deleted", benchmarkRoot: testBenchmarkRoot, precreatedClusters: map[string]ClusterConfig{ clusterNameForBenchmark("random-cluster", fakeRepository): { Location: "us-central1", NodeCount: 3, NodeType: "n1-standard-4", }, }, expectedClusters: allExpectedClusters, }, // clusters that belong to this repo, and have corresponding benchmark, will be recreated with the new config { testName: "clusters that belong to this repo, and have corresponding benchmark, will be recreated with the new config", benchmarkRoot: testBenchmarkRoot, precreatedClusters: map[string]ClusterConfig{ clusterNameForBenchmark("test-benchmark1", fakeRepository): { Location: "us-central1", NodeCount: 2, NodeType: "n1-standard-4", }, }, expectedClusters: allExpectedClusters, }, // multiple different clusters can be all handled in one single function call { testName: "multiple different clusters can be all handled in one single function call", benchmarkRoot: testBenchmarkRoot, precreatedClusters: map[string]ClusterConfig{ clusterNameForBenchmark("test-benchmark1", fakeRepository): { Location: "us-central1", NodeCount: 2, NodeType: "n1-standard-4", }, clusterNameForBenchmark("test-benchmark2", fakeRepository): { Location: "us-west1", NodeCount: 2, NodeType: "n1-standard-8", }, }, expectedClusters: allExpectedClusters, }, } for _, tc := range testCases { client := setupFakeGKEClient() for name, config := range tc.precreatedClusters { region, zone := gke.RegionZoneFromLoc(config.Location) var addons []string if strings.TrimSpace(config.Addons) != "" { addons = strings.Split(config.Addons, ",") } req := &gke.Request{ ClusterName: name, MinNodes: config.NodeCount, MaxNodes: config.NodeCount, NodeType: config.NodeType, Addons: addons, } creq, _ := gke.NewCreateClusterRequest(req) client.ops.CreateCluster(fakeProject, region, zone, creq) } err := client.RecreateClusters(fakeProject, fakeRepository, testBenchmarkRoot) fmt.Println(err) clusters, _ := client.ops.ListClustersInProject(fakeProject) actual := make(map[string]ClusterConfig) for _, cluster := range clusters { actual[cluster.Name] = ClusterConfig{ Location: cluster.Location, NodeCount: cluster.NodePools[0].Autoscaling.MaxNodeCount, NodeType: cluster.NodePools[0].Config.MachineType, Addons: getAddonsForCluster(cluster), } } if diff := cmp.Diff(tc.expectedClusters, actual); diff != "" { t.Fatalf("Test %q fails, RecreateClusters(%q, %q, %q) returns wrong result (-want +got):\n%s", tc.testName, fakeProject, fakeRepository, tc.benchmarkRoot, diff) } } } func TestReconcileClusters(t *testing.T) { reconciledClusters := map[string]ClusterConfig{ clusterNameForBenchmark("test-benchmark1", fakeRepository): clusterConfigForBenchmark("test-benchmark1", testBenchmarkRoot), clusterNameForBenchmark("test-benchmark2", fakeRepository): clusterConfigForBenchmark("test-benchmark2", testBenchmarkRoot), clusterNameForBenchmark("test-benchmark3", fakeRepository): clusterConfigForBenchmark("test-benchmark3", testBenchmarkRoot), clusterNameForBenchmark("test-benchmark4", fakeRepository): clusterConfigForBenchmark("test-benchmark4", testBenchmarkRoot), } testCases := []struct { testName string benchmarkRoot string precreatedClusters map[string]ClusterConfig expectedClusters map[string]ClusterConfig }{ // all clusters will be created if there is no cluster at the beginning { testName: "all clusters will be created if there is no cluster at the beginning", benchmarkRoot: testBenchmarkRoot, precreatedClusters: make(map[string]ClusterConfig), expectedClusters: reconciledClusters, }, // clusters that do not belong to this repo will not be touched { testName: "clusters that do not belong to this repo will not be touched", benchmarkRoot: testBenchmarkRoot, precreatedClusters: map[string]ClusterConfig{ "unrelated-cluster": { Location: "us-central1", NodeCount: 3, NodeType: "n1-standard-4", }, }, expectedClusters: combineClusterMaps(map[string]ClusterConfig{ "unrelated-cluster": { Location: "us-central1", NodeCount: 3, NodeType: "n1-standard-4", }, }, reconciledClusters), }, // clusters that belong to this repo, but have no corresponding benchmark, will be deleted { testName: "clusters that belong to this repo, but have no corresponding benchmark, will be deleted", benchmarkRoot: testBenchmarkRoot, precreatedClusters: map[string]ClusterConfig{ clusterNameForBenchmark("random-cluster", fakeRepository): { Location: "us-central1", NodeCount: 3, NodeType: "n1-standard-4", }, }, expectedClusters: reconciledClusters, }, // clusters that belong to this repo, and have corresponding benchmark, will be recreated with the new config { testName: "clusters that belong to this repo, and have corresponding benchmark, will be recreated with the new config", benchmarkRoot: testBenchmarkRoot, precreatedClusters: map[string]ClusterConfig{ clusterNameForBenchmark("test-benchmark1", fakeRepository): { Location: "us-central1", NodeCount: 2, NodeType: "n1-standard-4", }, }, expectedClusters: reconciledClusters, }, // multiple different clusters can be all handled in one single function call { testName: "multiple different clusters can be all handled in one single function call", benchmarkRoot: testBenchmarkRoot, precreatedClusters: map[string]ClusterConfig{ clusterNameForBenchmark("test-benchmark1", fakeRepository): { Location: "us-central1", NodeCount: 2, NodeType: "n1-standard-4", }, clusterNameForBenchmark("test-benchmark2", fakeRepository): { Location: "us-west1", NodeCount: 2, NodeType: "n1-standard-8", }, clusterNameForBenchmark("random-cluster", fakeRepository): { Location: "us-west1", NodeCount: 2, NodeType: "n1-standard-8", }, }, expectedClusters: reconciledClusters, }, } for _, tc := range testCases { client := setupFakeGKEClient() for name, config := range tc.precreatedClusters { region, zone := gke.RegionZoneFromLoc(config.Location) var addons []string if strings.TrimSpace(config.Addons) != "" { addons = strings.Split(config.Addons, ",") } req := &gke.Request{ ClusterName: name, MinNodes: config.NodeCount, MaxNodes: config.NodeCount, NodeType: config.NodeType, Addons: addons, } creq, _ := gke.NewCreateClusterRequest(req) client.ops.CreateCluster(fakeProject, region, zone, creq) } err := client.ReconcileClusters(fakeProject, fakeRepository, testBenchmarkRoot) fmt.Println(err) clusters, _ := client.ops.ListClustersInProject(fakeProject) actual := make(map[string]ClusterConfig) for _, cluster := range clusters { actual[cluster.Name] = ClusterConfig{ Location: cluster.Location, NodeCount: cluster.NodePools[0].Autoscaling.MaxNodeCount, NodeType: cluster.NodePools[0].Config.MachineType, Addons: getAddonsForCluster(cluster), } } if diff := cmp.Diff(tc.expectedClusters, actual); diff != "" { t.Fatalf("Test %q fails, ReconcileClusters(%q, %q, %q) returns wrong result (-want +got):\n%s", tc.testName, fakeProject, fakeRepository, tc.benchmarkRoot, diff) } } } func TestDeleteClusters(t *testing.T) { testCases := []struct { testName string benchmarkRoot string precreatedClusters map[string]ClusterConfig expectedClusters map[string]ClusterConfig }{ // nothing will be done if there is no cluster at the beginning { testName: "all related clusters will be deleted", benchmarkRoot: testBenchmarkRoot, precreatedClusters: make(map[string]ClusterConfig), expectedClusters: make(map[string]ClusterConfig), }, // all clusters will be created if there is no cluster at the beginning { testName: "all related clusters will be deleted", benchmarkRoot: testBenchmarkRoot, precreatedClusters: map[string]ClusterConfig{ clusterNameForBenchmark("test-benchmark1", fakeRepository): { Location: "us-central1", NodeCount: 2, NodeType: "n1-standard-4", }, clusterNameForBenchmark("test-benchmark2", fakeRepository): { Location: "us-west1", NodeCount: 2, NodeType: "n1-standard-8", }, }, expectedClusters: make(map[string]ClusterConfig), }, // clusters that do not belong to this repo will not be touched { testName: "clusters that do not belong to this repo will not be touched", benchmarkRoot: testBenchmarkRoot, precreatedClusters: map[string]ClusterConfig{ clusterNameForBenchmark("test-benchmark1", fakeRepository): { Location: "us-central1", NodeCount: 2, NodeType: "n1-standard-4", }, "unrelated-cluster": { Location: "us-central1", NodeCount: 3, NodeType: "n1-standard-4", }, }, expectedClusters: map[string]ClusterConfig{ "unrelated-cluster": { Location: "us-central1", NodeCount: 3, NodeType: "n1-standard-4", }, }, }, } for _, tc := range testCases { client := setupFakeGKEClient() for name, config := range tc.precreatedClusters { region, zone := gke.RegionZoneFromLoc(config.Location) var addons []string if strings.TrimSpace(config.Addons) != "" { addons = strings.Split(config.Addons, ",") } req := &gke.Request{ ClusterName: name, MinNodes: config.NodeCount, MaxNodes: config.NodeCount, NodeType: config.NodeType, Addons: addons, } creq, _ := gke.NewCreateClusterRequest(req) client.ops.CreateCluster(fakeProject, region, zone, creq) } err := client.DeleteClusters(fakeProject, fakeRepository, testBenchmarkRoot) fmt.Println(err) clusters, _ := client.ops.ListClustersInProject(fakeProject) actual := make(map[string]ClusterConfig) for _, cluster := range clusters { actual[cluster.Name] = ClusterConfig{ Location: cluster.Location, NodeCount: cluster.NodePools[0].Autoscaling.MaxNodeCount, NodeType: cluster.NodePools[0].Config.MachineType, Addons: getAddonsForCluster(cluster), } } if diff := cmp.Diff(tc.expectedClusters, actual); diff != "" { t.Fatalf("Test %q fails, DeleteClusters(%q, %q, %q) returns wrong result (-want +got):\n%s", tc.testName, fakeProject, fakeRepository, tc.benchmarkRoot, diff) } } } // Return addons as a string slice for the given cluster. // In this test we only use istio so only checking istio is enough here. func getAddonsForCluster(cluster *container.Cluster) string { addons := make([]string, 0) if cluster.AddonsConfig.IstioConfig != nil && !cluster.AddonsConfig.IstioConfig.Disabled { addons = append(addons, "istio") } return strings.Join(addons, ",") } func combineClusterMaps(m1 map[string]ClusterConfig, m2 map[string]ClusterConfig) map[string]ClusterConfig { for name, config := range m2 { m1[name] = config } return m1 }
apache-2.0
johngmyers/airlift
concurrent/src/main/java/io/airlift/concurrent/MoreFutures.java
24426
package io.airlift.concurrent; import com.google.common.util.concurrent.AsyncFunction; import com.google.common.util.concurrent.FluentFuture; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import io.airlift.units.Duration; import javax.annotation.Nullable; import java.lang.ref.WeakReference; import java.util.List; import java.util.Optional; import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Throwables.propagateIfPossible; import static com.google.common.base.Throwables.throwIfInstanceOf; import static com.google.common.collect.Iterables.isEmpty; import static com.google.common.util.concurrent.Futures.immediateFailedFuture; import static com.google.common.util.concurrent.Futures.immediateFuture; import static com.google.common.util.concurrent.MoreExecutors.directExecutor; import static java.util.Objects.requireNonNull; import static java.util.concurrent.TimeUnit.MILLISECONDS; public final class MoreFutures { private MoreFutures() {} /** * Cancels the destination Future if the source Future is cancelled. */ public static <X, Y> void propagateCancellation(ListenableFuture<? extends X> source, Future<? extends Y> destination, boolean mayInterruptIfRunning) { source.addListener(() -> { if (source.isCancelled()) { destination.cancel(mayInterruptIfRunning); } }, directExecutor()); } /** * Mirrors all results of the source Future to the destination Future. * <p> * This also propagates cancellations from the destination Future back to the source Future. */ public static <T> void mirror(ListenableFuture<? extends T> source, SettableFuture<? super T> destination, boolean mayInterruptIfRunning) { FutureCallback<T> callback = new FutureCallback<T>() { @Override public void onSuccess(@Nullable T result) { destination.set(result); } @Override public void onFailure(Throwable t) { destination.setException(t); } }; Futures.addCallback(source, callback, directExecutor()); propagateCancellation(destination, source, mayInterruptIfRunning); } /** * Attempts to unwrap a throwable that has been wrapped in a {@link CompletionException}. */ public static Throwable unwrapCompletionException(Throwable throwable) { if (throwable instanceof CompletionException) { return firstNonNull(throwable.getCause(), throwable); } return throwable; } /** * Returns a future that can not be completed or canceled. */ @Deprecated public static <V> CompletableFuture<V> unmodifiableFuture(CompletableFuture<V> future) { return unmodifiableFuture(future, false); } /** * Returns a future that can not be completed or optionally canceled. */ @Deprecated public static <V> CompletableFuture<V> unmodifiableFuture(CompletableFuture<V> future, boolean propagateCancel) { requireNonNull(future, "future is null"); Function<Boolean, Boolean> onCancelFunction; if (propagateCancel) { onCancelFunction = future::cancel; } else { onCancelFunction = mayInterrupt -> false; } UnmodifiableCompletableFuture<V> unmodifiableFuture = new UnmodifiableCompletableFuture<>(onCancelFunction); future.whenComplete((value, exception) -> { if (exception != null) { unmodifiableFuture.internalCompleteExceptionally(exception); } else { unmodifiableFuture.internalComplete(value); } }); return unmodifiableFuture; } /** * Returns a failed future containing the specified throwable. */ @Deprecated public static <V> CompletableFuture<V> failedFuture(Throwable throwable) { requireNonNull(throwable, "throwable is null"); CompletableFuture<V> future = new CompletableFuture<>(); future.completeExceptionally(throwable); return future; } /** * Waits for the value from the future. If the future is failed, the exception * is thrown directly if unchecked or wrapped in a RuntimeException. If the * thread is interrupted, the thread interruption flag is set and the original * InterruptedException is wrapped in a RuntimeException and thrown. */ public static <V> V getFutureValue(Future<V> future) { return getFutureValue(future, RuntimeException.class); } /** * Waits for the value from the future. If the future is failed, the exception * is thrown directly if it is an instance of the specified exception type or * unchecked, or it is wrapped in a RuntimeException. If the thread is * interrupted, the thread interruption flag is set and the original * InterruptedException is wrapped in a RuntimeException and thrown. */ public static <V, E extends Exception> V getFutureValue(Future<V> future, Class<E> exceptionType) throws E { requireNonNull(future, "future is null"); requireNonNull(exceptionType, "exceptionType is null"); try { return future.get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException("interrupted", e); } catch (ExecutionException e) { Throwable cause = e.getCause() == null ? e : e.getCause(); propagateIfPossible(cause, exceptionType); throw new RuntimeException(cause); } } /** * Gets the current value of the future without waiting. If the future * value is null, an empty Optional is still returned, and in this case the caller * must check the future directly for the null value. */ public static <T> Optional<T> tryGetFutureValue(Future<T> future) { requireNonNull(future, "future is null"); if (!future.isDone()) { return Optional.empty(); } return tryGetFutureValue(future, 0, MILLISECONDS); } /** * Waits for the the value from the future for the specified time. If the future * value is null, an empty Optional is still returned, and in this case the caller * must check the future directly for the null value. If the future is failed, * the exception is thrown directly if unchecked or wrapped in a RuntimeException. * If the thread is interrupted, the thread interruption flag is set and the original * InterruptedException is wrapped in a RuntimeException and thrown. */ public static <V> Optional<V> tryGetFutureValue(Future<V> future, int timeout, TimeUnit timeUnit) { return tryGetFutureValue(future, timeout, timeUnit, RuntimeException.class); } /** * Waits for the the value from the future for the specified time. If the future * value is null, an empty Optional is still returned, and in this case the caller * must check the future directly for the null value. If the future is failed, * the exception is thrown directly if it is an instance of the specified exception * type or unchecked, or it is wrapped in a RuntimeException. If the thread is * interrupted, the thread interruption flag is set and the original * InterruptedException is wrapped in a RuntimeException and thrown. */ public static <V, E extends Exception> Optional<V> tryGetFutureValue(Future<V> future, int timeout, TimeUnit timeUnit, Class<E> exceptionType) throws E { requireNonNull(future, "future is null"); checkArgument(timeout >= 0, "timeout is negative"); requireNonNull(timeUnit, "timeUnit is null"); requireNonNull(exceptionType, "exceptionType is null"); try { return Optional.ofNullable(future.get(timeout, timeUnit)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException("interrupted", e); } catch (ExecutionException e) { Throwable cause = e.getCause() == null ? e : e.getCause(); propagateIfPossible(cause, exceptionType); throw new RuntimeException(cause); } catch (TimeoutException expected) { // expected } return Optional.empty(); } /** * Returns the result of the input {@link Future}, which must have already completed. * <p> * Similar to Futures{@link Futures#getDone(Future)}, but does not throw checked exceptions. */ public static <T> T getDone(Future<T> future) { requireNonNull(future, "future is null"); checkArgument(future.isDone(), "future not done yet"); return getFutureValue(future); } /** * Checks that the completed future completed successfully. */ public static void checkSuccess(Future<?> future, String errorMessage) { requireNonNull(future, "future is null"); requireNonNull(errorMessage, "errorMessage is null"); checkArgument(future.isDone(), "future not done yet"); try { getFutureValue(future); } catch (RuntimeException e) { throw new IllegalArgumentException(errorMessage, e); } } /** * Creates a future that completes when the first future completes either normally * or exceptionally. Cancellation of the future propagates to the supplied futures. */ public static <V> ListenableFuture<V> whenAnyComplete(Iterable<? extends ListenableFuture<? extends V>> futures) { requireNonNull(futures, "futures is null"); checkArgument(!isEmpty(futures), "futures is empty"); ExtendedSettableFuture<V> firstCompletedFuture = ExtendedSettableFuture.create(); for (ListenableFuture<? extends V> future : futures) { firstCompletedFuture.setAsync(future); } return firstCompletedFuture; } /** * Creates a future that completes when the first future completes either normally * or exceptionally. All other futures are cancelled when one completes. * Cancellation of the returned future propagates to the supplied futures. * <p> * It is critical for the performance of this function that * {@code guava.concurrent.generate_cancellation_cause} is false, * which is the default since Guava v20. */ public static <V> ListenableFuture<V> whenAnyCompleteCancelOthers(Iterable<? extends ListenableFuture<? extends V>> futures) { requireNonNull(futures, "futures is null"); checkArgument(!isEmpty(futures), "futures is empty"); // wait for the first task to unblock and then cancel all futures to free up resources ListenableFuture<V> anyComplete = whenAnyComplete(futures); anyComplete.addListener( () -> { for (ListenableFuture<?> future : futures) { future.cancel(true); } }, directExecutor()); return anyComplete; } /** * Creates a future that completes when the first future completes either normally * or exceptionally. Cancellation of the future does not propagate to the supplied * futures. */ @Deprecated public static <V> CompletableFuture<V> firstCompletedFuture(Iterable<? extends CompletionStage<? extends V>> futures) { return firstCompletedFuture(futures, false); } /** * Creates a future that completes when the first future completes either normally * or exceptionally. Cancellation of the future will optionally propagate to the * supplied futures. */ @Deprecated public static <V> CompletableFuture<V> firstCompletedFuture(Iterable<? extends CompletionStage<? extends V>> futures, boolean propagateCancel) { requireNonNull(futures, "futures is null"); checkArgument(!isEmpty(futures), "futures is empty"); CompletableFuture<V> future = new CompletableFuture<>(); for (CompletionStage<? extends V> stage : futures) { stage.whenComplete((value, exception) -> { if (exception != null) { future.completeExceptionally(exception); } else { future.complete(value); } }); } if (propagateCancel) { future.exceptionally(throwable -> { if (throwable instanceof CancellationException) { for (CompletionStage<? extends V> sourceFuture : futures) { if (sourceFuture instanceof Future) { ((Future<?>) sourceFuture).cancel(true); } } } return null; }); } return future; } /** * Returns an unmodifiable future that is completed when all of the given * futures complete. If any of the given futures complete exceptionally, then the * returned future also does so immediately, with a CompletionException holding this exception * as its cause. Otherwise, the results of the given futures are reflected in the * returned future as a list of results matching the input order. If no futures are * provided, returns a future completed with an empty list. */ @Deprecated public static <V> CompletableFuture<List<V>> allAsList(List<CompletableFuture<? extends V>> futures) { CompletableFuture<Void> allDoneFuture = CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])); // Eagerly propagate exceptions, rather than waiting for all the futures to complete first (default behavior) for (CompletableFuture<? extends V> future : futures) { future.whenComplete((v, throwable) -> { if (throwable != null) { allDoneFuture.completeExceptionally(throwable); } }); } return unmodifiableFuture(allDoneFuture.thenApply(v -> futures.stream() .map(CompletableFuture::join) .collect(Collectors.<V>toList()))); } /** * Returns a new future that is completed when the supplied future completes or * when the timeout expires. If the timeout occurs or the returned CompletableFuture * is canceled, the supplied future will be canceled. */ public static <T> ListenableFuture<T> addTimeout(ListenableFuture<T> future, Callable<T> onTimeout, Duration timeout, ScheduledExecutorService executorService) { AsyncFunction<TimeoutException, T> timeoutHandler = timeoutException -> { try { return immediateFuture(onTimeout.call()); } catch (Throwable throwable) { return immediateFailedFuture(throwable); } }; return FluentFuture.from(future) .withTimeout(timeout.toMillis(), MILLISECONDS, executorService) .catchingAsync(TimeoutException.class, timeoutHandler, directExecutor()); } /** * Returns a new future that is completed when the supplied future completes or * when the timeout expires. If the timeout occurs or the returned CompletableFuture * is canceled, the supplied future will be canceled. */ @Deprecated public static <T> CompletableFuture<T> addTimeout(CompletableFuture<T> future, Callable<T> onTimeout, Duration timeout, ScheduledExecutorService executorService) { requireNonNull(future, "future is null"); requireNonNull(onTimeout, "timeoutValue is null"); requireNonNull(timeout, "timeout is null"); requireNonNull(executorService, "executorService is null"); // if the future is already complete, just return it if (future.isDone()) { return future; } // create an unmodifiable future that propagates cancel // down cast is safe because this is our code UnmodifiableCompletableFuture<T> futureWithTimeout = (UnmodifiableCompletableFuture<T>) unmodifiableFuture(future, true); // schedule a task to complete the future when the time expires ScheduledFuture<?> timeoutTaskFuture = executorService.schedule(new TimeoutFutureTask<>(futureWithTimeout, onTimeout, future), timeout.toMillis(), MILLISECONDS); // when future completes, cancel the timeout task future.whenCompleteAsync((value, exception) -> timeoutTaskFuture.cancel(false), executorService); return futureWithTimeout; } /** * Converts a ListenableFuture to a CompletableFuture. Cancellation of the * CompletableFuture will be propagated to the ListenableFuture. */ public static <V> CompletableFuture<V> toCompletableFuture(ListenableFuture<V> listenableFuture) { requireNonNull(listenableFuture, "listenableFuture is null"); CompletableFuture<V> future = new CompletableFuture<>(); future.exceptionally(throwable -> { if (throwable instanceof CancellationException) { listenableFuture.cancel(true); } return null; }); FutureCallback<V> callback = new FutureCallback<V>() { @Override public void onSuccess(V result) { future.complete(result); } @Override public void onFailure(Throwable t) { future.completeExceptionally(t); } }; Futures.addCallback(listenableFuture, callback, directExecutor()); return future; } /** * Converts a CompletableFuture to a ListenableFuture. Cancellation of the * ListenableFuture will be propagated to the CompletableFuture. */ public static <V> ListenableFuture<V> toListenableFuture(CompletableFuture<V> completableFuture) { requireNonNull(completableFuture, "completableFuture is null"); SettableFuture<V> future = SettableFuture.create(); propagateCancellation(future, completableFuture, true); completableFuture.whenComplete((value, exception) -> { if (exception != null) { future.setException(exception); } else { future.set(value); } }); return future; } public static <T> void addSuccessCallback(ListenableFuture<T> future, Consumer<T> successCallback) { requireNonNull(future, "future is null"); requireNonNull(successCallback, "successCallback is null"); FutureCallback<T> callback = new FutureCallback<T>() { @Override public void onSuccess(@Nullable T result) { successCallback.accept(result); } @Override public void onFailure(Throwable t) {} }; Futures.addCallback(future, callback, directExecutor()); } public static <T> void addSuccessCallback(ListenableFuture<T> future, Runnable successCallback) { requireNonNull(successCallback, "successCallback is null"); addSuccessCallback(future, t -> successCallback.run()); } public static <T> void addExceptionCallback(ListenableFuture<T> future, Consumer<Throwable> exceptionCallback) { requireNonNull(future, "future is null"); requireNonNull(exceptionCallback, "exceptionCallback is null"); FutureCallback<T> callback = new FutureCallback<T>() { @Override public void onSuccess(@Nullable T result) {} @Override public void onFailure(Throwable t) { exceptionCallback.accept(t); } }; Futures.addCallback(future, callback, directExecutor()); } public static <T> void addExceptionCallback(ListenableFuture<T> future, Runnable exceptionCallback) { requireNonNull(exceptionCallback, "exceptionCallback is null"); addExceptionCallback(future, t -> exceptionCallback.run()); } private static class UnmodifiableCompletableFuture<V> extends CompletableFuture<V> { private final Function<Boolean, Boolean> onCancel; public UnmodifiableCompletableFuture(Function<Boolean, Boolean> onCancel) { this.onCancel = requireNonNull(onCancel, "onCancel is null"); } void internalComplete(V value) { super.complete(value); } void internalCompleteExceptionally(Throwable ex) { super.completeExceptionally(ex); } @Override public boolean cancel(boolean mayInterruptIfRunning) { return onCancel.apply(mayInterruptIfRunning); } @Override public boolean complete(V value) { throw new UnsupportedOperationException(); } @Override public boolean completeExceptionally(Throwable ex) { if (ex instanceof CancellationException) { return cancel(false); } throw new UnsupportedOperationException(); } @Override public void obtrudeValue(V value) { throw new UnsupportedOperationException(); } @Override public void obtrudeException(Throwable ex) { throw new UnsupportedOperationException(); } } private static class TimeoutFutureTask<T> implements Runnable { private final UnmodifiableCompletableFuture<T> settableFuture; private final Callable<T> timeoutValue; private final WeakReference<CompletableFuture<T>> futureReference; public TimeoutFutureTask(UnmodifiableCompletableFuture<T> settableFuture, Callable<T> timeoutValue, CompletableFuture<T> future) { this.settableFuture = settableFuture; this.timeoutValue = timeoutValue; // the scheduled executor can hold on to the timeout task for a long time, and // the future can reference large expensive objects. Since we are only interested // in canceling this future on a timeout, only hold a weak reference to the future this.futureReference = new WeakReference<>(future); } @Override public void run() { if (settableFuture.isDone()) { return; } // run the timeout task and set the result into the future try { T result = timeoutValue.call(); settableFuture.internalComplete(result); } catch (Throwable t) { settableFuture.internalCompleteExceptionally(t); throwIfInstanceOf(t, RuntimeException.class); } // cancel the original future, if it still exists Future<T> future = futureReference.get(); if (future != null) { future.cancel(true); } } } }
apache-2.0
electrum/airline
src/test/java/io/airlift/airline/args/ArgsArityString.java
1184
/* * Copyright (C) 2010 the original author or authors. * See the notice.md file distributed with this work for additional * information regarding copyright ownership. * * 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.airlift.airline.args; import io.airlift.airline.Arguments; import io.airlift.airline.Command; import io.airlift.airline.Option; import java.util.List; /** * Test parameter arity. * * @author cbeust */ @Command(name = "ArgsArityString") public class ArgsArityString { @Option(name = "-pairs", arity = 2, description = "Pairs") public List<String> pairs; @Arguments(description = "Rest") public List<String> rest; }
apache-2.0
zaevans/azure-sdk-for-net
src/ResourceManagement/DataFactory/DataFactoryManagement/Generated/Core/LinkedServiceOperations.cs
96609
// // Copyright (c) Microsoft and contributors. 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. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.DataFactories.Common.Models; using Microsoft.Azure.Management.DataFactories.Core; using Microsoft.Azure.Management.DataFactories.Core.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.DataFactories.Core { /// <summary> /// Operations for managing data factory internal linkedServices. /// </summary> internal partial class LinkedServiceOperations : IServiceOperations<DataFactoryManagementClient>, ILinkedServiceOperations { /// <summary> /// Initializes a new instance of the LinkedServiceOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal LinkedServiceOperations(DataFactoryManagementClient client) { this._client = client; } private DataFactoryManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.DataFactories.Core.DataFactoryManagementClient. /// </summary> public DataFactoryManagementClient Client { get { return this._client; } } /// <summary> /// Create or update a data factory linkedService. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. The name of the data factory. /// </param> /// <param name='parameters'> /// Required. The parameters required to create or update a data /// factory linkedService. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The create or update data factory linkedService operation response. /// </returns> public async Task<LinkedServiceCreateOrUpdateResponse> BeginCreateOrUpdateAsync(string resourceGroupName, string dataFactoryName, LinkedServiceCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.Length > 1000) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$") == false) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (dataFactoryName == null) { throw new ArgumentNullException("dataFactoryName"); } if (dataFactoryName != null && dataFactoryName.Length > 63) { throw new ArgumentOutOfRangeException("dataFactoryName"); } if (Regex.IsMatch(dataFactoryName, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$") == false) { throw new ArgumentOutOfRangeException("dataFactoryName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.LinkedService != null) { if (parameters.LinkedService.Name != null && parameters.LinkedService.Name.Length > 260) { throw new ArgumentOutOfRangeException("parameters.LinkedService.Name"); } if (Regex.IsMatch(parameters.LinkedService.Name, "^[A-Za-z0-9_][^<>*#.%&:\\\\+?/]*$") == false) { throw new ArgumentOutOfRangeException("parameters.LinkedService.Name"); } if (parameters.LinkedService.Properties != null) { if (parameters.LinkedService.Properties.Type == null) { throw new ArgumentNullException("parameters.LinkedService.Properties.Type"); } if (parameters.LinkedService.Properties.TypeProperties == null) { throw new ArgumentNullException("parameters.LinkedService.Properties.TypeProperties"); } } } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("dataFactoryName", dataFactoryName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "BeginCreateOrUpdateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/Microsoft.DataFactory/datafactories/"; url = url + Uri.EscapeDataString(dataFactoryName); url = url + "/linkedservices/"; if (parameters.LinkedService != null && parameters.LinkedService.Name != null) { url = url + Uri.EscapeDataString(parameters.LinkedService.Name); } List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-07-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject linkedServiceCreateOrUpdateParametersValue = new JObject(); requestDoc = linkedServiceCreateOrUpdateParametersValue; if (parameters.LinkedService != null) { if (parameters.LinkedService.Name != null) { linkedServiceCreateOrUpdateParametersValue["name"] = parameters.LinkedService.Name; } if (parameters.LinkedService.Properties != null) { JObject propertiesValue = new JObject(); linkedServiceCreateOrUpdateParametersValue["properties"] = propertiesValue; propertiesValue["type"] = parameters.LinkedService.Properties.Type; propertiesValue["typeProperties"] = JObject.Parse(parameters.LinkedService.Properties.TypeProperties); if (parameters.LinkedService.Properties.Description != null) { propertiesValue["description"] = parameters.LinkedService.Properties.Description; } if (parameters.LinkedService.Properties.ProvisioningState != null) { propertiesValue["provisioningState"] = parameters.LinkedService.Properties.ProvisioningState; } if (parameters.LinkedService.Properties.HubName != null) { propertiesValue["hubName"] = parameters.LinkedService.Properties.HubName; } if (parameters.LinkedService.Properties.ErrorMessage != null) { propertiesValue["errorMessage"] = parameters.LinkedService.Properties.ErrorMessage; } } } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result LinkedServiceCreateOrUpdateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new LinkedServiceCreateOrUpdateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { LinkedService linkedServiceInstance = new LinkedService(); result.LinkedService = linkedServiceInstance; JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); linkedServiceInstance.Name = nameInstance; } JToken propertiesValue2 = responseDoc["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { LinkedServiceProperties propertiesInstance = new LinkedServiceProperties(); linkedServiceInstance.Properties = propertiesInstance; JToken typeValue = propertiesValue2["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); propertiesInstance.Type = typeInstance; } JToken typePropertiesValue = propertiesValue2["typeProperties"]; if (typePropertiesValue != null && typePropertiesValue.Type != JTokenType.Null) { string typePropertiesInstance = typePropertiesValue.ToString(Newtonsoft.Json.Formatting.Indented); propertiesInstance.TypeProperties = typePropertiesInstance; } JToken descriptionValue = propertiesValue2["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); propertiesInstance.Description = descriptionInstance; } JToken provisioningStateValue = propertiesValue2["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); propertiesInstance.ProvisioningState = provisioningStateInstance; } JToken hubNameValue = propertiesValue2["hubName"]; if (hubNameValue != null && hubNameValue.Type != JTokenType.Null) { string hubNameInstance = ((string)hubNameValue); propertiesInstance.HubName = hubNameInstance; } JToken errorMessageValue = propertiesValue2["errorMessage"]; if (errorMessageValue != null && errorMessageValue.Type != JTokenType.Null) { string errorMessageInstance = ((string)errorMessageValue); propertiesInstance.ErrorMessage = errorMessageInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } result.Location = url; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Create or update a data factory linkedService with raw json content. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. The name of the data factory. /// </param> /// <param name='linkedServiceName'> /// Required. The name of the data factory table to be created or /// updated. /// </param> /// <param name='parameters'> /// Required. The parameters required to create or update a data /// factory linkedService. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The create or update data factory linkedService operation response. /// </returns> public async Task<LinkedServiceCreateOrUpdateResponse> BeginCreateOrUpdateWithRawJsonContentAsync(string resourceGroupName, string dataFactoryName, string linkedServiceName, LinkedServiceCreateOrUpdateWithRawJsonContentParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.Length > 1000) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$") == false) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (dataFactoryName == null) { throw new ArgumentNullException("dataFactoryName"); } if (dataFactoryName != null && dataFactoryName.Length > 63) { throw new ArgumentOutOfRangeException("dataFactoryName"); } if (Regex.IsMatch(dataFactoryName, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$") == false) { throw new ArgumentOutOfRangeException("dataFactoryName"); } if (linkedServiceName == null) { throw new ArgumentNullException("linkedServiceName"); } if (linkedServiceName != null && linkedServiceName.Length > 260) { throw new ArgumentOutOfRangeException("linkedServiceName"); } if (Regex.IsMatch(linkedServiceName, "^[A-Za-z0-9_][^<>*#.%&:\\\\+?/]*$") == false) { throw new ArgumentOutOfRangeException("linkedServiceName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Content == null) { throw new ArgumentNullException("parameters.Content"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("dataFactoryName", dataFactoryName); tracingParameters.Add("linkedServiceName", linkedServiceName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "BeginCreateOrUpdateWithRawJsonContentAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/Microsoft.DataFactory/datafactories/"; url = url + Uri.EscapeDataString(dataFactoryName); url = url + "/linkedservices/"; url = url + Uri.EscapeDataString(linkedServiceName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-07-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = parameters.Content; httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result LinkedServiceCreateOrUpdateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new LinkedServiceCreateOrUpdateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { LinkedService linkedServiceInstance = new LinkedService(); result.LinkedService = linkedServiceInstance; JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); linkedServiceInstance.Name = nameInstance; } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { LinkedServiceProperties propertiesInstance = new LinkedServiceProperties(); linkedServiceInstance.Properties = propertiesInstance; JToken typeValue = propertiesValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); propertiesInstance.Type = typeInstance; } JToken typePropertiesValue = propertiesValue["typeProperties"]; if (typePropertiesValue != null && typePropertiesValue.Type != JTokenType.Null) { string typePropertiesInstance = typePropertiesValue.ToString(Newtonsoft.Json.Formatting.Indented); propertiesInstance.TypeProperties = typePropertiesInstance; } JToken descriptionValue = propertiesValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); propertiesInstance.Description = descriptionInstance; } JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); propertiesInstance.ProvisioningState = provisioningStateInstance; } JToken hubNameValue = propertiesValue["hubName"]; if (hubNameValue != null && hubNameValue.Type != JTokenType.Null) { string hubNameInstance = ((string)hubNameValue); propertiesInstance.HubName = hubNameInstance; } JToken errorMessageValue = propertiesValue["errorMessage"]; if (errorMessageValue != null && errorMessageValue.Type != JTokenType.Null) { string errorMessageInstance = ((string)errorMessageValue); propertiesInstance.ErrorMessage = errorMessageInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } result.Location = url; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Delete a data factory linkedService instance. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='linkedServiceName'> /// Required. A unique data factory linkedService name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public async Task<LongRunningOperationResponse> BeginDeleteAsync(string resourceGroupName, string dataFactoryName, string linkedServiceName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.Length > 1000) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$") == false) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (dataFactoryName == null) { throw new ArgumentNullException("dataFactoryName"); } if (dataFactoryName != null && dataFactoryName.Length > 63) { throw new ArgumentOutOfRangeException("dataFactoryName"); } if (Regex.IsMatch(dataFactoryName, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$") == false) { throw new ArgumentOutOfRangeException("dataFactoryName"); } if (linkedServiceName == null) { throw new ArgumentNullException("linkedServiceName"); } if (linkedServiceName != null && linkedServiceName.Length > 260) { throw new ArgumentOutOfRangeException("linkedServiceName"); } if (Regex.IsMatch(linkedServiceName, "^[A-Za-z0-9_][^<>*#.%&:\\\\+?/]*$") == false) { throw new ArgumentOutOfRangeException("linkedServiceName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("dataFactoryName", dataFactoryName); tracingParameters.Add("linkedServiceName", linkedServiceName); TracingAdapter.Enter(invocationId, this, "BeginDeleteAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/Microsoft.DataFactory/datafactories/"; url = url + Uri.EscapeDataString(dataFactoryName); url = url + "/linkedservices/"; url = url + Uri.EscapeDataString(linkedServiceName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-07-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result LongRunningOperationResponse result = null; // Deserialize Response result = new LongRunningOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Location")) { result.OperationStatusLink = httpResponse.Headers.GetValues("Location").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (statusCode == HttpStatusCode.Conflict) { result.Status = OperationStatus.Failed; } if (statusCode == HttpStatusCode.NoContent) { result.Status = OperationStatus.Succeeded; } if (statusCode == HttpStatusCode.OK) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Create or update a data factory linkedService. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. The name of the data factory. /// </param> /// <param name='parameters'> /// Required. The parameters required to create or update a data /// factory linkedService. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The create or update data factory linkedService operation response. /// </returns> public async Task<LinkedServiceCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, string dataFactoryName, LinkedServiceCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { DataFactoryManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("dataFactoryName", dataFactoryName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); LinkedServiceCreateOrUpdateResponse response = await client.LinkedServices.BeginCreateOrUpdateAsync(resourceGroupName, dataFactoryName, parameters, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); LinkedServiceCreateOrUpdateResponse result = await client.LinkedServices.GetCreateOrUpdateStatusAsync(response.Location, cancellationToken).ConfigureAwait(false); int delayInSeconds = 5; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while ((result.Status != OperationStatus.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.LinkedServices.GetCreateOrUpdateStatusAsync(response.Location, cancellationToken).ConfigureAwait(false); delayInSeconds = 5; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } /// <summary> /// Create or update a data factory linkedService with raw json content. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. The name of the data factory. /// </param> /// <param name='linkedServiceName'> /// Required. The name of the data factory table to be created or /// updated. /// </param> /// <param name='parameters'> /// Required. The parameters required to create or update a data /// factory linkedService. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The create or update data factory linkedService operation response. /// </returns> public async Task<LinkedServiceCreateOrUpdateResponse> CreateOrUpdateWithRawJsonContentAsync(string resourceGroupName, string dataFactoryName, string linkedServiceName, LinkedServiceCreateOrUpdateWithRawJsonContentParameters parameters, CancellationToken cancellationToken) { DataFactoryManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("dataFactoryName", dataFactoryName); tracingParameters.Add("linkedServiceName", linkedServiceName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateWithRawJsonContentAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); LinkedServiceCreateOrUpdateResponse response = await client.LinkedServices.BeginCreateOrUpdateWithRawJsonContentAsync(resourceGroupName, dataFactoryName, linkedServiceName, parameters, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); LinkedServiceCreateOrUpdateResponse result = await client.LinkedServices.GetCreateOrUpdateStatusAsync(response.Location, cancellationToken).ConfigureAwait(false); int delayInSeconds = 5; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while ((result.Status != OperationStatus.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.LinkedServices.GetCreateOrUpdateStatusAsync(response.Location, cancellationToken).ConfigureAwait(false); delayInSeconds = 5; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } /// <summary> /// Delete a data factory linkedService instance. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='linkedServiceName'> /// Required. A unique data factory linkedService name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public async Task<LongRunningOperationResponse> DeleteAsync(string resourceGroupName, string dataFactoryName, string linkedServiceName, CancellationToken cancellationToken) { DataFactoryManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("dataFactoryName", dataFactoryName); tracingParameters.Add("linkedServiceName", linkedServiceName); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); LongRunningOperationResponse response = await client.LinkedServices.BeginDeleteAsync(resourceGroupName, dataFactoryName, linkedServiceName, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); LongRunningOperationResponse result = await client.GetLongRunningOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); int delayInSeconds = response.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 30; } if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while ((result.Status != OperationStatus.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetLongRunningOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); delayInSeconds = result.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 15; } if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } /// <summary> /// Gets a data factory linkedService instance. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='linkedServiceName'> /// Required. A unique data factory linkedService name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Get data factory linkedService operation response. /// </returns> public async Task<LinkedServiceGetResponse> GetAsync(string resourceGroupName, string dataFactoryName, string linkedServiceName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.Length > 1000) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$") == false) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (dataFactoryName == null) { throw new ArgumentNullException("dataFactoryName"); } if (dataFactoryName != null && dataFactoryName.Length > 63) { throw new ArgumentOutOfRangeException("dataFactoryName"); } if (Regex.IsMatch(dataFactoryName, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$") == false) { throw new ArgumentOutOfRangeException("dataFactoryName"); } if (linkedServiceName == null) { throw new ArgumentNullException("linkedServiceName"); } if (linkedServiceName != null && linkedServiceName.Length > 260) { throw new ArgumentOutOfRangeException("linkedServiceName"); } if (Regex.IsMatch(linkedServiceName, "^[A-Za-z0-9_][^<>*#.%&:\\\\+?/]*$") == false) { throw new ArgumentOutOfRangeException("linkedServiceName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("dataFactoryName", dataFactoryName); tracingParameters.Add("linkedServiceName", linkedServiceName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/Microsoft.DataFactory/datafactories/"; url = url + Uri.EscapeDataString(dataFactoryName); url = url + "/linkedservices/"; url = url + Uri.EscapeDataString(linkedServiceName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-07-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result LinkedServiceGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new LinkedServiceGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { LinkedService linkedServiceInstance = new LinkedService(); result.LinkedService = linkedServiceInstance; JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); linkedServiceInstance.Name = nameInstance; } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { LinkedServiceProperties propertiesInstance = new LinkedServiceProperties(); linkedServiceInstance.Properties = propertiesInstance; JToken typeValue = propertiesValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); propertiesInstance.Type = typeInstance; } JToken typePropertiesValue = propertiesValue["typeProperties"]; if (typePropertiesValue != null && typePropertiesValue.Type != JTokenType.Null) { string typePropertiesInstance = typePropertiesValue.ToString(Newtonsoft.Json.Formatting.Indented); propertiesInstance.TypeProperties = typePropertiesInstance; } JToken descriptionValue = propertiesValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); propertiesInstance.Description = descriptionInstance; } JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); propertiesInstance.ProvisioningState = provisioningStateInstance; } JToken hubNameValue = propertiesValue["hubName"]; if (hubNameValue != null && hubNameValue.Type != JTokenType.Null) { string hubNameInstance = ((string)hubNameValue); propertiesInstance.HubName = hubNameInstance; } JToken errorMessageValue = propertiesValue["errorMessage"]; if (errorMessageValue != null && errorMessageValue.Type != JTokenType.Null) { string errorMessageInstance = ((string)errorMessageValue); propertiesInstance.ErrorMessage = errorMessageInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The create or update data factory linkedService operation response. /// </returns> public async Task<LinkedServiceCreateOrUpdateResponse> GetCreateOrUpdateStatusAsync(string operationStatusLink, CancellationToken cancellationToken) { // Validate if (operationStatusLink == null) { throw new ArgumentNullException("operationStatusLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("operationStatusLink", operationStatusLink); TracingAdapter.Enter(invocationId, this, "GetCreateOrUpdateStatusAsync", tracingParameters); } // Construct URL string url = ""; url = url + operationStatusLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); httpRequest.Headers.Add("x-ms-version", "2015-07-01-preview"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result LinkedServiceCreateOrUpdateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new LinkedServiceCreateOrUpdateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { LinkedService linkedServiceInstance = new LinkedService(); result.LinkedService = linkedServiceInstance; JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); linkedServiceInstance.Name = nameInstance; } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { LinkedServiceProperties propertiesInstance = new LinkedServiceProperties(); linkedServiceInstance.Properties = propertiesInstance; JToken typeValue = propertiesValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); propertiesInstance.Type = typeInstance; } JToken typePropertiesValue = propertiesValue["typeProperties"]; if (typePropertiesValue != null && typePropertiesValue.Type != JTokenType.Null) { string typePropertiesInstance = typePropertiesValue.ToString(Newtonsoft.Json.Formatting.Indented); propertiesInstance.TypeProperties = typePropertiesInstance; } JToken descriptionValue = propertiesValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); propertiesInstance.Description = descriptionInstance; } JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); propertiesInstance.ProvisioningState = provisioningStateInstance; } JToken hubNameValue = propertiesValue["hubName"]; if (hubNameValue != null && hubNameValue.Type != JTokenType.Null) { string hubNameInstance = ((string)hubNameValue); propertiesInstance.HubName = hubNameInstance; } JToken errorMessageValue = propertiesValue["errorMessage"]; if (errorMessageValue != null && errorMessageValue.Type != JTokenType.Null) { string errorMessageInstance = ((string)errorMessageValue); propertiesInstance.ErrorMessage = errorMessageInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } result.Location = url; if (result.LinkedService != null && result.LinkedService.Properties != null && result.LinkedService.Properties.ProvisioningState == "Failed") { result.Status = OperationStatus.Failed; } if (result.LinkedService != null && result.LinkedService.Properties != null && result.LinkedService.Properties.ProvisioningState == "Succeeded") { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets the first page of linked service instances with the link to /// the next page. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List data factory linkedServices operation response. /// </returns> public async Task<LinkedServiceListResponse> ListAsync(string resourceGroupName, string dataFactoryName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.Length > 1000) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$") == false) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (dataFactoryName == null) { throw new ArgumentNullException("dataFactoryName"); } if (dataFactoryName != null && dataFactoryName.Length > 63) { throw new ArgumentOutOfRangeException("dataFactoryName"); } if (Regex.IsMatch(dataFactoryName, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$") == false) { throw new ArgumentOutOfRangeException("dataFactoryName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("dataFactoryName", dataFactoryName); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/Microsoft.DataFactory/datafactories/"; url = url + Uri.EscapeDataString(dataFactoryName); url = url + "/linkedServices"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-07-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result LinkedServiceListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new LinkedServiceListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { LinkedService linkedServiceInstance = new LinkedService(); result.LinkedServices.Add(linkedServiceInstance); JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); linkedServiceInstance.Name = nameInstance; } JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { LinkedServiceProperties propertiesInstance = new LinkedServiceProperties(); linkedServiceInstance.Properties = propertiesInstance; JToken typeValue = propertiesValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); propertiesInstance.Type = typeInstance; } JToken typePropertiesValue = propertiesValue["typeProperties"]; if (typePropertiesValue != null && typePropertiesValue.Type != JTokenType.Null) { string typePropertiesInstance = typePropertiesValue.ToString(Newtonsoft.Json.Formatting.Indented); propertiesInstance.TypeProperties = typePropertiesInstance; } JToken descriptionValue = propertiesValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); propertiesInstance.Description = descriptionInstance; } JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); propertiesInstance.ProvisioningState = provisioningStateInstance; } JToken hubNameValue = propertiesValue["hubName"]; if (hubNameValue != null && hubNameValue.Type != JTokenType.Null) { string hubNameInstance = ((string)hubNameValue); propertiesInstance.HubName = hubNameInstance; } JToken errorMessageValue = propertiesValue["errorMessage"]; if (errorMessageValue != null && errorMessageValue.Type != JTokenType.Null) { string errorMessageInstance = ((string)errorMessageValue); propertiesInstance.ErrorMessage = errorMessageInstance; } } } } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets the next page of linked service instances with the link to the /// next page. /// </summary> /// <param name='nextLink'> /// Required. The url to the next linked services page. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List data factory linkedServices operation response. /// </returns> public async Task<LinkedServiceListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = ""; url = url + nextLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result LinkedServiceListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new LinkedServiceListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { LinkedService linkedServiceInstance = new LinkedService(); result.LinkedServices.Add(linkedServiceInstance); JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); linkedServiceInstance.Name = nameInstance; } JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { LinkedServiceProperties propertiesInstance = new LinkedServiceProperties(); linkedServiceInstance.Properties = propertiesInstance; JToken typeValue = propertiesValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); propertiesInstance.Type = typeInstance; } JToken typePropertiesValue = propertiesValue["typeProperties"]; if (typePropertiesValue != null && typePropertiesValue.Type != JTokenType.Null) { string typePropertiesInstance = typePropertiesValue.ToString(Newtonsoft.Json.Formatting.Indented); propertiesInstance.TypeProperties = typePropertiesInstance; } JToken descriptionValue = propertiesValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); propertiesInstance.Description = descriptionInstance; } JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); propertiesInstance.ProvisioningState = provisioningStateInstance; } JToken hubNameValue = propertiesValue["hubName"]; if (hubNameValue != null && hubNameValue.Type != JTokenType.Null) { string hubNameInstance = ((string)hubNameValue); propertiesInstance.HubName = hubNameInstance; } JToken errorMessageValue = propertiesValue["errorMessage"]; if (errorMessageValue != null && errorMessageValue.Type != JTokenType.Null) { string errorMessageInstance = ((string)errorMessageValue); propertiesInstance.ErrorMessage = errorMessageInstance; } } } } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
apache-2.0
azurelogic/XdtExtended
XmlTransform/XmlLocator.cs
8661
using System; using System.Collections.Generic; using System.Diagnostics; using System.Xml; namespace Microsoft.Web.XmlTransform.Extended { public enum XPathAxis { Child, Descendant, Parent, Ancestor, FollowingSibling, PrecedingSibling, Following, Preceding, Self, DescendantOrSelf, AncestorOrSelf, } public abstract class Locator { #region private data members private string _argumentString; private IList<string> _arguments; private string _parentPath; private XmlElementContext _context; private XmlTransformationLogger _logger; #endregion protected virtual string ParentPath { get { return _parentPath; } } protected XmlNode CurrentElement { get { return _context.Element; } } virtual protected string NextStepNodeTest { get { if (!String.IsNullOrEmpty(CurrentElement.NamespaceURI) && String.IsNullOrEmpty(CurrentElement.Prefix)) return String.Concat("_defaultNamespace:", CurrentElement.LocalName); return CurrentElement.Name; } } virtual protected XPathAxis NextStepAxis { get { return XPathAxis.Child; } } protected virtual string ConstructPath() { return AppendStep(ParentPath, NextStepAxis, NextStepNodeTest, ConstructPredicate()); } protected string AppendStep(string basePath, string stepNodeTest) { return AppendStep(basePath, XPathAxis.Child, stepNodeTest, String.Empty); } protected string AppendStep(string basePath, XPathAxis stepAxis, string stepNodeTest) { return AppendStep(basePath, stepAxis, stepNodeTest, String.Empty); } protected string AppendStep(string basePath, string stepNodeTest, string predicate) { return AppendStep(basePath, XPathAxis.Child, stepNodeTest, predicate); } protected string AppendStep(string basePath, XPathAxis stepAxis, string stepNodeTest, string predicate) { return String.Concat( EnsureTrailingSlash(basePath), GetAxisString(stepAxis), stepNodeTest, EnsureBracketedPredicate(predicate)); } protected virtual string ConstructPredicate() { return String.Empty; } protected XmlTransformationLogger Log { get { if (_logger != null) return _logger; _logger = _context.GetService<XmlTransformationLogger>(); if (_logger != null) _logger.CurrentReferenceNode = _context.LocatorAttribute; return _logger; } } protected string ArgumentString { get { return _argumentString; } } protected IList<string> Arguments { get { if (_arguments == null && _argumentString != null) _arguments = XmlArgumentUtility.SplitArguments(_argumentString); return _arguments; } } protected void EnsureArguments() { EnsureArguments(1); } protected void EnsureArguments(int min) { if (Arguments == null || Arguments.Count < min) { throw new XmlTransformationException(string.Format(System.Globalization.CultureInfo.CurrentCulture, SR.XMLTRANSFORMATION_RequiresMinimumArguments, GetType().Name, min)); } } protected void EnsureArguments(int min, int max) { Debug.Assert(min <= max); if (min == max) if (Arguments == null || Arguments.Count != min) throw new XmlTransformationException(string.Format(System.Globalization.CultureInfo.CurrentCulture, SR.XMLTRANSFORMATION_RequiresExactArguments, GetType().Name, min)); EnsureArguments(min); if (Arguments.Count > max) throw new XmlTransformationException(string.Format(System.Globalization.CultureInfo.CurrentCulture, SR.XMLTRANSFORMATION_TooManyArguments, GetType().Name)); } internal string ConstructPath(string parentPath, XmlElementContext context, string argumentString) { Debug.Assert(_parentPath == null && _context == null && _argumentString == null, "Do not call ConstructPath recursively"); var resultPath = String.Empty; if (_parentPath != null || _context != null || _argumentString != null) return resultPath; try { _parentPath = parentPath; _context = context; _argumentString = argumentString; resultPath = ConstructPath(); } finally { _parentPath = null; _context = null; _argumentString = null; _arguments = null; ReleaseLogger(); } return resultPath; } internal string ConstructParentPath(string parentPath, XmlElementContext context, string argumentString) { Debug.Assert(_parentPath == null && _context == null && _argumentString == null, "Do not call ConstructPath recursively"); var resultPath = String.Empty; if (_parentPath != null || _context != null || _argumentString != null) return resultPath; try { _parentPath = parentPath; _context = context; _argumentString = argumentString; resultPath = ParentPath; } finally { _parentPath = null; _context = null; _argumentString = null; _arguments = null; ReleaseLogger(); } return resultPath; } private void ReleaseLogger() { if (_logger == null) return; _logger.CurrentReferenceNode = null; _logger = null; } private string GetAxisString(XPathAxis stepAxis) { switch (stepAxis) { case XPathAxis.Child: return String.Empty; case XPathAxis.Descendant: return "descendant::"; case XPathAxis.Parent: return "parent::"; case XPathAxis.Ancestor: return "ancestor::"; case XPathAxis.FollowingSibling: return "following-sibling::"; case XPathAxis.PrecedingSibling: return "preceding-sibling::"; case XPathAxis.Following: return "following::"; case XPathAxis.Preceding: return "preceding::"; case XPathAxis.Self: return "self::"; case XPathAxis.DescendantOrSelf: return "/"; case XPathAxis.AncestorOrSelf: return "ancestor-or-self::"; default: Debug.Fail("There should be no XPathAxis enum value that isn't handled in this switch statement"); return String.Empty; } } private string EnsureTrailingSlash(string basePath) { if (!basePath.EndsWith("/", StringComparison.Ordinal)) { basePath = String.Concat(basePath, "/"); } return basePath; } private string EnsureBracketedPredicate(string predicate) { if (String.IsNullOrEmpty(predicate)) { return String.Empty; } if (!predicate.StartsWith("[", StringComparison.Ordinal)) { predicate = String.Concat("[", predicate); } if (!predicate.EndsWith("]", StringComparison.Ordinal)) { predicate = String.Concat(predicate, "]"); } return predicate; } } }
apache-2.0
tavultesoft/keymanweb
windows/src/support/NetInputBoxTest/NetInputBoxTest/Program.cs
914
/* Name: Program Copyright: Copyright (C) 2003-2012 Software For Specialists Ltd. Documentation: Description: Create Date: 29 Mar 2015 Modified Date: 29 Mar 2015 Authors: mcdurdin Related Files: Dependencies: Bugs: Todo: Notes: History: 29 Mar 2015 - mcdurdin - I4642 - V9.0 - In Logos, generated backspace receives a scan of 0x00 instead of 0xFF */ using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace NetInputBoxTest { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
apache-2.0
freightlive/bumbal-client-api-php
src/Model/PauseListResponse.php
7532
<?php /** * PauseListResponse * * PHP version 5 * * @category Class * @package BumbalClient * @author Swaagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ /** * Bumbal Client Api * * Bumbal API documentation * * OpenAPI spec version: 2.0 * Contact: gerb@bumbal.eu * Generated by: https://github.com/swagger-api/swagger-codegen.git * */ /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ namespace BumbalClient\Model; use \ArrayAccess; /** * PauseListResponse Class Doc Comment * * @category Class * @package BumbalClient * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ class PauseListResponse implements ArrayAccess { const DISCRIMINATOR = null; /** * The original name of the model. * @var string */ protected static $swaggerModelName = 'PauseListResponse'; /** * Array of property to type mappings. Used for (de)serialization * @var string[] */ protected static $swaggerTypes = [ 'items' => '\BumbalClient\Model\PauseModel[]', 'count_filtered' => 'int', 'count_unfiltered' => 'int', 'count_limited' => 'int' ]; /** * Array of property to format mappings. Used for (de)serialization * @var string[] */ protected static $swaggerFormats = [ 'items' => null, 'count_filtered' => null, 'count_unfiltered' => null, 'count_limited' => null ]; public static function swaggerTypes() { return self::$swaggerTypes; } public static function swaggerFormats() { return self::$swaggerFormats; } /** * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ protected static $attributeMap = [ 'items' => 'items', 'count_filtered' => 'count_filtered', 'count_unfiltered' => 'count_unfiltered', 'count_limited' => 'count_limited' ]; /** * Array of attributes to setter functions (for deserialization of responses) * @var string[] */ protected static $setters = [ 'items' => 'setItems', 'count_filtered' => 'setCountFiltered', 'count_unfiltered' => 'setCountUnfiltered', 'count_limited' => 'setCountLimited' ]; /** * Array of attributes to getter functions (for serialization of requests) * @var string[] */ protected static $getters = [ 'items' => 'getItems', 'count_filtered' => 'getCountFiltered', 'count_unfiltered' => 'getCountUnfiltered', 'count_limited' => 'getCountLimited' ]; public static function attributeMap() { return self::$attributeMap; } public static function setters() { return self::$setters; } public static function getters() { return self::$getters; } /** * Associative array for storing property values * @var mixed[] */ protected $container = []; /** * Constructor * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { $this->container['items'] = isset($data['items']) ? $data['items'] : null; $this->container['count_filtered'] = isset($data['count_filtered']) ? $data['count_filtered'] : null; $this->container['count_unfiltered'] = isset($data['count_unfiltered']) ? $data['count_unfiltered'] : null; $this->container['count_limited'] = isset($data['count_limited']) ? $data['count_limited'] : null; } /** * show all the invalid properties with reasons. * * @return array invalid properties with reasons */ public function listInvalidProperties() { $invalid_properties = []; return $invalid_properties; } /** * validate all the properties in the model * return true if all passed * * @return bool True if all properties are valid */ public function valid() { return true; } /** * Gets items * @return \BumbalClient\Model\PauseModel[] */ public function getItems() { return $this->container['items']; } /** * Sets items * @param \BumbalClient\Model\PauseModel[] $items * @return $this */ public function setItems($items) { $this->container['items'] = $items; return $this; } /** * Gets count_filtered * @return int */ public function getCountFiltered() { return $this->container['count_filtered']; } /** * Sets count_filtered * @param int $count_filtered Count of total items with filters in place * @return $this */ public function setCountFiltered($count_filtered) { $this->container['count_filtered'] = $count_filtered; return $this; } /** * Gets count_unfiltered * @return int */ public function getCountUnfiltered() { return $this->container['count_unfiltered']; } /** * Sets count_unfiltered * @param int $count_unfiltered Count of total items without filters in place * @return $this */ public function setCountUnfiltered($count_unfiltered) { $this->container['count_unfiltered'] = $count_unfiltered; return $this; } /** * Gets count_limited * @return int */ public function getCountLimited() { return $this->container['count_limited']; } /** * Sets count_limited * @param int $count_limited Count of items with limit in place * @return $this */ public function setCountLimited($count_limited) { $this->container['count_limited'] = $count_limited; return $this; } /** * Returns true if offset exists. False otherwise. * @param integer $offset Offset * @return boolean */ public function offsetExists($offset) { return isset($this->container[$offset]); } /** * Gets offset. * @param integer $offset Offset * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } /** * Sets value based on offset. * @param integer $offset Offset * @param mixed $value Value to be set * @return void */ public function offsetSet($offset, $value) { if (is_null($offset)) { $this->container[] = $value; } else { $this->container[$offset] = $value; } } /** * Unsets offset. * @param integer $offset Offset * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } /** * Gets the string presentation of the object * @return string */ public function __toString() { if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print return json_encode(\BumbalClient\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); } return json_encode(\BumbalClient\ObjectSerializer::sanitizeForSerialization($this)); } }
apache-2.0
lessthanoptimal/ejml
examples/src/org/ejml/example/ExampleComplexMath.java
2091
/* * Copyright (c) 2009-2018, Peter Abeles. All Rights Reserved. * * This file is part of Efficient Java Matrix Library (EJML). * * 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.ejml.example; import org.ejml.data.ComplexPolar_F64; import org.ejml.data.Complex_F64; import org.ejml.ops.ComplexMath_F64; /** * Demonstration of different operations that can be performed on complex numbers. * * @author Peter Abeles */ public class ExampleComplexMath { public static void main( String []args ) { Complex_F64 a = new Complex_F64(1,2); Complex_F64 b = new Complex_F64(-1,-0.6); Complex_F64 c = new Complex_F64(); ComplexPolar_F64 polarC = new ComplexPolar_F64(); System.out.println("a = "+a); System.out.println("b = "+b); System.out.println("------------------"); ComplexMath_F64.plus(a, b, c); System.out.println("a + b = "+c); ComplexMath_F64.minus(a, b, c); System.out.println("a - b = "+c); ComplexMath_F64.multiply(a, b, c); System.out.println("a * b = "+c); ComplexMath_F64.divide(a, b, c); System.out.println("a / b = "+c); System.out.println("------------------"); ComplexPolar_F64 polarA = new ComplexPolar_F64(); ComplexMath_F64.convert(a, polarA); System.out.println("polar notation of a = "+polarA); ComplexMath_F64.pow(polarA, 3, polarC); System.out.println("a ** 3 = "+polarC); ComplexMath_F64.convert(polarC, c); System.out.println("a ** 3 = "+c); } }
apache-2.0
dagnir/aws-sdk-java
aws-java-sdk-clouddirectory/src/main/java/com/amazonaws/services/clouddirectory/model/transform/EnableDirectoryResultJsonUnmarshaller.java
2847
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.clouddirectory.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.clouddirectory.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * EnableDirectoryResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class EnableDirectoryResultJsonUnmarshaller implements Unmarshaller<EnableDirectoryResult, JsonUnmarshallerContext> { public EnableDirectoryResult unmarshall(JsonUnmarshallerContext context) throws Exception { EnableDirectoryResult enableDirectoryResult = new EnableDirectoryResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return enableDirectoryResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("DirectoryArn", targetDepth)) { context.nextToken(); enableDirectoryResult.setDirectoryArn(context.getUnmarshaller(String.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return enableDirectoryResult; } private static EnableDirectoryResultJsonUnmarshaller instance; public static EnableDirectoryResultJsonUnmarshaller getInstance() { if (instance == null) instance = new EnableDirectoryResultJsonUnmarshaller(); return instance; } }
apache-2.0
KEOpenSource/SimulynIO
src/file/save/view/SaveDocumentFileChooserView.java
2151
/* FileChooserView -- a class within the FileManagerFramework. Copyright (C) 2012, Kaleb Kircher. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package file.save.view; import file.util.globals.Globals; import file.save.controller.SaveFileControllerInterface; import file.util.filters.TxtFilter; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFileChooser; /** * A special JFileChoser View that is integrated into an MVC library * that allows files to be parsed with different parsing algorithms. * @author Kaleb */ public class SaveDocumentFileChooserView extends JFileChooser { private SaveFileControllerInterface fileController; /** * Initialize the SaveFileChooserView a SaveFileControllerInterface. * @param fileController */ public SaveDocumentFileChooserView(SaveFileControllerInterface fileController) { // Start in the C:/ drive super(Globals.defaultDirectory); this.addChoosableFileFilter(new TxtFilter()); this.fileController = fileController; // Select the file this.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { { // Update the controller SaveDocumentFileChooserView.this.fileController.saveFile(SaveDocumentFileChooserView.this.getSelectedFile().getPath()); } } }); } }
apache-2.0
timdown/log4javascript2
src/loggingevent.js
1454
(function(api) { var LoggingEvent = function(logger, timeStamp, level, messages, exception) { this.logger = logger; this.timeStamp = timeStamp; this.timeStampInMilliseconds = +timeStamp; this.timeStampInSeconds = Math.floor(this.timeStampInMilliseconds / 1000); this.milliseconds = this.timeStamp.getMilliseconds(); this.level = level; this.messages = messages; this.exception = exception; }; api.extend(LoggingEvent.prototype = { getThrowableStrRep: function() { return this.exception ? api.exceptionToStr(this.exception) : ""; }, getCombinedMessages: function() { var messages = this.messages; return (messages.length == 1) ? messages[0] : messages.join("\r\n"); }, /* getRenderedMessages: function() { var renderedMessages = []; for (var i = 0, len = this.messages.length; i < len; ++i) { renderedMessages[i] = render(this.messages[i]); } return renderedMessages; }, getCombinedRenderedMessages: function() { return (this.messages.length == 1) ? render( this.messages[0] ) : this.getRenderedMessages().join(newLine); }, */ toString: function() { return "LoggingEvent[" + this.level + "]"; } }); api.LoggingEvent = LoggingEvent; })(log4javascript);
apache-2.0
weiPlace/Day366
application/models/Database/Table/Userinfo.php
219
<?php require_once('Zend/Db/Table/Abstract.php'); class Database_Table_Userinfo extends Zend_Db_Table { protected function _setup(){ $this->_name='user'; $this->_primary='user_id'; parent::_setup(); } } ?>
apache-2.0
spf13/afero
iofs_test.go
8973
// +build go1.16 package afero import ( "bytes" "errors" "io" "io/fs" "os" "testing" "testing/fstest" "time" ) func TestIOFS(t *testing.T) { t.Parallel() t.Run("use MemMapFs", func(t *testing.T) { mmfs := NewMemMapFs() err := mmfs.MkdirAll("dir1/dir2", os.ModePerm) if err != nil { t.Fatal("MkdirAll failed:", err) } f, err := mmfs.OpenFile("dir1/dir2/test.txt", os.O_RDWR|os.O_CREATE, os.ModePerm) if err != nil { t.Fatal("OpenFile (O_CREATE) failed:", err) } f.Close() if err := fstest.TestFS(NewIOFS(mmfs), "dir1/dir2/test.txt"); err != nil { t.Error(err) } }) t.Run("use OsFs", func(t *testing.T) { osfs := NewBasePathFs(NewOsFs(), t.TempDir()) err := osfs.MkdirAll("dir1/dir2", os.ModePerm) if err != nil { t.Fatal("MkdirAll failed:", err) } f, err := osfs.OpenFile("dir1/dir2/test.txt", os.O_RDWR|os.O_CREATE, os.ModePerm) if err != nil { t.Fatal("OpenFile (O_CREATE) failed:", err) } f.Close() if err := fstest.TestFS(NewIOFS(osfs), "dir1/dir2/test.txt"); err != nil { t.Error(err) } }) } func TestFromIOFS(t *testing.T) { t.Parallel() fsys := fstest.MapFS{ "test.txt": { Data: []byte("File in root"), Mode: fs.ModePerm, ModTime: time.Now(), }, "dir1": { Mode: fs.ModeDir | fs.ModePerm, ModTime: time.Now(), }, "dir1/dir2": { Mode: fs.ModeDir | fs.ModePerm, ModTime: time.Now(), }, "dir1/dir2/hello.txt": { Data: []byte("Hello world"), Mode: fs.ModePerm, ModTime: time.Now(), }, } fromIOFS := FromIOFS{fsys} t.Run("Create", func(t *testing.T) { _, err := fromIOFS.Create("test") assertPermissionError(t, err) }) t.Run("Mkdir", func(t *testing.T) { err := fromIOFS.Mkdir("test", 0) assertPermissionError(t, err) }) t.Run("MkdirAll", func(t *testing.T) { err := fromIOFS.Mkdir("test", 0) assertPermissionError(t, err) }) t.Run("Open", func(t *testing.T) { t.Run("non existing file", func(t *testing.T) { _, err := fromIOFS.Open("nonexisting") if !errors.Is(err, fs.ErrNotExist) { t.Errorf("Expected error to be fs.ErrNotExist, got %[1]T (%[1]v)", err) } }) t.Run("directory", func(t *testing.T) { dirFile, err := fromIOFS.Open("dir1") if err != nil { t.Errorf("dir1 open failed: %v", err) return } defer dirFile.Close() dirStat, err := dirFile.Stat() if err != nil { t.Errorf("dir1 stat failed: %v", err) return } if !dirStat.IsDir() { t.Errorf("dir1 stat told that it is not a directory") return } }) t.Run("simple file", func(t *testing.T) { file, err := fromIOFS.Open("test.txt") if err != nil { t.Errorf("test.txt open failed: %v", err) return } defer file.Close() fileStat, err := file.Stat() if err != nil { t.Errorf("test.txt stat failed: %v", err) return } if fileStat.IsDir() { t.Errorf("test.txt stat told that it is a directory") return } }) }) t.Run("Remove", func(t *testing.T) { err := fromIOFS.Remove("test") assertPermissionError(t, err) }) t.Run("Rename", func(t *testing.T) { err := fromIOFS.Rename("test", "test2") assertPermissionError(t, err) }) t.Run("Stat", func(t *testing.T) { t.Run("non existing file", func(t *testing.T) { _, err := fromIOFS.Stat("nonexisting") if !errors.Is(err, fs.ErrNotExist) { t.Errorf("Expected error to be fs.ErrNotExist, got %[1]T (%[1]v)", err) } }) t.Run("directory", func(t *testing.T) { stat, err := fromIOFS.Stat("dir1/dir2") if err != nil { t.Errorf("dir1/dir2 stat failed: %v", err) return } if !stat.IsDir() { t.Errorf("dir1/dir2 stat told that it is not a directory") return } }) t.Run("file", func(t *testing.T) { stat, err := fromIOFS.Stat("dir1/dir2/hello.txt") if err != nil { t.Errorf("dir1/dir2 stat failed: %v", err) return } if stat.IsDir() { t.Errorf("dir1/dir2/hello.txt stat told that it is a directory") return } if lenFile := len(fsys["dir1/dir2/hello.txt"].Data); int64(lenFile) != stat.Size() { t.Errorf("dir1/dir2/hello.txt stat told invalid size: expected %d, got %d", lenFile, stat.Size()) return } }) }) t.Run("Chmod", func(t *testing.T) { err := fromIOFS.Chmod("test", os.ModePerm) assertPermissionError(t, err) }) t.Run("Chown", func(t *testing.T) { err := fromIOFS.Chown("test", 0, 0) assertPermissionError(t, err) }) t.Run("Chtimes", func(t *testing.T) { err := fromIOFS.Chtimes("test", time.Now(), time.Now()) assertPermissionError(t, err) }) } func TestFromIOFS_File(t *testing.T) { t.Parallel() fsys := fstest.MapFS{ "test.txt": { Data: []byte("File in root"), Mode: fs.ModePerm, ModTime: time.Now(), }, "dir1": { Mode: fs.ModeDir | fs.ModePerm, ModTime: time.Now(), }, "dir2": { Mode: fs.ModeDir | fs.ModePerm, ModTime: time.Now(), }, } fromIOFS := FromIOFS{fsys} file, err := fromIOFS.Open("test.txt") if err != nil { t.Errorf("test.txt open failed: %v", err) return } defer file.Close() fileStat, err := file.Stat() if err != nil { t.Errorf("test.txt stat failed: %v", err) return } if fileStat.IsDir() { t.Errorf("test.txt stat told that it is a directory") return } t.Run("ReadAt", func(t *testing.T) { // MapFS files implements io.ReaderAt b := make([]byte, 2) _, err := file.ReadAt(b, 2) if err != nil { t.Errorf("ReadAt failed: %v", err) return } if expectedData := fsys["test.txt"].Data[2:4]; !bytes.Equal(b, expectedData) { t.Errorf("Unexpected content read: %s, expected %s", b, expectedData) } }) t.Run("Seek", func(t *testing.T) { n, err := file.Seek(2, io.SeekStart) if err != nil { t.Errorf("Seek failed: %v", err) return } if n != 2 { t.Errorf("Seek returned unexpected value: %d, expected 2", n) } }) t.Run("Write", func(t *testing.T) { _, err := file.Write(nil) assertPermissionError(t, err) }) t.Run("WriteAt", func(t *testing.T) { _, err := file.WriteAt(nil, 0) assertPermissionError(t, err) }) t.Run("Name", func(t *testing.T) { if name := file.Name(); name != "test.txt" { t.Errorf("expected file.Name() == test.txt, got %s", name) } }) t.Run("Readdir", func(t *testing.T) { t.Run("not directory", func(t *testing.T) { _, err := file.Readdir(-1) assertPermissionError(t, err) }) t.Run("root directory", func(t *testing.T) { root, err := fromIOFS.Open(".") if err != nil { t.Errorf("root open failed: %v", err) return } defer root.Close() items, err := root.Readdir(-1) if err != nil { t.Errorf("Readdir error: %v", err) return } var expectedItems = []struct { Name string IsDir bool Size int64 }{ {Name: "dir1", IsDir: true, Size: 0}, {Name: "dir2", IsDir: true, Size: 0}, {Name: "test.txt", IsDir: false, Size: int64(len(fsys["test.txt"].Data))}, } if len(expectedItems) != len(items) { t.Errorf("Items count mismatch, expected %d, got %d", len(expectedItems), len(items)) return } for i, item := range items { if item.Name() != expectedItems[i].Name { t.Errorf("Item %d: expected name %s, got %s", i, expectedItems[i].Name, item.Name()) } if item.IsDir() != expectedItems[i].IsDir { t.Errorf("Item %d: expected IsDir %t, got %t", i, expectedItems[i].IsDir, item.IsDir()) } if item.Size() != expectedItems[i].Size { t.Errorf("Item %d: expected IsDir %d, got %d", i, expectedItems[i].Size, item.Size()) } } }) }) t.Run("Readdirnames", func(t *testing.T) { t.Run("not directory", func(t *testing.T) { _, err := file.Readdirnames(-1) assertPermissionError(t, err) }) t.Run("root directory", func(t *testing.T) { root, err := fromIOFS.Open(".") if err != nil { t.Errorf("root open failed: %v", err) return } defer root.Close() items, err := root.Readdirnames(-1) if err != nil { t.Errorf("Readdirnames error: %v", err) return } var expectedItems = []string{"dir1", "dir2", "test.txt"} if len(expectedItems) != len(items) { t.Errorf("Items count mismatch, expected %d, got %d", len(expectedItems), len(items)) return } for i, item := range items { if item != expectedItems[i] { t.Errorf("Item %d: expected name %s, got %s", i, expectedItems[i], item) } } }) }) t.Run("Truncate", func(t *testing.T) { err := file.Truncate(1) assertPermissionError(t, err) }) t.Run("WriteString", func(t *testing.T) { _, err := file.WriteString("a") assertPermissionError(t, err) }) } func assertPermissionError(t *testing.T, err error) { t.Helper() var perr *fs.PathError if !errors.As(err, &perr) { t.Errorf("Expected *fs.PathError, got %[1]T (%[1]v)", err) return } if perr.Err != fs.ErrPermission { t.Errorf("Expected (*fs.PathError).Err == fs.ErrPermisson, got %[1]T (%[1]v)", err) } }
apache-2.0
sschepens/pulsar
pulsar-broker/src/test/java/org/apache/pulsar/client/impl/UnAcknowledgedMessagesTimeoutTest.java
17184
/** * 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.pulsar.client.impl; import static org.testng.Assert.assertEquals; import java.util.HashSet; import java.util.concurrent.TimeUnit; import org.apache.pulsar.broker.service.BrokerTestBase; import org.apache.pulsar.client.api.Consumer; import org.apache.pulsar.client.api.Message; import org.apache.pulsar.client.api.MessageId; import org.apache.pulsar.client.api.MessageRoutingMode; import org.apache.pulsar.client.api.Producer; import org.apache.pulsar.client.api.PulsarClientException; import org.apache.pulsar.client.api.SubscriptionType; import org.apache.pulsar.common.policies.data.PropertyAdmin; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class UnAcknowledgedMessagesTimeoutTest extends BrokerTestBase { private static final long testTimeout = 90000; // 1.5 min private static final Logger log = LoggerFactory.getLogger(UnAcknowledgedMessagesTimeoutTest.class); private final long ackTimeOutMillis = TimeUnit.SECONDS.toMillis(2); @Override @BeforeMethod public void setup() throws Exception { super.internalSetup(); } @Override @AfterMethod public void cleanup() throws Exception { super.internalCleanup(); } @Test(timeOut = testTimeout) public void testExclusiveSingleAckedNormalTopic() throws Exception { String key = "testExclusiveSingleAckedNormalTopic"; final String topicName = "persistent://prop/use/ns-abc/topic-" + key; final String subscriptionName = "my-ex-subscription-" + key; final String messagePredicate = "my-message-" + key + "-"; final int totalMessages = 10; // 1. producer connect Producer<byte[]> producer = pulsarClient.newProducer().topic(topicName).create(); // 2. Create consumer Consumer<byte[]> consumer = pulsarClient.newConsumer().topic(topicName).subscriptionName(subscriptionName) .receiverQueueSize(7).ackTimeout(ackTimeOutMillis, TimeUnit.MILLISECONDS).subscribe(); // 3. producer publish messages for (int i = 0; i < totalMessages / 2; i++) { String message = messagePredicate + i; log.info("Producer produced: " + message); producer.send(message.getBytes()); } // 4. Receiver receives the message Message<byte[]> message = consumer.receive(); while (message != null) { log.info("Consumer received : " + new String(message.getData())); message = consumer.receive(500, TimeUnit.MILLISECONDS); } long size = ((ConsumerImpl<?>) consumer).getUnAckedMessageTracker().size(); log.info(key + " Unacked Message Tracker size is " + size); assertEquals(size, totalMessages / 2); // Blocking call, redeliver should kick in message = consumer.receive(); log.info("Consumer received : " + new String(message.getData())); HashSet<String> hSet = new HashSet<>(); for (int i = totalMessages / 2; i < totalMessages; i++) { String messageString = messagePredicate + i; producer.send(messageString.getBytes()); } do { hSet.add(new String(message.getData())); consumer.acknowledge(message); log.info("Consumer acknowledged : " + new String(message.getData())); message = consumer.receive(500, TimeUnit.MILLISECONDS); } while (message != null); size = ((ConsumerImpl<?>) consumer).getUnAckedMessageTracker().size(); log.info(key + " Unacked Message Tracker size is " + size); assertEquals(size, 0); assertEquals(hSet.size(), totalMessages); } @Test(timeOut = testTimeout) public void testExclusiveCumulativeAckedNormalTopic() throws Exception { String key = "testExclusiveCumulativeAckedNormalTopic"; final String topicName = "persistent://prop/use/ns-abc/topic-" + key; final String subscriptionName = "my-ex-subscription-" + key; final String messagePredicate = "my-message-" + key + "-"; final int totalMessages = 10; // 1. producer connect Producer<byte[]> producer = pulsarClient.newProducer().topic(topicName).create(); // 2. Create consumer Consumer<byte[]> consumer = pulsarClient.newConsumer().topic(topicName).subscriptionName(subscriptionName) .receiverQueueSize(7).ackTimeout(ackTimeOutMillis, TimeUnit.MILLISECONDS).subscribe(); // 3. producer publish messages for (int i = 0; i < totalMessages; i++) { String message = messagePredicate + i; producer.send(message.getBytes()); } // 4. Receiver receives the message HashSet<String> hSet = new HashSet<>(); Message<byte[]> message = consumer.receive(); Message<byte[]> lastMessage = message; while (message != null) { lastMessage = message; hSet.add(new String(message.getData())); log.info("Consumer received " + new String(message.getData())); log.info("Message ID details " + ((MessageIdImpl) message.getMessageId()).toString()); message = consumer.receive(500, TimeUnit.MILLISECONDS); } long size = ((ConsumerImpl<?>) consumer).getUnAckedMessageTracker().size(); assertEquals(size, totalMessages); log.info("Comulative Ack sent for " + new String(lastMessage.getData())); log.info("Message ID details " + ((MessageIdImpl) lastMessage.getMessageId()).toString()); consumer.acknowledgeCumulative(lastMessage); size = ((ConsumerImpl<?>) consumer).getUnAckedMessageTracker().size(); assertEquals(size, 0); message = consumer.receive((int) (2 * ackTimeOutMillis), TimeUnit.MILLISECONDS); assertEquals(message, null); } @Test(timeOut = testTimeout) public void testSharedSingleAckedPartitionedTopic() throws Exception { String key = "testSharedSingleAckedPartitionedTopic"; final String topicName = "persistent://prop/use/ns-abc/topic-" + key; final String subscriptionName = "my-shared-subscription-" + key; final String messagePredicate = "my-message-" + key + "-"; final int totalMessages = 20; final int numberOfPartitions = 3; admin.properties().createProperty("prop", new PropertyAdmin()); admin.persistentTopics().createPartitionedTopic(topicName, numberOfPartitions); // Special step to create partitioned topic // 1. producer connect Producer<byte[]> producer = pulsarClient.newProducer().topic(topicName) .messageRoutingMode(MessageRoutingMode.RoundRobinPartition).create(); // 2. Create consumer Consumer<byte[]> consumer1 = pulsarClient.newConsumer().topic(topicName).subscriptionName(subscriptionName) .receiverQueueSize(100).subscriptionType(SubscriptionType.Shared) .ackTimeout(ackTimeOutMillis, TimeUnit.MILLISECONDS).consumerName("Consumer-1").subscribe(); Consumer<byte[]> consumer2 = pulsarClient.newConsumer().topic(topicName).subscriptionName(subscriptionName) .receiverQueueSize(100).subscriptionType(SubscriptionType.Shared) .ackTimeout(ackTimeOutMillis, TimeUnit.MILLISECONDS).consumerName("Consumer-2").subscribe(); // 3. producer publish messages for (int i = 0; i < totalMessages; i++) { String message = messagePredicate + i; MessageId msgId = producer.send(message.getBytes()); log.info("Message produced: {} -- msgId: {}", message, msgId); } // 4. Receive messages int messageCount1 = receiveAllMessage(consumer1, false /* no-ack */); int messageCount2 = receiveAllMessage(consumer2, true /* yes-ack */); int ackCount1 = 0; int ackCount2 = messageCount2; log.info(key + " messageCount1 = " + messageCount1); log.info(key + " messageCount2 = " + messageCount2); log.info(key + " ackCount1 = " + ackCount1); log.info(key + " ackCount2 = " + ackCount2); assertEquals(messageCount1 + messageCount2, totalMessages); // 5. Check if Messages redelivered again // Since receive is a blocking call hoping that timeout will kick in Thread.sleep((int) (ackTimeOutMillis * 1.1)); log.info(key + " Timeout should be triggered now"); messageCount1 = receiveAllMessage(consumer1, true); messageCount2 += receiveAllMessage(consumer2, false); ackCount1 = messageCount1; log.info(key + " messageCount1 = " + messageCount1); log.info(key + " messageCount2 = " + messageCount2); log.info(key + " ackCount1 = " + ackCount1); log.info(key + " ackCount2 = " + ackCount2); assertEquals(messageCount1 + messageCount2, totalMessages); assertEquals(ackCount1 + messageCount2, totalMessages); Thread.sleep((int) (ackTimeOutMillis * 1.1)); // Since receive is a blocking call hoping that timeout will kick in log.info(key + " Timeout should be triggered again"); ackCount1 += receiveAllMessage(consumer1, true); ackCount2 += receiveAllMessage(consumer2, true); log.info(key + " ackCount1 = " + ackCount1); log.info(key + " ackCount2 = " + ackCount2); assertEquals(ackCount1 + ackCount2, totalMessages); } private static int receiveAllMessage(Consumer<?> consumer, boolean ackMessages) throws Exception { int messagesReceived = 0; Message<?> msg = consumer.receive(1, TimeUnit.SECONDS); while (msg != null) { ++messagesReceived; log.info("Consumer received {}", new String(msg.getData())); if (ackMessages) { consumer.acknowledge(msg); } msg = consumer.receive(1, TimeUnit.SECONDS); } return messagesReceived; } @Test(timeOut = testTimeout) public void testFailoverSingleAckedPartitionedTopic() throws Exception { String key = "testFailoverSingleAckedPartitionedTopic"; final String topicName = "persistent://prop/use/ns-abc/topic-" + key; final String subscriptionName = "my-failover-subscription-" + key; final String messagePredicate = "my-message-" + key + "-"; final int totalMessages = 10; final int numberOfPartitions = 3; admin.properties().createProperty("prop", new PropertyAdmin()); admin.persistentTopics().createPartitionedTopic(topicName, numberOfPartitions); // Special step to create partitioned topic // 1. producer connect Producer<byte[]> producer = pulsarClient.newProducer().topic(topicName) .messageRoutingMode(MessageRoutingMode.RoundRobinPartition).create(); // 2. Create consumer Consumer<byte[]> consumer1 = pulsarClient.newConsumer().topic(topicName).subscriptionName(subscriptionName) .receiverQueueSize(7).subscriptionType(SubscriptionType.Shared) .ackTimeout(ackTimeOutMillis, TimeUnit.MILLISECONDS).consumerName("Consumer-1").subscribe(); Consumer<byte[]> consumer2 = pulsarClient.newConsumer().topic(topicName).subscriptionName(subscriptionName) .receiverQueueSize(7).subscriptionType(SubscriptionType.Shared) .ackTimeout(ackTimeOutMillis, TimeUnit.MILLISECONDS).consumerName("Consumer-2").subscribe(); // 3. producer publish messages for (int i = 0; i < totalMessages; i++) { String message = messagePredicate + i; log.info("Message produced: " + message); producer.send(message.getBytes()); } // 4. Receive messages Message<byte[]> message1 = consumer1.receive(); Message<byte[]> message2 = consumer2.receive(); int messageCount1 = 0; int messageCount2 = 0; int ackCount1 = 0; int ackCount2 = 0; do { if (message1 != null) { log.info("Consumer1 received " + new String(message1.getData())); messageCount1 += 1; } if (message2 != null) { log.info("Consumer2 received " + new String(message2.getData())); messageCount2 += 1; consumer2.acknowledge(message2); ackCount2 += 1; } message1 = consumer1.receive(500, TimeUnit.MILLISECONDS); message2 = consumer2.receive(500, TimeUnit.MILLISECONDS); } while (message1 != null || message2 != null); log.info(key + " messageCount1 = " + messageCount1); log.info(key + " messageCount2 = " + messageCount2); log.info(key + " ackCount1 = " + ackCount1); log.info(key + " ackCount2 = " + ackCount2); assertEquals(messageCount1 + messageCount2, totalMessages); // 5. Check if Messages redelivered again // Since receive is a blocking call hoping that timeout will kick in log.info(key + " Timeout should be triggered now"); message1 = consumer1.receive(); messageCount1 = 0; do { if (message1 != null) { log.info("Consumer1 received " + new String(message1.getData())); messageCount1 += 1; consumer1.acknowledge(message1); ackCount1 += 1; } if (message2 != null) { log.info("Consumer2 received " + new String(message2.getData())); messageCount2 += 1; } message1 = consumer1.receive(500, TimeUnit.MILLISECONDS); message2 = consumer2.receive(500, TimeUnit.MILLISECONDS); } while (message1 != null || message2 != null); log.info(key + " messageCount1 = " + messageCount1); log.info(key + " messageCount2 = " + messageCount2); log.info(key + " ackCount1 = " + ackCount1); log.info(key + " ackCount2 = " + ackCount2); assertEquals(ackCount1 + messageCount2, totalMessages); } @Test public void testAckTimeoutMinValue() throws PulsarClientException { try { pulsarClient.newConsumer().ackTimeout(999, TimeUnit.MILLISECONDS); Assert.fail("Exception should have been thrown since the set timeout is less than min timeout."); } catch (Exception ex) { // Ok } } @Test(timeOut = testTimeout) public void testCheckUnAcknowledgedMessageTimer() throws PulsarClientException, InterruptedException { String key = "testCheckUnAcknowledgedMessageTimer"; final String topicName = "persistent://prop/use/ns-abc/topic-" + key; final String subscriptionName = "my-ex-subscription-" + key; final String messagePredicate = "my-message-" + key + "-"; final int totalMessages = 3; // 1. producer connect Producer<byte[]> producer = pulsarClient.newProducer().topic(topicName).create(); // 2. Create consumer ConsumerImpl<byte[]> consumer = (ConsumerImpl<byte[]>) pulsarClient.newConsumer().topic(topicName) .subscriptionName(subscriptionName).receiverQueueSize(7).subscriptionType(SubscriptionType.Shared) .ackTimeout(ackTimeOutMillis, TimeUnit.MILLISECONDS).subscribe(); // 3. producer publish messages for (int i = 0; i < totalMessages; i++) { String message = messagePredicate + i; log.info("Producer produced: " + message); producer.send(message.getBytes()); } Thread.sleep((long) (ackTimeOutMillis * 1.1)); for (int i = 0; i < totalMessages - 1; i++) { Message<byte[]> msg = consumer.receive(); consumer.acknowledge(msg); } assertEquals(consumer.getUnAckedMessageTracker().size(), 1); Message<byte[]> msg = consumer.receive(); consumer.acknowledge(msg); assertEquals(consumer.getUnAckedMessageTracker().size(), 0); Thread.sleep((long) (ackTimeOutMillis * 1.1)); assertEquals(consumer.getUnAckedMessageTracker().size(), 0); } }
apache-2.0
walterfan/pims4java
server/src/main/java/com/github/walterfan/kanban/dao/NoResultsFoundException.java
1493
package com.github.walterfan.kanban.dao; import org.springframework.dao.DataAccessException; import java.io.PrintStream; import java.io.PrintWriter; /** * Thrown if a record didnot exist by the search condition */ public class NoResultsFoundException extends DataAccessException { /** * DOCUMENT ME! */ private Throwable nestedThrowable = null; /** * Creates a new NoResultsFoundException object. * * @param msg DOCUMENT ME! */ public NoResultsFoundException(String msg) { super(msg); } /** * Creates a new NoResultsFoundException object. * * @param msg DOCUMENT ME! * @param nestedThrowable DOCUMENT ME! */ public NoResultsFoundException(String msg, Throwable nestedThrowable) { super(msg); this.nestedThrowable = nestedThrowable; } /** * DOCUMENT ME! */ public void printStackTrace() { super.printStackTrace(); if (nestedThrowable != null) { nestedThrowable.printStackTrace(); } } /** * DOCUMENT ME! * * @param ps DOCUMENT ME! */ public void printStackTrace(PrintStream ps) { super.printStackTrace(ps); if (nestedThrowable != null) { nestedThrowable.printStackTrace(ps); } } /** * DOCUMENT ME! * * @param pw DOCUMENT ME! */ public void printStackTrace(PrintWriter pw) { super.printStackTrace(pw); } }
apache-2.0
jpotts/alfresco-developer-series
webscripts/webscripts-tutorial/webscripts-tutorial-platform/src/main/resources/alfresco/extension/templates/webscripts/com/someco/ratings/rating.get.js
644
<import resource="classpath:alfresco/module/behavior-tutorial-platform/scripts/rating.js"> if (args.id == null || args.id.length == 0) { logger.log("ID arg not set"); status.code = 400; status.message = "Node ID has not been provided"; status.redirect = true; } else { logger.log("Getting current node"); var curNode = search.findNode("workspace://SpacesStore/" + args.id); if (curNode == null) { logger.log("Node not found"); status.code = 404; status.message = "No node found for id:" + args.id; status.redirect = true; } else { logger.log("Setting model rating data"); model.rating = getRating(curNode, args.user); } }
apache-2.0
jkingdon/ghilbert
js/proofstep.js
32283
// Javascript for displaying proof steps. Steps are organized into proof blocks. // by Paul Merrell, 2013 /** * Represents an s-expression. */ GH.sExpression = function(operator, begin, end, isString) { this.parent = null; this.operator = operator; this.operands = []; this.siblingIndex = null; // If the expression comes from a string. this.isString = isString; // Where the expression begins and ends within the textarea. this.begin = begin; this.end = end; // Set to true later, if the expression is a proven statement on the proof stack. this.isProven = false; }; GH.sExpression.prototype.appendOperand = function(operand) { operand.parent = this; operand.siblingIndex = this.operands.length; this.operands.push(operand); }; GH.sExpression.fromRaw = function(expression) { var isString = (GH.typeOf(expression) == 'string'); var operator = isString ? expression : expression[0]; var result = new GH.sExpression(operator, expression.beg, expression.end, isString); if (!isString) { for (var i = 1; i < expression.length; i++) { result.appendOperand(GH.sExpression.fromRaw(expression[i])); } } return result; }; // Create an s-expression for a number between 0 and 10. GH.sExpression.createDigit = function(num) { return new GH.sExpression(num.toString(), -1, -1, false); }; // Create an s-expression for a variable. GH.sExpression.createVariable = function(name) { return new GH.sExpression(name, -1, -1, true); }; GH.sExpression.createOperator = function(operator, operands) { var result = new GH.sExpression(operator, -1, -1, false); for (var i = 0; i < operands.length; i++) { result.appendOperand(operands[i]); } return result; }; GH.sExpression.prototype.getRoot = function() { var result = this; while(result.parent) { result = result.parent; } return result; }; GH.sExpression.fromString = function(str) { return GH.sExpression.fromRaw(GH.sExpression.stringToExpression(str)); }; GH.sExpression.stringToExpression = function(str) { var depth = 0; var starts = []; var ends = []; var start = null; var end = null; for (var i = 0; i < str.length; i++) { var c = str.charAt(i); if (c != ' ') { if ((start == null) && (depth == 1)) { start = i; } } if (c == '(') { depth++; } else if (c == ')') { if ((depth == 1) && (start != null)) { end = i; } depth--; } else if (c == ' ') { if ((depth == 1) && (start != null)) { end = i; } } if (end != null) { starts.push(start); ends.push(end); start = null; end = null; } } if (starts.length > 0) { var expressions = []; for (var i = 0; i < starts.length; i++) { expressions.push(GH.sExpression.stringToExpression(str.substring(starts[i], ends[i]))); } return expressions; } else { return str; } }; // Construct the expression from the operator and operands. GH.sExpression.prototype.getExpression = function() { if (this.isString) { return this.operator; } else { var expression = []; expression.push(this.operator); for (var i = 0; i < this.operands.length; i++) { expression.push(this.operands[i].getExpression()); } return expression; } }; GH.sExpression.prototype.copy = function() { return GH.sExpression.fromRaw(this.getExpression()); }; GH.sExpression.prototype.child = function () { if (this.operands.length > 1) { alert('Warning this expression has more than one child.'); } else if (this.operands.length == 0) { alert('Warning this expression has no children.'); } return this.operands[0]; }; GH.sExpression.prototype.left = function () { if (this.operands.length < 2) { alert('Warning this expression does not have a left side.'); } return this.operands[0]; }; GH.sExpression.prototype.right = function () { if (this.operands.length < 2) { alert('Warning this expression does not have a right side.'); } return this.operands[1]; }; GH.sExpression.prototype.replace = function () { if (this.operands.length < 2) { alert('Warning this expression does not have a right side.'); } return this.operands[1]; }; // Find all matches to sexp within this expression. GH.sExpression.prototype.findExp = function(sexp) { var result = []; if (this.equals(sexp)) { result.push(this); } for (var i = 0; i < this.operands.length; i++) { result = result.concat(this.operands[i].findExp(sexp)); } return result; }; GH.sExpression.stripParams = function(operator) { delete operator['beg']; delete operator['end']; return operator; }; // Returns true is the s-expressions are identical. GH.sExpression.prototype.equals = function(sexp) { var numOperands = this.operands.length; GH.sExpression.stripParams(this.operator); GH.sExpression.stripParams(sexp.operator); if (this.operator.length != sexp.operator.length) { return false; } for (var i = 0; i < this.operator.length; i++) { if (this.operator[i] != sexp.operator[i]) { return false; } } if ((numOperands != sexp.operands.length)) { return false; } for (var i = 0; i < numOperands; i++) { if (!this.operands[i].equals(sexp.operands[i])) { return false; } } return true; }; /** * Displays an s-expression. If the cursor is inside of the s-expression, it is highlighted. * If the cursor is touching a particular symbol, that symbol is further hightlighted. */ GH.sExpression.prototype.display = function(stack, indentation, cursorPosition) { var text = GH.sexptohtmlHighlighted(this.getExpression(), cursorPosition); var isHighlighted = this.begin <= cursorPosition && cursorPosition <= this.end; // For now comment out the highlighting. Add it back in when we get a better editor like ACE or CodeMirror. //var mouseOverFunc = 'GH.setSelectionRange(' + this.begin + ',' + this.end +')'; var mouseOverFunc = ''; stack.appendChild(GH.ProofStep.stepToHtml(text, indentation, isHighlighted, false, mouseOverFunc, '', '', '')); }; GH.sExpression.prototype.toString = function() { var result = []; result.push(this.operator); for (var i = 0; i < this.operands.length; i++) { result.push(this.operands[i].toString()); } result = result.join(' '); if (!this.isString) { result = '(' + result + ')'; } return result; }; GH.sExpression.prototype.getBeginning = function() { return this.begin; }; /** * Proof steps are rendered into blocks containing one or more steps. * The steps can be organized into tables. */ GH.ProofBlock = function(classes) { this.classes = classes; this.steps = []; this.tableList = []; }; // Render a proof block into html. GH.ProofBlock.prototype.display = function(stack, cursorPosition) { var blockElement = document.createElement("div"); blockElement.setAttribute('class', this.classes); this.addTables(blockElement, cursorPosition); stack.appendChild(blockElement); GH.ProofBlock.resizeTables(blockElement); }; // Enlarge the last column of each table so that each row spans the width of the block. GH.ProofBlock.resizeTables = function(block){ for (var i = 0; i < block.childElementCount; i++) { var table = block.children[i]; var lastCell = table.firstChild.lastChild; // The width is equal to the current width plus the difference between the block and the table width. var newWidth = block.offsetWidth - table.offsetWidth + parseInt(window.getComputedStyle(lastCell).width) - 20; lastCell.setAttribute('style', 'width: ' + newWidth); } }; /** * Add table elements to the block element. Every step is added to a table. The table list * contains groups of steps that are put into tables together. If there is no table list * for a step it is added into a one-line table. */ GH.ProofBlock.prototype.addTables = function(blockElement, cursorPosition) { var i = 0; while (i < this.steps.length) { var styled = false; for (var j = 0; (j < this.tableList.length) && !styled; j++) { if (this.tableList[j].begin == i) { this.addTable(this.tableList[j], blockElement, cursorPosition); i = this.tableList[j].end; styled = true; } } if (!styled) { this.addOneLineTable(i, blockElement, cursorPosition); i++; } } }; // Add in a table to a block. Add in the styling for the table if // it is present. Unstyled tables simply indent the hypotheses. GH.ProofBlock.prototype.addTable = function(table, blockElement, cursorPosition) { var tableElement = document.createElement("table"); tableElement.setAttribute('cellspacing', 0); var hasHighlightedStep = false; for (var i = table.begin; i < table.end; i++) { var step = this.steps[i]; hasHighlightedStep = hasHighlightedStep || (step.classes_.match(new RegExp(GH.ProofStep.HIGHLIGHTED_STEP_)) != null); if (table.styling) { var styleIndex = i - table.begin; step.expression_ = GH.RenderableProofStep.styleExpression(table.styling[styleIndex], step.expression_); } else { step.classes_ += ' unstyled'; } tableElement.appendChild(step.render(cursorPosition)); } // Do not include the table border if there aren't any steps outside the table. if (table.end - table.begin < this.steps.length) { tableElement.className += 'table-border'; if (!hasHighlightedStep) { // table-background is currently not used, but it might be later. tableElement.className += ' table-background'; } } blockElement.appendChild(tableElement); }; GH.ProofBlock.hideableOperators = ['<->', '=', '=_', '<', '<=']; // Consider putting -> in. // Render the proof step. Hide parts on the left-side of an expression that are identical in the previous // step. GH.ProofBlock.renderVisibleParts = function(prevStep, step, tableElement, cursorPosition) { var isHidden = false; if (prevStep != null) { var hideableOperators = GH.ProofBlock.hideableOperators; var sexp = step.expression_; var prevSexp = prevStep.expression_; var operator = String(sexp[0]); if (operator == String(prevSexp[0])) { var hideable = false; for (var i = 0; i < hideableOperators.length && !hideable; i++) { hideable = hideable || (operator == hideableOperators[i]); } if (hideable) { var prevLeft = GH.sExpression.fromRaw(prevSexp[1]); var left = GH.sExpression.fromRaw(sexp[1]); isHidden = left.equals(prevLeft) } } } if (isHidden) { var sexp = step.expression_; sexp[1] = ['htmlSpan', 'hidden', sexp[1]]; // Hide. tableElement.appendChild(step.render(cursorPosition)); sexp[1] = sexp[1][2]; // Revert the s-expression. } else { tableElement.appendChild(step.render(cursorPosition)); } }; // Add a one line table with no border or styling to it. GH.ProofBlock.prototype.addOneLineTable = function(i, blockElement, cursorPosition) { var tableElement = document.createElement("table"); tableElement.setAttribute('cellspacing', 0); tableElement.className = 'table-no-border'; var step = this.steps[i]; var notLast = (i < this.steps.length - 1); var prevStep = (i > 0) && notLast ? this.steps[i - 1] : null; step.classes_ += ' unstyled'; GH.ProofBlock.renderVisibleParts(prevStep, step, tableElement, cursorPosition); blockElement.appendChild(tableElement); }; // Stores information for styling a table within a block. GH.proofTable = function(styling, begin, end) { this.styling = styling; this.begin = begin; this.end = end; }; /** * This represents a hierarchy of proof steps. A proofHierarchy either contains a single * proof step or it contains a list of children that are proofHierarchies themselves. * If it has children, the children contains all the proof steps between a pair of <d> and * </d> tags. * - step: A single proof step or null. * - begin: The cursor position where the hierarchy begins. */ GH.ProofHierarchy = function(step, begin) { this.parent = null; this.step = step; this.children = []; // An array of proofHierarchies. if (step) { step.hierarchy = this; this.end = step.end; } else { this.end = 1e10; } this.begin = begin; this.siblingIndex = -1; }; GH.ProofHierarchy.prototype.appendChild = function(child) { child.siblingIndex = this.children.length; child.parent = this; this.children.push(child); if (child.begin < this.begin) { this.begin = child.begin; } }; GH.ProofHierarchy.prototype.removeChild = function(siblingIndex) { for (var i = siblingIndex + 1; i < this.children.length; i++) { this.children[i].siblingIndex--; } this.children.splice(siblingIndex, 1); }; // Find the highest position with the hierarchy that a statement is not the conclusion of. GH.ProofHierarchy.prototype.findPosition = function() { if (this.parent && (this.siblingIndex == this.parent.children.length - 1)) { return this.parent.findPosition(); } else { return this.parent; } }; // Return true, if the step at this part of the hierarchy is important at a particular cursor position. GH.ProofHierarchy.prototype.isImportant = function(cursorPosition) { var position = this.findPosition(); return (position.begin <= cursorPosition) && (cursorPosition <= position.end); }; // Returns the depth of the position. GH.ProofHierarchy.prototype.getDepth = function() { var position = this.findPosition(); var depth = 0; while(position.parent) { position = position.parent; depth++; } return depth; }; // Lower this proof hierarchy. It will acquire a new parent and become a grandchild of its current parent. GH.ProofHierarchy.prototype.reparent = function(newParent) { this.parent.removeChild(this.siblingIndex); newParent.appendChild(this); }; /** * Represents the input and output of each proof step. * name (string): The name of this proof step. * hypotheses (Array.<ProofStep>): An array of proof steps used as inputs to this step. * conclusion: (s-expression) An s-expression that is the result of this step. * begin (number): The cursor position of the beginning of this step. * end (number): The cursor position of the end of this step. * sExpressions (Array.<s-expression>): An array of s-expressions used to create this step. * isError: Whether the expression is signaling an error. * isThm: Whether this is a theorem "thm" and not an axiom "stmt". * depth: The depth of the proof step. Proof steps with a higher depth are less important and less visible. * styling: The way to style the statements. */ GH.ProofStep = function(name, hypotheses, conclusion, begin, end, sExpressions, isError, isThm, styling) { this.name_ = name; this.hypotheses = hypotheses; this.conclusion = conclusion; this.begin = begin; this.end = end; this.isError = isError; this.isThm = isThm; this.substitution = null; this.styling = styling ? styling.table : null; this.title = styling && styling.title ? styling.title : ''; this.hierarchy = null; this.sExpressions_ = []; for (var i = 0; i < sExpressions.length; i++) { this.sExpressions_.push(GH.sExpression.fromRaw(sExpressions[i][1])); } }; /** * Find the beginning of the proof step this includes the beginning of any hypotheses * that this step depends on. */ GH.ProofStep.prototype.getBeginning = function() { if (this.hypotheses.length > 0) { return this.hypotheses[0].getBeginning(); } else { if (this.sExpressions_.length > 0) { return this.sExpressions_[0].getBeginning(); } else { return this.begin; } } }; // Returns true, if the position is inside this proof step or its descendants. GH.ProofStep.prototype.isInsideBroad = function(position) { return ((this.getBeginning() <= position) && (position <= this.end)); }; // Returns true, if the position is inside this proof step. GH.ProofStep.prototype.isInsideNarrow = function(position) { return ((this.begin <= position) && (position <= this.end)) }; // Render the proof step name in HTML. GH.ProofStep.nameToHtml = function(name, title, isLink, isPrimary, isHypothesis) { if ((title == '') || (title === undefined)) { title = name; } var classes = 'proof-step-name'; //classes += (isHypothesis ? ' display-on-hover' : ''); classes += (isPrimary ? ' primary-step-name' : ''); if (isLink) { return '<a href="/edit' + url + '/' + name + '" class=\'' + classes + '\'>' + title + '</a>'; } else { return '<span class=\'' + classes + '\'>' + title + '</span>'; } }; // Html for adding a new cell to a table. GH.ProofStep.NEW_CELL = '</td><td>'; /** * Returns the proof step displayed as a set of blocks. * This is the main entry point for displaying the proof steps. */ GH.ProofStep.prototype.displayStack = function(stack, cursorPosition) { var blocks = this.display(false, cursorPosition); for (var i = 0; i < blocks.length; i++) { blocks[i].display(stack, cursorPosition); } }; GH.ProofStep.createBlock = function(isGrayed, blocks) { var classes = 'proof-block' + (blocks.length == 0 ? ' ' + GH.ProofStep.PRIMARY_BLOCK_ : '') + (isGrayed ? ' gray-block' : ''); var newBlock = new GH.ProofBlock(classes) return [newBlock]; }; /** * Returns an array of strings recursively displaying each proof step. * isGrayed: True if the proof-block is a gray color. The blocks alternate * between white and gray blocks. * cursorPosition: The cursor position in the text input box. */ GH.ProofStep.prototype.display = function(isGrayed, cursorPosition) { var lowestDepth = 1e10; var mostImportantHyp = null; for (var i = 0; i < this.hypotheses.length; i++) { var depth = this.hypotheses[i].hierarchy.getDepth(); if (depth < lowestDepth) { lowestDepth = depth; if (this.hypotheses[i].hierarchy.isImportant(cursorPosition)) { mostImportantHyp = this.hypotheses[i]; } else { mostImportantHyp = null; } } else if (depth == lowestDepth) { mostImportantHyp = null; // There can only be one most important hyp or none. } } var isExpanded = this.isInsideNarrow(cursorPosition); var highlightedIndex = -1; for (var i = 0; i < this.hypotheses.length; i++) { if ((this.hypotheses[i] != mostImportantHyp) && (this.hypotheses[i].isInsideBroad(cursorPosition))) { highlightedIndex = i; isExpanded = true; } } var visibleHypotheses; if (isExpanded) { visibleHypotheses = this.hypotheses; } else if (mostImportantHyp) { visibleHypotheses = [mostImportantHyp]; } else { visibleHypotheses = []; } var oneHyp = !!mostImportantHyp; var blocks = []; var displayedHyps = []; // Display a new block for the hypothesis that the cursor is inside of, but only if that hypothesis // is not the one important hypothesis, since a single important hypothesis should be not be separated // to the current block. var highlighted = []; for (var i = 0; i < this.hypotheses.length; i++) { if (i == highlightedIndex) { var newBlocks = this.hypotheses[i].display(!isGrayed, cursorPosition); blocks = blocks.concat(newBlocks); highlighted.push(true); } else { highlighted.push(false); } } for (var i = 0; i < visibleHypotheses.length; i++) { var blockOffset = highlighted[i] ? 1 : 0; var isIndented = (visibleHypotheses.length > 1) && (visibleHypotheses[i] != mostImportantHyp); var prevOutsideTable = oneHyp && isExpanded && (visibleHypotheses[i] == mostImportantHyp); displayedHyps.push(visibleHypotheses[i].displayStep(isIndented, cursorPosition, true, highlighted[i], blockOffset, prevOutsideTable)); } var newBlocks = []; // Add the hypotheses to an existing block if there is a most important hypotheses. if (mostImportantHyp) { newBlocks = mostImportantHyp.display(isGrayed, cursorPosition); } // Otherwise add the hypotheses to a new block. if (newBlocks.length == 0) { newBlocks = GH.ProofStep.createBlock(isGrayed, blocks); } var lastBlock = newBlocks[newBlocks.length - 1]; if (lastBlock.steps.length > 0) { // Remove the conclusion. It gets added as a displayedHyp. lastBlock.steps.pop(); } var oneHypSteps = lastBlock.steps.length; for (var i = 0; i < displayedHyps.length; i++) { lastBlock.steps.push(displayedHyps[i]); } blocks = blocks.concat(newBlocks); // Hook up the highlighted from the conclusion of a block to the step in the previous block. if (blocks.length > 1) { var steps = blocks[blocks.length - 2].steps; steps[steps.length - 1].setConclusionMouseOver(1, highlightedIndex + oneHypSteps); } // Add conclusion to the last block. lastBlock.steps.push(this.displayStep(false, cursorPosition, false, false, 0, false)); // Only add the styling when none of the unimportant hypotheses are hidden. var numBlockHypotheses = lastBlock.steps.length; var numTableHypotheses = numBlockHypotheses - oneHypSteps; if (isExpanded) { var begin = numBlockHypotheses - numTableHypotheses; var styling = (this.styling && (numTableHypotheses == this.styling.length)) ? this.styling : null; lastBlock.tableList.push(new GH.proofTable(styling, begin, numBlockHypotheses)); } return blocks; }; /** * Display just this step without recursion. */ GH.ProofStep.prototype.displayStep = function(isIndented, cursorPosition, isHypothesis, isHighlighted, blockOffset, prevOutsideTable) { var inStep = this.begin <= cursorPosition && cursorPosition <= this.end; var classes = ''; if (isIndented) { classes += ' ' + GH.ProofStep.INDENTED_STEP_; } if (this.Error_) { classes += ' error-in-step'; } if (isHighlighted) { classes += ' ' + GH.ProofStep.HIGHLIGHTED_STEP_; } var nameHtml = GH.ProofStep.nameToHtml(this.name_, this.title, this.isThm, inStep, isHypothesis); return new GH.RenderableProofStep(this.conclusion, classes, this.begin, this.end, inStep, prevOutsideTable, nameHtml, blockOffset); }; /** * Stores the data necessary to render a single line of the proof. */ GH.RenderableProofStep = function(expression, classes, begin, end, cursorInside, prevOutsideTable, nameHtml, blockOffset) { this.expression_ = expression; this.classes_ = classes; this.begin = begin; this.end = end; this.blockOffset_ = blockOffset; this.cursorInside = cursorInside; // True if the cursor is inside this step. this.nameHtml_ = nameHtml; this.hypIndex_ = null; this.prevOutsideTable = prevOutsideTable; }; /** * Add styling to an expression. The styling and the expression are both trees that we traverse * together. Whenever we encounter a node in the styling tree that has a "table" in it, we wrap * the expression there in a "table" node. */ GH.RenderableProofStep.styleExpression = function(styling, expression) { if (styling[0] == "table") { var styledExpression = GH.RenderableProofStep.styleExpression(styling[2], expression); return [styling[0], styling[1], styledExpression, styling[3]]; } else if (styling[0] == 'htmlSpan') { var styledExpression = GH.RenderableProofStep.styleExpression(styling[2], expression); return [styling[0], styling[1], styledExpression]; } else { if (typeof styling == 'string') { return expression; } else { var newExpression = [expression[0]]; for (var i = 1; i < styling.length; i++) { newExpression.push(GH.RenderableProofStep.styleExpression(styling[i], expression[i])); } } return newExpression; } }; /** * Sets the values needed for handling a mouseover of a conclusion. On mouseover, the conclusion * gets highlighted where it appears as a hypothesis. * blockOffset: The number of blocks to traverse down to reach the block where the conclusion * appears as a hypothesis. * hypIndex: An index describing which hypotheses corresponds to the conclusion. */ GH.RenderableProofStep.prototype.setConclusionMouseOver = function(blockOffset, hypIndex) { this.blockOffset_ = blockOffset; this.hypIndex_ = hypIndex; }; // Render the proof step into HTML. GH.RenderableProofStep.prototype.render = function(cursorPosition) { var mouseOverFunc; if (this.hypIndex_ != null) { mouseOverFunc = 'GH.ProofStep.handleConclusionMouseOver(' + this.begin + ',' + this.end + ', ' + this.blockOffset_ + ', ' + this.hypIndex_ + ', this)'; } else { mouseOverFunc = 'GH.ProofStep.handleMouseOver(' + this.begin + ',' + this.end + ', ' + this.blockOffset_ + ', ' + this.prevOutsideTable + ', this)'; } var mouseOutFunc = 'GH.ProofStep.handleMouseOut()'; var clickFunc = 'GH.ProofStep.handleClick(' + this.begin + ',' + this.end +', ' + this.cursorInside + ')'; var text = GH.sexptohtmlHighlighted(this.expression_, cursorPosition); return GH.ProofStep.stepToHtml(text, this.classes_, mouseOverFunc, mouseOutFunc, clickFunc, this.nameHtml_); }; // Display a proof step. // text: The text inside the step. // classes: The CSS classes applied to this step. // mouseOverFunc: The function to call on mouseover. // mouseOutFunc: The function to call on mouseout. // clickFunc: The function to call on a mouse click. // name: The name of the proofstep. GH.ProofStep.stepToHtml = function(text, classes, mouseOverFunc, mouseOutFunc, clickFunc, name) { var row = document.createElement("tr"); row.setAttribute('class', 'proof-step-div ' + classes); row.setAttribute('onmouseover', mouseOverFunc); row.setAttribute('onmouseout', mouseOutFunc); row.setAttribute('onclick', clickFunc); // Split the text using the html tags into the cells of a table. var cellTexts = []; var index = text.indexOf(GH.ProofStep.NEW_CELL); var newCellLength = GH.ProofStep.NEW_CELL.length; while(index > -1) { cellTexts.push(text.substring(0, index)); text = text.substring(index + newCellLength, text.length); index = text.indexOf(GH.ProofStep.NEW_CELL); } cellTexts.push(text); // Add the table cells into a row of the table. for (var i = 0; i < cellTexts.length; i++) { var cell = document.createElement("td"); var cellText = cellTexts[i]; var classname = ''; // Add classes for the first and last column. // Add the name of the step onto the last column. if (i == 0) { classname = 'first-column'; } cell.setAttribute('class', classname); cell.innerHTML = cellText; row.appendChild(cell); } var cell = document.createElement("td"); cell.setAttribute('class', 'last-column'); cell.innerHTML = name; row.appendChild(cell); return row; }; // Get the previous step. If it has no previous siblings, check its previous cousin. GH.ProofStep.getPreviousStep = function(step) { if (step.previousElementSibling) { return step.previousElementSibling; } else { var result = step.parentElement; result = result.previousElementSibling; if (!result) { return null; } else { return result.lastChild; } } }; // Highlight in orange this proof step and any steps it directly depends on. GH.ProofStep.orangeStep_ = function(prevOutsideTable, hoveredStep) { var step = hoveredStep; var block = step.parentElement.parentElement; var orangeSteps = [[step]]; var numOrangeSteps = 1; if (!GH.ProofStep.hasClass_(step, GH.ProofStep.INDENTED_STEP_)) { var splitGroup; if (prevOutsideTable) { // Grab the first step above the table. splitGroup = (step.parentElement.firstChild != step); step = step.parentElement.previousElementSibling && step.parentElement.previousElementSibling.lastChild; } else { step = GH.ProofStep.getPreviousStep(step); splitGroup = false; } var done = false; while (step && !done) { if (splitGroup) { orangeSteps.push([step]); splitGroups = false; } else { orangeSteps[orangeSteps.length - 1].push(step); } numOrangeSteps++; done = done || (!GH.ProofStep.hasClass_(step, GH.ProofStep.INDENTED_STEP_)); step = GH.ProofStep.getPreviousStep(step); } } // If all the steps in a block or a table are orange then orange the whole thing rather than the individual steps. var numBlockSteps = GH.ProofStep.getStepElements(block).length; if (numOrangeSteps == numBlockSteps) { GH.ProofStep.addClass_(block, GH.ProofStep.ORANGE_BLOCK_); } else if ((hoveredStep.parentElement.className.match(/table-border/) != null) && (hoveredStep == hoveredStep.parentElement.lastChild)) { GH.ProofStep.addClass_(hoveredStep.parentElement, 'orange-table'); } else { for (var j = 0; j < orangeSteps.length; j++) { for (var i = 0; i < orangeSteps[j].length; i++) { var orangeStep = orangeSteps[j][i]; if (i != 0) { GH.ProofStep.addClass_(orangeStep, GH.ProofStep.OPEN_BOTTOM_); } if (i != orangeSteps[j].length - 1) { GH.ProofStep.addClass_(orangeStep, GH.ProofStep.OPEN_TOP_); } GH.ProofStep.addClass_(orangeStep, GH.ProofStep.ORANGE_STEP_); } } } }; GH.ProofStep.findCorrespondingBlock_ = function(step, blockOffset) { var correspondingBlock = null; if (blockOffset) { correspondingBlock = step.parentElement.parentElement; if (blockOffset > 0) { for (var i = 0; i < blockOffset; i++) { correspondingBlock = correspondingBlock.previousSibling; } } else { for (var i = 0; i < -blockOffset; i++) { correspondingBlock = correspondingBlock.nextSibling; } } } return correspondingBlock; }; GH.ProofStep.handleMouseOver = function(start, end, blockOffset, prevOutsideTable, hoveredStep) { GH.ProofStep.orangeStep_(prevOutsideTable, hoveredStep); // For now comment out the highlighting. Add it back in when we get a better editor like ACE or CodeMirror. //GH.setSelectionRange(start, end); var highlightBlock = GH.ProofStep.findCorrespondingBlock_(hoveredStep, blockOffset); if (highlightBlock) { if (!GH.ProofStep.hasClass_(highlightBlock, GH.ProofStep.ORANGE_BLOCK_)) { GH.ProofStep.addClass_(highlightBlock, GH.ProofStep.ORANGE_BLOCK_); } } }; GH.ProofStep.getStepElements = function(blockElement) { var steps = []; for (var j = 0; j < blockElement.childElementCount; j++) { var table = blockElement.children[j]; for (var k = 0; k < table.childElementCount; k++) { steps.push(table.children[k]); } } return steps; }; // When a conclusion of a block is moused over, this highlights the same statement as a hypothesis // in the previous block. GH.ProofStep.handleConclusionMouseOver = function(start, end, blockOffset, hypIndex, hoveredStep) { GH.ProofStep.handleMouseOver(start, end, 0, false, hoveredStep); var highlightBlock = GH.ProofStep.findCorrespondingBlock_(hoveredStep, -blockOffset); if (highlightBlock) { var steps = GH.ProofStep.getStepElements(highlightBlock); GH.ProofStep.addClass_(steps[hypIndex], GH.ProofStep.ORANGE_STEP_); } }; // Returns true if an element has a particular class. GH.ProofStep.hasClass_ = function(element, className) { return element.className.match(new RegExp(className)); }; // Add a class to an element. GH.ProofStep.addClass_ = function(element, className) { if (!GH.ProofStep.hasClass_(element, className)) { element.className += ' ' + className; } }; // Remove a class from an element. GH.ProofStep.removeClass_ = function(element, className) { element.className = element.className.replace(new RegExp(' ' + className), ''); }; // Handle a mouse out event. Remove all the highlighting that was added in the mouseover handling. GH.ProofStep.handleMouseOut = function() { var stack = document.getElementById('stack'); for (var i = 0; i < stack.childElementCount; i++) { var block = stack.children[i]; GH.ProofStep.removeClass_(block, GH.ProofStep.ORANGE_BLOCK_); for (var j = 0; j < block.childElementCount; j++) { var table = block.children[j]; GH.ProofStep.removeClass_(table, 'orange-table'); for (var k = 0; k < table.childElementCount; k++) { var step = table.children[k]; GH.ProofStep.removeClass_(step, GH.ProofStep.ORANGE_STEP_); GH.ProofStep.removeClass_(step, GH.ProofStep.OPEN_TOP_); GH.ProofStep.removeClass_(step, GH.ProofStep.OPEN_BOTTOM_); } } } }; // Handle clicking on a proof step. GH.ProofStep.handleClick = function(start, end, incrementClicks) { GH.setSelectionRange(start, end); window.direct.update(true); }; /** * Class name of the highlighted step. */ GH.ProofStep.HIGHLIGHTED_STEP_ = 'highlighted-step'; /** * Class name of the indented step in a proof block. The hypotheses are indented. */ GH.ProofStep.INDENTED_STEP_ = 'indented-step'; /** * Class name of the highlighted block. */ GH.ProofStep.ORANGE_BLOCK_ = 'orange-block'; /** * Class name of the primary block. */ GH.ProofStep.PRIMARY_BLOCK_ = 'primary-block'; /** * Class name to highlight a step in orange. */ GH.ProofStep.ORANGE_STEP_ = 'orange-step'; /** * Class name that indicates that the border is open at the bottom. */ GH.ProofStep.OPEN_BOTTOM_ = 'open-bottom'; /** * Class name that indicates that the border is open at the top. */ GH.ProofStep.OPEN_TOP_ = 'open-top';
apache-2.0
desruisseaux/sis
core/sis-referencing/src/main/java/org/apache/sis/internal/jaxb/referencing/CS_PolarCS.java
2993
/* * 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.internal.jaxb.referencing; import javax.xml.bind.annotation.XmlElement; import org.opengis.referencing.cs.PolarCS; import org.apache.sis.referencing.cs.DefaultPolarCS; import org.apache.sis.internal.jaxb.gco.PropertyType; /** * JAXB adapter mapping implementing class to the GeoAPI interface. See * package documentation for more information about JAXB and interface. * * @author Martin Desruisseaux (Geomatys) * @since 0.4 * @version 0.4 * @module */ public final class CS_PolarCS extends PropertyType<CS_PolarCS, PolarCS> { /** * Empty constructor for JAXB only. */ public CS_PolarCS() { } /** * Returns the GeoAPI interface which is bound by this adapter. * This method is indirectly invoked by the private constructor * below, so it shall not depend on the state of this object. * * @return {@code PolarCS.class} */ @Override protected Class<PolarCS> getBoundType() { return PolarCS.class; } /** * Constructor for the {@link #wrap} method only. */ private CS_PolarCS(final PolarCS cs) { super(cs); } /** * Invoked by {@link PropertyType} at marshalling time for wrapping the given value * in a {@code <gml:PolarCS>} XML element. * * @param cs The element to marshall. * @return A {@code PropertyType} wrapping the given the element. */ @Override protected CS_PolarCS wrap(final PolarCS cs) { return new CS_PolarCS(cs); } /** * Invoked by JAXB at marshalling time for getting the actual element to write * inside the {@code <gml:PolarCS>} XML element. * This is the value or a copy of the value given in argument to the {@code wrap} method. * * @return The element to be marshalled. */ @XmlElement(name = "PolarCS") public DefaultPolarCS getElement() { return DefaultPolarCS.castOrCopy(metadata); } /** * Invoked by JAXB at unmarshalling time for storing the result temporarily. * * @param cs The unmarshalled element. */ public void setElement(final DefaultPolarCS cs) { metadata = cs; } }
apache-2.0