code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Module: Rake::Win32</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<link rel="stylesheet" href="../.././rdoc-style.css" type="text/css" media="screen" />
<script type="text/javascript">
// <![CDATA[
function popupCode( url ) {
window.open(url, "Code", "resizable=yes,scrollbars=yes,toolbar=no,status=no,height=150,width=400")
}
function toggleCode( id ) {
if ( document.getElementById )
elem = document.getElementById( id );
else if ( document.all )
elem = eval( "document.all." + id );
else
return false;
elemStyle = elem.style;
if ( elemStyle.display != "block" ) {
elemStyle.display = "block"
} else {
elemStyle.display = "none"
}
return true;
}
// Make codeblocks hidden by default
document.writeln( "<style type=\"text/css\">div.method-source-code { display: none }</style>" )
// ]]>
</script>
</head>
<body>
<div id="classHeader">
<table class="header-table">
<tr class="top-aligned-row">
<td><strong>Module</strong></td>
<td class="class-name-in-header">Rake::Win32</td>
</tr>
<tr class="top-aligned-row">
<td><strong>In:</strong></td>
<td>
<a href="../../files/lib/rake/win32_rb.html">
lib/rake/win32.rb
</a>
<br />
</td>
</tr>
</table>
</div>
<!-- banner header -->
<div id="bodyContent">
<div id="contextContent">
<div id="description">
<p>
Win 32 interface methods for Rake. Windows specific functionality will be
placed here to collect that knowledge in one spot.
</p>
</div>
</div>
<div id="method-list">
<h3 class="section-bar">Methods</h3>
<div class="name-list">
<a href="#M000705">normalize</a>
<a href="#M000704">rake_system</a>
<a href="#M000703">windows?</a>
</div>
</div>
</div>
<!-- if includes -->
<div id="section">
<div id="class-list">
<h3 class="section-bar">Classes and Modules</h3>
Class <a href="Win32/Win32HomeError.html" class="link">Rake::Win32::Win32HomeError</a><br />
</div>
<!-- if method_list -->
<div id="methods">
<h3 class="section-bar">Public Class methods</h3>
<div id="method-M000705" class="method-detail">
<a name="M000705"></a>
<div class="method-heading">
<a href="#M000705" class="method-signature">
<span class="method-name">normalize</span><span class="method-args">(path)</span>
</a>
</div>
<div class="method-description">
<p>
Normalize a win32 path so that the slashes are all forward slashes.
</p>
<p><a class="source-toggle" href="#"
onclick="toggleCode('M000705-source');return false;">[Source]</a></p>
<div class="method-source-code" id="M000705-source">
<pre>
<span class="ruby-comment cmt"># File lib/rake/win32.rb, line 48</span>
48: <span class="ruby-keyword kw">def</span> <span class="ruby-identifier">normalize</span>(<span class="ruby-identifier">path</span>)
49: <span class="ruby-identifier">path</span>.<span class="ruby-identifier">gsub</span>(<span class="ruby-regexp re">/\\/</span>, <span class="ruby-value str">'/'</span>)
50: <span class="ruby-keyword kw">end</span>
</pre>
</div>
</div>
</div>
<div id="method-M000704" class="method-detail">
<a name="M000704"></a>
<div class="method-heading">
<a href="#M000704" class="method-signature">
<span class="method-name">rake_system</span><span class="method-args">(*cmd)</span>
</a>
</div>
<div class="method-description">
<p>
Run a command line on windows.
</p>
<p><a class="source-toggle" href="#"
onclick="toggleCode('M000704-source');return false;">[Source]</a></p>
<div class="method-source-code" id="M000704-source">
<pre>
<span class="ruby-comment cmt"># File lib/rake/win32.rb, line 19</span>
19: <span class="ruby-keyword kw">def</span> <span class="ruby-identifier">rake_system</span>(<span class="ruby-operator">*</span><span class="ruby-identifier">cmd</span>)
20: <span class="ruby-keyword kw">if</span> <span class="ruby-identifier">cmd</span>.<span class="ruby-identifier">size</span> <span class="ruby-operator">==</span> <span class="ruby-value">1</span>
21: <span class="ruby-identifier">system</span>(<span class="ruby-node">"call #{cmd}"</span>)
22: <span class="ruby-keyword kw">else</span>
23: <span class="ruby-identifier">system</span>(<span class="ruby-operator">*</span><span class="ruby-identifier">cmd</span>)
24: <span class="ruby-keyword kw">end</span>
25: <span class="ruby-keyword kw">end</span>
</pre>
</div>
</div>
</div>
<div id="method-M000703" class="method-detail">
<a name="M000703"></a>
<div class="method-heading">
<a href="#M000703" class="method-signature">
<span class="method-name">windows?</span><span class="method-args">()</span>
</a>
</div>
<div class="method-description">
<p>
True if running on a windows system.
</p>
<p><a class="source-toggle" href="#"
onclick="toggleCode('M000703-source');return false;">[Source]</a></p>
<div class="method-source-code" id="M000703-source">
<pre>
<span class="ruby-comment cmt"># File lib/rake/win32.rb, line 14</span>
14: <span class="ruby-keyword kw">def</span> <span class="ruby-identifier">windows?</span>
15: <span class="ruby-constant">Config</span><span class="ruby-operator">::</span><span class="ruby-constant">CONFIG</span>[<span class="ruby-value str">'host_os'</span>] <span class="ruby-operator">=~</span> <span class="ruby-regexp re">/mswin/</span>
16: <span class="ruby-keyword kw">end</span>
</pre>
</div>
</div>
</div>
</div>
</div>
<div id="validator-badges">
<p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p>
</div>
</body>
</html>
|
google-code/android-scripting
|
jruby/src/lib/ruby/gems/1.8/doc/rake-0.8.3/rdoc/classes/Rake/Win32.html
|
HTML
|
apache-2.0
| 6,679
|
module.exports = function(w)
{
var global = require('ui/common/globals');
w.barImage='images/iPhone_Nav_Bar_Bkgrd_With_Black.png';
// This is where I am going put the with all the results.
var overview = Ti.UI.createView({
width: Ti.UI.FILL,
height: Ti.UI.SIZE,
layout: 'vertical',
top: 0
});
// Creates back button
var back = Ti.UI.createButton({ title: "Back" });
back.addEventListener("click", function()
{
w.close({animated:true});
});
w.setLeftNavButton(back);
// Creates top label
var top_label = Ti.UI.createLabel({
text: 'Settings',
color: 'white',
font:{
fontFamily:'Helvetica Neue',
fontSize:18,
fontWeight:'Bold'
},
textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER,
width: Ti.UI.FILL,
height: 40,
top:0,
backgroundColor: global.colors.dark,
});
w.add(top_label)
var logout_button = Ti.UI.createButton({
top: 60,
width: Ti.UI.FILL,
height: 42,
left: 10,
right: 10,
backgroundColor: global.colors.dark,
backgroundImage:'none',
color: 'white',
font:{
fontFamily:'Helvetica Neue',
fontSize:18,
},
borderRadius: 5,
title: 'Logout'
});
overview.add(logout_button);
logout_button.addEventListener('click', function(e){
global.api.logout(function(data){
Ti.App.fireEvent('user_logout', {});
});
//alert('You have successfully logged out');
});
// add overview to the window.
w.add(overview);
}
//*/
|
GladiusMattius/WineApp
|
Resources/ui/common/settings.js
|
JavaScript
|
apache-2.0
| 1,543
|
/*
* Copyright 2008-2011 Nokia Siemens Networks Oyj
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package hudson.plugins.robot;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.util.ChartUtil;
import java.io.IOException;
import java.util.Calendar;
import javax.servlet.ServletException;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
public class RobotProjectAction extends AbstractRobotAction {
private AbstractProject<?, ?> project;
/**
* Create new Robot project action
* @param project Project which this action will be applied to
*/
public RobotProjectAction(AbstractProject<?, ?> project) {
this.project = project;
}
/**
* Get associated project.
* @return
*/
public AbstractProject<?, ?> getProject() {
return project;
}
/**
* Returns true if there are any builds in the associated project.
* @return
*/
public boolean isDisplayGraph() {
if (getLastBuildAction() != null)
return true;
return false;
}
/**
* Return the action of last build associated with robot
* @return null if action not found or no build
*/
public RobotBuildAction getLastBuildAction(){
AbstractBuild<?, ?> lastBuild = getLastBuildWithRobot();
if(lastBuild != null)
return lastBuild.getAction(RobotBuildAction.class);
else return null;
}
/**
* Return robot trend graph in the request.
* @param req
* @param rsp
* @throws IOException
* @throws ServletException
*/
public void doGraph(StaplerRequest req, StaplerResponse rsp)
throws IOException, ServletException {
if (ChartUtil.awtProblemCause != null) {
rsp.sendRedirect2(req.getContextPath() + "/images/headless.png");
return;
}
Calendar t = project.getLastCompletedBuild().getTimestamp();
if (req.checkIfModified(t, rsp))
return;
AbstractBuild<?,?> lastBuild = getLastBuildWithRobot();
rsp.sendRedirect2("../" + lastBuild.getNumber() + "/" + getUrlName() + "/graph");
}
/**
* Show Robot html report of the latest build. If no builds are associated with Robot, returns info page.
* @param req
* @param rsp
* @throws IOException
*/
public void doIndex(StaplerRequest req, StaplerResponse rsp)
throws IOException {
AbstractBuild<?,?> lastBuild = getLastBuildWithRobot();
if (lastBuild == null) {
rsp.sendRedirect2("nodata");
} else {
int buildNumber = lastBuild.getNumber();
rsp.sendRedirect2("../" + buildNumber + "/" + getUrlName());
}
}
private AbstractBuild<?, ?> getLastBuildWithRobot() {
AbstractBuild<?, ?> lastBuild = (AbstractBuild<?, ?>) project
.getLastBuild();
while (lastBuild != null
&& lastBuild.getAction(RobotBuildAction.class) == null) {
lastBuild = lastBuild.getPreviousBuild();
}
return lastBuild;
}
}
|
imikemo/robot-plugin
|
src/main/java/hudson/plugins/robot/RobotProjectAction.java
|
Java
|
apache-2.0
| 3,305
|
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/compute/v1/compute.proto
package com.google.cloud.compute.v1;
public interface ShareSettingsProjectConfigOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.cloud.compute.v1.ShareSettingsProjectConfig)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* The project ID, should be same as the key of this project config in the parent map.
* </pre>
*
* <code>optional string project_id = 177513473;</code>
*
* @return Whether the projectId field is set.
*/
boolean hasProjectId();
/**
*
*
* <pre>
* The project ID, should be same as the key of this project config in the parent map.
* </pre>
*
* <code>optional string project_id = 177513473;</code>
*
* @return The projectId.
*/
java.lang.String getProjectId();
/**
*
*
* <pre>
* The project ID, should be same as the key of this project config in the parent map.
* </pre>
*
* <code>optional string project_id = 177513473;</code>
*
* @return The bytes for projectId.
*/
com.google.protobuf.ByteString getProjectIdBytes();
}
|
googleapis/java-compute
|
proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/ShareSettingsProjectConfigOrBuilder.java
|
Java
|
apache-2.0
| 1,792
|
package com.ztemt.test.platform.model;
import com.ztemt.test.platform.data.TextData;
import com.ztemt.test.platform.data.TextDataFactory;
import android.os.Parcel;
@SuppressWarnings("serial")
public class SystemTest extends Task {
/** 测试名称字段 */
public static final String NAME = "name";
/** 测试所需模块名称字段 */
public static final String MODULE = "module";
/** 测试参数字段 */
public static final String EXTRAS = "extras";
/** 测试是否可等待字段 ,如普通APK需要等待测试完成*/
public static final String WAITABLE = "waitable";
/** 测试进程号字段,用户结束进程 */
public static final String PID = "pid";
private String mName;
private String mModule;
private String mExtras;
private boolean mWaitable;
private int mPid;
public SystemTest() {
super(TYPE_SYSTEM_TEST);
}
public SystemTest(Parcel in) {
super(in);
mName = in.readString();
mModule = in.readString();
mExtras = in.readString();
mWaitable = in.readInt() == 1;
mPid = in.readInt();
}
public SystemTest(TextData data) {
super(data);
mName = data.getString(NAME);
mModule = data.getString(MODULE);
mExtras = data.getString(EXTRAS);
mWaitable = data.getBoolean(WAITABLE);
mPid = data.getInt(PID);
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
public String getModule() {
return mModule;
}
public void setModule(String module) {
mModule = module;
}
public String getExtras() {
return mExtras;
}
public void setExtras(String extras) {
mExtras = extras;
}
public boolean isWaitable() {
return mWaitable;
}
public void setWaitable(boolean waitable) {
mWaitable = waitable;
}
public int getPid() {
return mPid;
}
public void setPid(int pid) {
mPid = pid;
}
@Override
public String toString() {
TextData data = TextDataFactory.create(super.toString());
data.putString(NAME, mName);
data.putString(MODULE, mModule);
data.putString(EXTRAS, mExtras);
data.putBoolean(WAITABLE, mWaitable);
data.putInt(PID, mPid);
return data.toString();
}
}
|
doctang/TestPlatform
|
TestPlatform/src/com/ztemt/test/platform/model/SystemTest.java
|
Java
|
apache-2.0
| 2,445
|
# AUTOGENERATED FILE
FROM balenalib/qemux86-64-fedora:35-build
# http://bugs.python.org/issue19846
# > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK.
ENV LANG C.UTF-8
RUN dnf install -y \
python3-pip \
python3-dbus \
&& dnf clean all
# install "virtualenv", since the vast majority of users of this image will want it
RUN pip3 install -U --no-cache-dir --ignore-installed pip setuptools \
&& pip3 install --no-cache-dir virtualenv
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'As of January 1st, 2020, Python 2 was end-of-life, we will change the latest tag for Balenalib Python base image to Python 3.x and drop support for Python 2 soon. So after 1st July, 2020, all the balenalib Python latest tag will point to the latest Python 3 version and no changes, or fixes will be made to balenalib Python 2 base image. If you are using Python 2 for your application, please upgrade to Python 3 before 1st July.' > /.balena/messages/python-deprecation-warning
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@python.sh" \
&& echo "Running test-stack@python" \
&& chmod +x test-stack@python.sh \
&& bash test-stack@python.sh \
&& rm -rf test-stack@python.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: Intel 64-bit (x86-64) \nOS: Fedora 35 \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.6.15, Pip v21.3.1, Setuptools v60.5.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo $'#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh
|
resin-io-library/base-images
|
balena-base-images/python/qemux86-64/fedora/35/3.6.15/build/Dockerfile
|
Dockerfile
|
apache-2.0
| 2,453
|
codility
========
Java solutions with 100% score.
|
1azyman/codility
|
README.md
|
Markdown
|
apache-2.0
| 51
|
package de.sw4j.blog.webservices.web;
import de.sw4j.blog.webservices.calculator.Addition;
import de.sw4j.blog.webservices.calculator.CalculatorPortType;
import de.sw4j.blog.webservices.calculator.DivByZeroMsg;
import de.sw4j.blog.webservices.calculator.Division;
import de.sw4j.blog.webservices.calculator.Multiplication;
import de.sw4j.blog.webservices.calculator.Subtraction;
import java.math.BigInteger;
import javax.jws.WebService;
/**
*
* @author Uwe Plonus <uwe.plonus@sw4j.org>
*/
@WebService(endpointInterface="de.sw4j.blog.webservices.calculator.CalculatorPortType",
serviceName="CalculatorService",
portName="CalculatorPort",
targetNamespace="http://blog.sw4j.de/webservices/calculator")
public class CalculatorService implements CalculatorPortType {
@Override
public BigInteger add(Addition operands) {
BigInteger result = BigInteger.ZERO;
for (BigInteger operand: operands.getAddend()) {
result = result.add(operand);
}
return result;
}
@Override
public BigInteger sub(Subtraction operands) {
BigInteger result = operands.getMinuend();
result = result.subtract(operands.getSubtrahend());
return result;
}
@Override
public BigInteger mul(Multiplication operands) {
BigInteger result = operands.getMultiplicand();
result = result.multiply(operands.getMultiplier());
return result;
}
@Override
public BigInteger div(Division operands) throws DivByZeroMsg {
BigInteger result = operands.getDividend();
try {
result = result.divide(operands.getDivisor());
} catch (ArithmeticException aex) {
throw new DivByZeroMsg("Division by zero.", null, aex);
}
return result;
}
}
|
uweplonus/webservices-blog
|
servlet/src/main/java/de/sw4j/blog/webservices/web/CalculatorService.java
|
Java
|
apache-2.0
| 1,703
|
import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { Floss } from '../models/floss';
import { DB } from '../models/db';
@Injectable()
export class CatalogService {
private flossUrl = 'app/floss'; // URL to web api
constructor(private http: Http) { }
getCatalog(): Promise<Floss[]> {
return Promise.resolve(DB.db);
}
getFloss(id: number): Promise<Floss> {
return this.getCatalog()
.then(catalog => catalog.find(floss => floss.dmc === id));
}
deleteFloss(floss: Floss, group : string): void {
var my : Floss[] = this.load(group);
if(!my){
my = [];
}
let newArr : Floss[] = my.filter(value => value.dmc != floss.dmc);
console.log(newArr);
this.store(group, newArr);
}
addFlossTo(floss: Floss, group: string) : void{
var collection : Floss[] = this.load(group);
if(!collection){
collection = [];
}
let found : Floss = collection.find(value => value.dmc === floss.dmc);
if(found)
return;
console.log(collection);
collection.push(floss);
this.store(group, collection);
}
isFlossIn(floss: Floss, group: string) : boolean {
var collection : Floss[] = this.load(group);
if(!collection){
collection = [];
}
let found : Floss = collection.find(value => value.dmc === floss.dmc);
return found ? true : false;
}
store(name: string, data: any): void {
let localData: any = localStorage.getItem('sara');
if (localData) {
localData = JSON.parse(localData);
} else {
localData = {};
}
localData[name] = data;
localStorage.setItem('sara', JSON.stringify(localData))
}
load(name: string): any {
let data: any = JSON.parse(localStorage.getItem('sara'));
if (!data) {
return undefined;
}
if (name) {
if (data[name]) {
return data[name];
} else {
return undefined;
}
}
return data;
}
}
|
paoloantinori/sara
|
app/services/catalog.service.ts
|
TypeScript
|
apache-2.0
| 1,983
|
/*
* Copyright (c) 2016 Yahoo Inc.
* Licensed under the terms of the Apache version 2.0 license.
* See LICENSE file for terms.
*/
package com.yahoo.yqlplus.engine.internal.bytecode.types.gambit;
import com.yahoo.yqlplus.engine.internal.bytecode.ASMClassSource;
import com.yahoo.yqlplus.engine.internal.bytecode.ReturnCode;
import com.yahoo.yqlplus.engine.internal.bytecode.UnitGenerator;
import com.yahoo.yqlplus.engine.internal.compiler.MethodGenerator;
import com.yahoo.yqlplus.engine.internal.plan.types.BytecodeExpression;
import com.yahoo.yqlplus.engine.internal.plan.types.TypeWidget;
import com.yahoo.yqlplus.engine.internal.plan.types.base.BytecodeCastExpression;
public class ByteInvocableBuilder extends ExpressionHandler implements InvocableBuilder {
private MethodGenerator generator;
private UnitGenerator unit;
static class InvocableUnit extends UnitGenerator {
InvocableUnit(String name, ASMClassSource environment) {
super(name, environment);
}
}
public ByteInvocableBuilder(ASMClassSource source) {
super(source);
this.unit = new InvocableUnit("invocable_" + source.generateUniqueElement(), source);
this.generator = unit.createStaticMethod("invoke");
// this isn't going to work when child expressions use things from outer scopes
body = generator.block();
}
@Override
public BytecodeExpression addArgument(String name, TypeWidget type) {
return generator.addArgument(name, type).read();
}
@Override
public Invocable complete(BytecodeExpression result) {
BytecodeExpression expr = result;
generator.setReturnType(expr.getType());
body.add(new BytecodeCastExpression(generator.getReturnType(), expr));
body.add(new ReturnCode(generator.getReturnType()));
return generator.createInvocable();
}
}
|
slolars/yql-plus
|
yqlplus_engine/src/main/java/com/yahoo/yqlplus/engine/internal/bytecode/types/gambit/ByteInvocableBuilder.java
|
Java
|
apache-2.0
| 1,887
|
# AUTOGENERATED FILE
FROM balenalib/orangepi-plus2-alpine:3.13-build
ENV GO_VERSION 1.14.14
# set up nsswitch.conf for Go's "netgo" implementation
# - https://github.com/golang/go/blob/go1.9.1/src/net/conf.go#L194-L275
# - docker run --rm debian:stretch grep '^hosts:' /etc/nsswitch.conf
RUN [ ! -e /etc/nsswitch.conf ] && echo 'hosts: files dns' > /etc/nsswitch.conf
RUN mkdir -p /usr/local/go \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/golang/v$GO_VERSION/go$GO_VERSION.linux-alpine-armv7hf.tar.gz" \
&& echo "e692f873293bde118580872c945b370229a9483bb75eb733a035fe09c95c1374 go$GO_VERSION.linux-alpine-armv7hf.tar.gz" | sha256sum -c - \
&& tar -xzf "go$GO_VERSION.linux-alpine-armv7hf.tar.gz" -C /usr/local/go --strip-components=1 \
&& rm -f go$GO_VERSION.linux-alpine-armv7hf.tar.gz
ENV GOROOT /usr/local/go
ENV GOPATH /go
ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH
RUN mkdir -p "$GOPATH/src" "$GOPATH/bin" && chmod -R 777 "$GOPATH"
WORKDIR $GOPATH
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@golang.sh" \
&& echo "Running test-stack@golang" \
&& chmod +x test-stack@golang.sh \
&& bash test-stack@golang.sh \
&& rm -rf test-stack@golang.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Alpine Linux 3.13 \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nGo v1.14.14 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo $'#!/bin/bash\nbalena-info\nbusybox ln -sf /bin/busybox /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& ln -f /bin/sh /bin/sh.real \
&& ln -f /bin/sh-shim /bin/sh
|
nghiant2710/base-images
|
balena-base-images/golang/orangepi-plus2/alpine/3.13/1.14.14/build/Dockerfile
|
Dockerfile
|
apache-2.0
| 2,343
|
package com.easemob.ChuangKeYuan.ui;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Window;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.widget.RelativeLayout;
import com.easemob.ChuangKeYuan.R;
import com.easemob.ChuangKeYuan.utils.Contacts;
import com.easemob.ChuangKeYuan.utils.SharedPreferencesUtil;
import com.easemob.ChuangKeYuan.utils.UiUtils;
public class SplashActivity extends Activity {
private RelativeLayout mRoot;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//去掉标题栏
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_splash);
initView();
setAnimation();
}
/**
* 初始化控件
*/
private void initView() {
mRoot = (RelativeLayout) findViewById(R.id.rel_splash_root);
}
/**
* 设置动画
*/
private void setAnimation() {
// 1.旋转动画
// fromDegrees : 开始的角度
// toDegrees : 结束的角度
// pivotXType, pivotXValue, pivotYType, pivotYValue : 旋转的类型和坐标
RotateAnimation rotateAnimation = new RotateAnimation(0, 360,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
rotateAnimation.setDuration(1000);// 设置持续时间
rotateAnimation.setFillAfter(true);// 保持结束的位置
// 2.缩放动画
// fromX, toX, fromY, toY : 表示从那里开始缩放,缩放到那里
// pivotXType, pivotXValue, pivotYType, pivotYValue : 旋转的类型和坐标
ScaleAnimation scaleAnimation = new ScaleAnimation(0, 1, 0, 1,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
scaleAnimation.setDuration(1000);
scaleAnimation.setFillAfter(true);
// 3.渐变动画
//fromAlpha, toAlpha : 从透明到不透明
AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);
alphaAnimation.setDuration(1000);
alphaAnimation.setFillAfter(true);
//4.组合动画
//shareInterpolator : 是否公用动画插补器,true:共用 false:不共用
AnimationSet animationSet = new AnimationSet(false);
//设置添加动画
animationSet.addAnimation(rotateAnimation);
animationSet.addAnimation(scaleAnimation);
animationSet.addAnimation(alphaAnimation);
//执行动画
mRoot.startAnimation(animationSet);
//动画设置监听
animationSet.setAnimationListener(animationListener);
}
//动画监听
Animation.AnimationListener animationListener = new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
//跳转操作
//第一次进入,跳转引导界面,不是第一次,跳转主界面,splash界面只是判断是否是第一次进入,更改操作放到其他界面
boolean isfirst_enter = SharedPreferencesUtil.getBoolean(UiUtils.getContext(), Contacts.FIRST_ENTER, true);
if (isfirst_enter) {
//跳转引导界面
startActivity(new Intent(SplashActivity.this, GuideActivity.class));
}else{
//跳转主界面
startActivity(new Intent(SplashActivity.this, HomeActivity.class));
}
//当跳转到其他界面的时候,点击返回键是直接退出程序,而不是跳回splash界面
finish();
}
};
}
|
xadevelop/ChuangKeYuan
|
src/com/easemob/ChuangKeYuan/ui/SplashActivity.java
|
Java
|
apache-2.0
| 4,061
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_151) on Thu Mar 08 14:17:37 MST 2018 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>TcpProtocolConsumer (BOM: * : All 2018.3.3 API)</title>
<meta name="date" content="2018-03-08">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="TcpProtocolConsumer (BOM: * : All 2018.3.3 API)";
}
}
catch(err) {
}
//-->
var methods = {"i0":6,"i1":18};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"],16:["t5","Default Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/TcpProtocolConsumer.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2018.3.3</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../../org/wildfly/swarm/config/management/access/syslog_handler/TcpProtocol.html" title="class in org.wildfly.swarm.config.management.access.syslog_handler"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../../../org/wildfly/swarm/config/management/access/syslog_handler/TcpProtocolSupplier.html" title="interface in org.wildfly.swarm.config.management.access.syslog_handler"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/wildfly/swarm/config/management/access/syslog_handler/TcpProtocolConsumer.html" target="_top">Frames</a></li>
<li><a href="TcpProtocolConsumer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.wildfly.swarm.config.management.access.syslog_handler</div>
<h2 title="Interface TcpProtocolConsumer" class="title">Interface TcpProtocolConsumer<T extends <a href="../../../../../../../org/wildfly/swarm/config/management/access/syslog_handler/TcpProtocol.html" title="class in org.wildfly.swarm.config.management.access.syslog_handler">TcpProtocol</a><T>></h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>Functional Interface:</dt>
<dd>This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.</dd>
</dl>
<hr>
<br>
<pre><a href="http://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html?is-external=true" title="class or interface in java.lang">@FunctionalInterface</a>
public interface <span class="typeNameLabel">TcpProtocolConsumer<T extends <a href="../../../../../../../org/wildfly/swarm/config/management/access/syslog_handler/TcpProtocol.html" title="class in org.wildfly.swarm.config.management.access.syslog_handler">TcpProtocol</a><T>></span></pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd"> </span></span><span id="t5" class="tableTab"><span><a href="javascript:show(16);">Default Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/management/access/syslog_handler/TcpProtocolConsumer.html#accept-T-">accept</a></span>(<a href="../../../../../../../org/wildfly/swarm/config/management/access/syslog_handler/TcpProtocolConsumer.html" title="type parameter in TcpProtocolConsumer">T</a> value)</code>
<div class="block">Configure a pre-constructed instance of TcpProtocol resource</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>default <a href="../../../../../../../org/wildfly/swarm/config/management/access/syslog_handler/TcpProtocolConsumer.html" title="interface in org.wildfly.swarm.config.management.access.syslog_handler">TcpProtocolConsumer</a><<a href="../../../../../../../org/wildfly/swarm/config/management/access/syslog_handler/TcpProtocolConsumer.html" title="type parameter in TcpProtocolConsumer">T</a>></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/management/access/syslog_handler/TcpProtocolConsumer.html#andThen-org.wildfly.swarm.config.management.access.syslog_handler.TcpProtocolConsumer-">andThen</a></span>(<a href="../../../../../../../org/wildfly/swarm/config/management/access/syslog_handler/TcpProtocolConsumer.html" title="interface in org.wildfly.swarm.config.management.access.syslog_handler">TcpProtocolConsumer</a><<a href="../../../../../../../org/wildfly/swarm/config/management/access/syslog_handler/TcpProtocolConsumer.html" title="type parameter in TcpProtocolConsumer">T</a>> after)</code> </td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="accept-org.wildfly.swarm.config.management.access.syslog_handler.TcpProtocol-">
<!-- -->
</a><a name="accept-T-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>accept</h4>
<pre>void accept(<a href="../../../../../../../org/wildfly/swarm/config/management/access/syslog_handler/TcpProtocolConsumer.html" title="type parameter in TcpProtocolConsumer">T</a> value)</pre>
<div class="block">Configure a pre-constructed instance of TcpProtocol resource</div>
</li>
</ul>
<a name="andThen-org.wildfly.swarm.config.management.access.syslog_handler.TcpProtocolConsumer-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>andThen</h4>
<pre>default <a href="../../../../../../../org/wildfly/swarm/config/management/access/syslog_handler/TcpProtocolConsumer.html" title="interface in org.wildfly.swarm.config.management.access.syslog_handler">TcpProtocolConsumer</a><<a href="../../../../../../../org/wildfly/swarm/config/management/access/syslog_handler/TcpProtocolConsumer.html" title="type parameter in TcpProtocolConsumer">T</a>> andThen(<a href="../../../../../../../org/wildfly/swarm/config/management/access/syslog_handler/TcpProtocolConsumer.html" title="interface in org.wildfly.swarm.config.management.access.syslog_handler">TcpProtocolConsumer</a><<a href="../../../../../../../org/wildfly/swarm/config/management/access/syslog_handler/TcpProtocolConsumer.html" title="type parameter in TcpProtocolConsumer">T</a>> after)</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/TcpProtocolConsumer.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2018.3.3</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../../org/wildfly/swarm/config/management/access/syslog_handler/TcpProtocol.html" title="class in org.wildfly.swarm.config.management.access.syslog_handler"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../../../org/wildfly/swarm/config/management/access/syslog_handler/TcpProtocolSupplier.html" title="interface in org.wildfly.swarm.config.management.access.syslog_handler"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/wildfly/swarm/config/management/access/syslog_handler/TcpProtocolConsumer.html" target="_top">Frames</a></li>
<li><a href="TcpProtocolConsumer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2018 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
|
wildfly-swarm/wildfly-swarm-javadocs
|
2018.3.3/apidocs/org/wildfly/swarm/config/management/access/syslog_handler/TcpProtocolConsumer.html
|
HTML
|
apache-2.0
| 12,260
|
/*
* Copyright 2008 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.powermock.api.easymock.mockpolicies;
/**
* An slf4j mock policy. This mock policy deals with solving slf4j related
* mocking issues. It takes care of loading all concerned slf4j and log4j
* classes through the correct class-loader and automatically prepares and
* injects logger instances. This policy does the following:
* <ol>
* <li>Prepares <tt>org.apache.log4j.Appender</tt>,
* <tt>org.slf4j.LoggerFactory</tt> and
* <tt>org.apache.log4j.xml.DOMConfigurator</tt> for testing.</li>
* <li>All calls to the <tt>org.slf4j.LoggerFactory#getLogger(..)</tt> methods
* are intercepted and returns a nice mock of type <tt>org.slf4j.Logger</tt>.</li>
* </ol>
*/
public class Slf4jMockPolicy extends AbstractEasyMockLogPolicyBase {
@Override
protected String[] getFullyQualifiedNamesOfClassesToLoadByMockClassloader() {
return new String[] { "org.apache.log4j.Appender", "org.slf4j.LoggerFactory", "org.apache.log4j.xml.DOMConfigurator" };
}
@Override
protected String getLogFrameworkName() {
return "slf4j";
}
@Override
protected String getLoggerClassToMock() {
return "org.slf4j.Logger";
}
@Override
protected String getLoggerFactoryClassName() {
return "org.slf4j.LoggerFactory";
}
@Override
protected String getLoggerMethodName() {
return "getLogger";
}
}
|
thekingnothing/powermock
|
api/easymock/src/main/java/org/powermock/api/easymock/mockpolicies/Slf4jMockPolicy.java
|
Java
|
apache-2.0
| 1,981
|
package com.twitter.finagle.exception
import com.twitter.util._
import com.twitter.finagle.core.util.InetAddressUtil
import com.twitter.finagle.util.LoadedReporterFactory
import java.net.{InetAddress, InetSocketAddress}
import com.twitter.finagle.exception.thrift.{ResultCode, LogEntry, Scribe}
import org.junit.runner.RunWith
import org.mockito.ArgumentCaptor
import org.mockito.Matchers.anyObject
import org.mockito.Mockito._
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar
@RunWith(classOf[JUnitRunner])
class DefaultReporterTest extends FunSuite with MockitoSugar {
val logger = mock[Scribe.FutureIface]
when(logger.log(anyObject())) thenReturn(Future.value(ResultCode.Ok))
val captor = ArgumentCaptor.forClass(classOf[Seq[LogEntry]])
val reporter = Reporter(logger, "service16")
val tse = new TestServiceException("service16", "my cool message")
test("log entries to a client once upon receive") {
reporter.handle(tse.throwable)
verify(logger).log(captor.capture())
}
test("log a json entry with the proper format") {
val es = captor.getValue
assert(es.size == 1)
tse.verifyCompressedJSON(es(0).message)
}
}
@RunWith(classOf[JUnitRunner])
class ClientReporterTest extends FunSuite with MockitoSugar {
val logger = mock[Scribe.FutureIface]
when(logger.log(anyObject())) thenReturn(Future.value(ResultCode.Ok))
val captor = ArgumentCaptor.forClass(classOf[Seq[LogEntry]])
val reporter = Reporter(logger, "service16").withClient()
val tse = new TestServiceException("service16", "my cool message",
clientAddress = Some(InetAddressUtil.Loopback.getHostAddress))
test("log entries to a client once upon receive") {
reporter.handle(tse.throwable)
verify(logger).log(captor.capture())
}
test("log a json entry with the proper format") {
val es = captor.getValue
assert(es.size == 1)
tse.verifyCompressedJSON(es(0).message)
}
}
@RunWith(classOf[JUnitRunner])
class SourceClientReporterTest extends FunSuite with MockitoSugar {
val logger = mock[Scribe.FutureIface]
when(logger.log(anyObject())) thenReturn(Future.value(ResultCode.Ok))
val captor = ArgumentCaptor.forClass(classOf[Seq[LogEntry]])
val socket = new InetSocketAddress("localhost", RandomSocket.nextPort())
val reporter = Reporter(logger, "service16")
.withSource(socket)
.withClient()
val tse = new TestServiceException("service16", "my cool message",
clientAddress = Some(InetAddressUtil.Loopback.getHostAddress), sourceAddress = Some(socket.getAddress.getHostName))
test("log entries to a client once upon receive") {
reporter.handle(tse.throwable)
verify(logger).log(captor.capture())
}
test("log a json entry with the proper format") {
val es = captor.getValue
assert(es.size == 1)
tse.verifyCompressedJSON(es(0).message)
}
}
@RunWith(classOf[JUnitRunner])
class ExceptionReporterTest extends FunSuite with MockitoSugar {
test("logs an exception through the loaded reporter") {
val logger = mock[Scribe.FutureIface]
when(logger.log(anyObject())) thenReturn(Future.value(ResultCode.Ok))
val captor = ArgumentCaptor.forClass(classOf[Seq[LogEntry]])
val tse = new TestServiceException("service", "my cool message")
val reporter = LoadedReporterFactory("service", None).asInstanceOf[Reporter]
reporter.copy(client = logger).handle(tse.throwable)
verify(logger).log(captor.capture())
}
test("logs a client exception through the loaded reporter") {
val logger = mock[Scribe.FutureIface]
when(logger.log(anyObject())) thenReturn(Future.value(ResultCode.Ok))
val captor = ArgumentCaptor.forClass(classOf[Seq[LogEntry]])
val socket = new InetSocketAddress("localhost", RandomSocket.nextPort())
val tse = new TestServiceException("service", "my cool message",
clientAddress = Some(socket.getAddress.getHostName))
val reporter = LoadedReporterFactory("service", Some(socket)).asInstanceOf[Reporter]
reporter.copy(client = logger).handle(tse.throwable)
verify(logger).log(captor.capture())
}
}
|
JustinTulloss/finagle
|
finagle-exception/src/test/scala/com/twitter/finagle/exception/ReporterSpec.scala
|
Scala
|
apache-2.0
| 4,139
|
<section id="about" data-aos="fade-down" data-aos-delay="200" data-aos-easing="ease-in">
<div class="container">
<h1>About the Conference</h1>
<div class="row align-items-center">
<div class="col-lg-6 col-sm-12 order-md-2">
<script async type="text/javascript" id="vidyard_embed_code_cEn5GFiBuQRjU3GZrPe4hq" src="//play.vidyard.com/cEn5GFiBuQRjU3GZrPe4hq.js?v=3.1.1&type=lightbox"></script>
<div class="outer_vidyard_wrapper">
<div class="vidyard_wrapper" onclick="fn_vidyard_cEn5GFiBuQRjU3GZrPe4hq();">
<img width="560" src="//play.vidyard.com/cEn5GFiBuQRjU3GZrPe4hq.jpg?" alt="Innovate Summit 2017 Highlight Reel">
<div class="vidyard_play_button">
<a href="javascript:void(0);"></a>
</div>
</div>
</div>
</div>
<div class="col-lg-6 col-sm-12 order-md-1">
<p>
Innovate Summit is a one-day event and a great opportunity for software developers
to meet and learn from SolarWinds engineers and others in the monitoring,
management and development community.
</p>
<p>
The 2017 Summit was held on December 14, 2017 in Brno, Czech Republic. Many joined
us for an evening of talks from experts and fellow devs on topics within
the
<em>cloud native</em> ecosystem, ranging from containers to serverless. The talks
were followed by a happy hour to network and have fun.
</p>
<p>
Check out the highlight reel as well as videos and photos from the talks and event
below.
</p>
<div class="about__aside">
<span class="about__aside-header">In the press</span>
<a href="https://www.zive.cz/clanky/pozvanka-na-konferenci-innovate-summit-innovation-goes-social-at-solarwinds-innovate-summit-2017/sc-3-a-190647/default.aspx"
target="_blank">Innovation goes social at Innovate Summit 2017</a>
</div>
</div>
</div>
</div>
</section>
|
leecalcote/innovate.solarwinds.io
|
_includes/2017/sections/about.html
|
HTML
|
apache-2.0
| 2,414
|
package me.chanjar.weixin.cp.bean;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* 调用wx.agentConfig时所需要的签名信息
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class WxCpAgentJsapiSignature implements Serializable {
private static final long serialVersionUID = 2650119900835832545L;
private String url;
private String corpid;
private Integer agentid;
private long timestamp;
private String nonceStr;
private String signature;
}
|
Wechat-Group/WxJava
|
weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpAgentJsapiSignature.java
|
Java
|
apache-2.0
| 585
|
/*
* Copyright 2013 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.example.xyzreader.cp1;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.NotificationCompat;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.example.xyzreader.cp1.dummy.DummyContent;
/**
* A list fragment representing a list of Articles. This fragment also supports tablet devices by
* allowing list items to be given an 'activated' state upon selection. This helps indicate which
* item is currently being viewed in a {@link ArticleDetailFragment}. <p> Activities containing this
* fragment MUST implement the {@link Callbacks} interface.
*/
public class ArticleListFragment extends ListFragment {
/**
* The serialization (saved instance state) Bundle key representing the activated item position.
* Only used on tablets.
*/
private static final String STATE_ACTIVATED_POSITION = "activated_position";
/**
* The fragment's current callback object, which is notified of list item clicks.
*/
private Callbacks mCallbacks = sDummyCallbacks;
/**
* The current activated item position. Only used on tablets.
*/
private int mActivatedPosition = ListView.INVALID_POSITION;
/**
* A callback interface that all activities containing this fragment must implement. This
* mechanism allows activities to be notified of item selections.
*/
public interface Callbacks {
/**
* Callback for when an item has been selected.
*/
public void onItemSelected(String id);
}
/**
* A dummy implementation of the {@link Callbacks} interface that does nothing. Used only when
* this fragment is not attached to an activity.
*/
private static Callbacks sDummyCallbacks = new Callbacks() {
@Override
public void onItemSelected(String id) {
}
};
/**
* Mandatory empty constructor for the fragment manager to instantiate the fragment (e.g. upon
* screen orientation changes).
*/
public ArticleListFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new MyAdapter());
setHasOptionsMenu(true);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Restore the previously serialized activated item position.
if (savedInstanceState != null
&& savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
setActivatedPosition(savedInstanceState
.getInt(STATE_ACTIVATED_POSITION));
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Activities containing this fragment must implement its callbacks.
if (!(activity instanceof Callbacks)) {
throw new IllegalStateException(
"Activity must implement fragment's callbacks.");
}
mCallbacks = (Callbacks) activity;
}
@Override
public void onDetach() {
super.onDetach();
// Reset the active callbacks interface to the dummy implementation.
mCallbacks = sDummyCallbacks;
}
@Override
public void onListItemClick(ListView listView, View view, int position,
long id) {
super.onListItemClick(listView, view, position, id);
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mCallbacks.onItemSelected(DummyContent.ITEMS.get(position).id);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mActivatedPosition != ListView.INVALID_POSITION) {
// Serialize and persist the activated item position.
outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition);
}
}
/**
* Turns on activate-on-click mode. When this mode is on, list items will be given the
* 'activated' state when touched.
*/
public void setActivateOnItemClick(boolean activateOnItemClick) {
// When setting CHOICE_MODE_SINGLE, ListView will automatically
// give items the 'activated' state when touched.
getListView().setChoiceMode(
activateOnItemClick ? ListView.CHOICE_MODE_SINGLE
: ListView.CHOICE_MODE_NONE);
}
private void setActivatedPosition(int position) {
if (position == ListView.INVALID_POSITION) {
getListView().setItemChecked(mActivatedPosition, false);
} else {
getListView().setItemChecked(position, true);
}
mActivatedPosition = position;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.refresh) {
DummyContent.DummyItem dummy = DummyContent.ITEMS.get(0);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 16;
Bitmap photo = BitmapFactory.decodeResource(getResources(), dummy.photoResId);
Notification n = new NotificationCompat.Builder(getActivity())
.setContentTitle("Article published")
.setSmallIcon(R.drawable.stat_icon)
.setDefaults(Notification.DEFAULT_SOUND)
.setLargeIcon(photo)
.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(photo)
.setSummaryText(dummy.title))
.setContentText(dummy.title)
.setContentIntent(PendingIntent.getActivity(getActivity(), 0,
new Intent(getActivity(), getActivity().getClass()),
PendingIntent.FLAG_UPDATE_CURRENT))
.setAutoCancel(true)
.addAction(R.drawable.ic_share, "Share",
PendingIntent.getActivity(getActivity(), 0,
new Intent(getActivity(), getActivity().getClass()),
PendingIntent.FLAG_UPDATE_CURRENT))
.build();
NotificationManager nm = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(1, n);
return true;
}
return super.onOptionsItemSelected(item);
}
private class MyAdapter extends BaseAdapter {
@Override
public int getCount() {
return DummyContent.ITEMS.size();
}
@Override
public Object getItem(int position) {
return DummyContent.ITEMS.get(position);
}
@Override
public long getItemId(int position) {
return DummyContent.ITEMS.get(position).id.hashCode();
}
@Override
public View getView(int position, View convertView, ViewGroup container) {
if (convertView == null) {
convertView = LayoutInflater.from(getActivity())
.inflate(R.layout.list_item_article, container, false);
}
final DummyContent.DummyItem item = (DummyContent.DummyItem) getItem(position);
((TextView) convertView.findViewById(R.id.article_title)).setText(item.title);
((TextView) convertView.findViewById(R.id.article_subtitle)).setText(
item.time + " by " + item.author);
Bitmap b = BitmapFactory.decodeResource(getResources(), item.photoResId);
((ImageView) convertView.findViewById(R.id.thumbnail)).setImageBitmap(b);
return convertView;
}
}
}
|
ankurkotwal/making-apps-beautiful
|
XYZReader_CP1/src/main/java/com/example/xyzreader/cp1/ArticleListFragment.java
|
Java
|
apache-2.0
| 9,181
|
# coding=utf-8
# Copyright 2018 The Google AI Language Team 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.
"""Compare a txt file of predictions with gold targets from a TSV file."""
from absl import app
from absl import flags
from language.compgen.nqg.tasks import tsv_utils
from tensorflow.io import gfile
FLAGS = flags.FLAGS
flags.DEFINE_string("gold", "", "tsv file containing gold targets.")
flags.DEFINE_string("predictions", "", "txt file with predicted targets.")
def main(unused_argv):
gold_examples = tsv_utils.read_tsv(FLAGS.gold)
preds = []
with gfile.GFile(FLAGS.predictions, "r") as f:
for line in f:
preds.append(line.rstrip())
correct = 0
incorrect = 0
for pred, gold_example in zip(preds, gold_examples):
if pred == gold_example[1]:
correct += 1
else:
incorrect += 1
print("Incorrect for example %s.\nTarget: %s\nPrediction: %s" %
(gold_example[0], gold_example[1], pred))
print("correct: %s" % correct)
print("incorrect: %s" % incorrect)
print("pct: %s" % str(float(correct) / float(correct + incorrect)))
if __name__ == "__main__":
app.run(main)
|
google-research/language
|
language/compgen/nqg/tasks/compare_predictions.py
|
Python
|
apache-2.0
| 1,653
|
package itat.zttc.shop.service;
import itat.zttc.shop.model.Address;
import itat.zttc.shop.model.ShopException;
import itat.zttc.shop.model.User;
import itat.zttc.shop.test.BaseTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.*;
/**
* since 2015/6/10.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:beans.xml"})
public class TestAddressService extends BaseTest {
@Autowired
private IAddressService addressService;
@Autowired
private IUserService userService;
@Test
public void testAdd() throws Exception {
User user = buildUser();
userService.add(user);
Address address = buildAddress();
address.setUser(user);
Address add = addressService.add(address);
assertTrue(add.getId() > 0);
}
@Test(expected = ShopException.class)
public void testAddEx() throws Exception {
User user = buildUser();
user.setId(10000);
Address address = buildAddress();
address.setUser(user);
Address add = addressService.add(address);
}
}
|
jt120/one-shop
|
src/test/java/itat/zttc/shop/service/TestAddressService.java
|
Java
|
apache-2.0
| 1,335
|
/*
* @license
* Copyright Hôpitaux Universitaires de Genève. 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 https://github.com/DSI-HUG/dejajs-components/blob/master/LICENSE
*/
import { Component, ElementRef, ViewChild, ViewEncapsulation } from '@angular/core';
import { Destroy } from '@deja-js/component/core';
import { Position } from '@deja-js/component/core/graphics';
import { BehaviorSubject, combineLatestWith, delay, filter, takeUntil, tap } from 'rxjs';
import { IDragCursorInfos } from './mouse-drag-cursor-infos.interface';
import { DejaMouseDragDropService } from './mouse-dragdrop.service';
@Component({
encapsulation: ViewEncapsulation.None,
selector: 'deja-mouse-dragdrop-cursor',
styleUrls: [
'./mouse-dragdrop-cursor.component.scss'
],
templateUrl: './mouse-dragdrop-cursor.component.html'
})
export class DejaMouseDragDropCursorComponent extends Destroy {
@ViewChild('block', { static: true }) private icon: ElementRef<HTMLElement>;
@ViewChild('content', { static: true }) private content: ElementRef<HTMLElement>;
private position$ = new BehaviorSubject<Position>(null);
private cursor$ = new BehaviorSubject<IDragCursorInfos>(null);
private currentCursor: IDragCursorInfos;
public constructor(elementRef: ElementRef, private dragDropService: DejaMouseDragDropService) {
super();
const element = elementRef.nativeElement as HTMLElement;
this.position$.pipe(
takeUntil(this.destroyed$)
).subscribe(pos => {
element.style.left = pos ? `${pos.left}px` : '-1000px';
element.style.top = pos ? `${pos.top}px` : '-1000px';
});
// Hide
this.cursor$.pipe(
filter(cursor => !cursor),
tap(cursor => {
if (this.currentCursor) {
if (this.contentElement) {
this.contentElement.style.opacity = '0';
}
if (this.iconElement) {
this.iconElement.style.opacity = '0';
}
}
this.currentCursor = cursor;
}),
delay(300),
takeUntil(this.destroyed$)
).subscribe(() => {
this.position$.next(null);
element.style.display = 'none';
});
// Show
this.cursor$.pipe(
filter(cursor => !!cursor),
tap(cursor => {
element.style.display = '';
if (this.contentElement) {
this.contentElement.style.opacity = '0';
}
if (this.iconElement) {
this.iconElement.style.opacity = '0';
}
this.currentCursor = cursor;
}),
filter(cursor => !cursor.className || cursor.className !== 'hidden'),
tap(cursor => {
if (cursor.html) {
element.className = cursor.className;
if (this.contentElement) {
this.contentElement.innerHTML = cursor.html;
this.contentElement.style.width = `${cursor.width || 48}px`;
this.contentElement.style.height = `${cursor.height || 48}px`;
}
} else if (this.iconElement) {
this.iconElement.style.opacity = '1';
}
}),
delay(1),
takeUntil(this.destroyed$)
).subscribe(cursor => {
if (!!cursor.html && this.contentElement) {
this.contentElement.style.opacity = '1';
}
});
this.dragDropService.dragCursor$.pipe(
combineLatestWith(this.dragDropService.dropCursor$),
takeUntil(this.destroyed$)
).subscribe(([dragCursor, dropCursor]) => {
const cursor = (dragCursor || dropCursor) && {
className: dropCursor?.className || dragCursor?.className,
html: dropCursor?.html || dragCursor?.html || (dropCursor && dragCursor?.originalHtml),
width: dropCursor?.width || dragCursor?.width,
height: dropCursor?.height || dragCursor?.height,
position: dragCursor?.position,
originalEvent: dragCursor?.originalEvent
} as IDragCursorInfos;
if (cursor?.html !== this.currentCursor?.html || cursor?.className !== this.currentCursor?.className || cursor?.width !== this.currentCursor?.width || cursor?.height !== this.currentCursor?.height) {
// Update Content
this.cursor$.next(cursor);
} else {
// Update only Position
this.position$.next(cursor?.position);
}
});
}
private get iconElement(): HTMLElement {
return this.icon?.nativeElement;
}
private get contentElement(): HTMLElement {
return this.content?.nativeElement;
}
}
|
DSI-HUG/dejajs-components
|
projects/deja-js/component/mouse-dragdrop/mouse-dragdrop-cursor.component.ts
|
TypeScript
|
apache-2.0
| 5,129
|
//---------------------------------------------------------------------------
// E L E N A P r o j e c t: ELENA Engine
//
// This file contains the Debugger class and its helpers header
// (C)2005-2015, by Alexei Rakov
//---------------------------------------------------------------------------
#ifndef gtkdebuggerH
#define gtkdebuggerH
#include "../debugging.h"
// --- EventManager ---
#define DEBUG_CLOSE 0
#define DEBUG_SUSPEND 1
#define DEBUG_RESUME 2
#define DEBUG_ACTIVE 3
#define MAX_DEBUG_EVENT 4
namespace _ELENA_
{
class DebugEventManager
{
// //HANDLE _events[MAX_DEBUG_EVENT];
public:
void init();
void resetEvent(int event);
void setEvent(int event);
int waitForAnyEvent();
bool waitForEvent(int event, int timeout);
void close();
DebugEventManager()
{
// for (int i = 0 ; i < MAX_DEBUG_EVENT ; i++)
// _events[i] = NULL;
}
~DebugEventManager()
{
close();
}
};
// --- ThreadBreakpoint ---
struct ThreadBreakpoint
{
bool software;
bool hardware;
size_t next;
size_t stackLevel;
void clearSoftware()
{
software = false;
next = 0;
}
ThreadBreakpoint()
{
hardware = software = false;
stackLevel = next = 0;
}
};
// --- ProcessException ---
struct ProcessException
{
int code;
int address;
const char* Text();
ProcessException()
{
code = 0;
}
};
// --- ThreadContext ---
struct ThreadContext
{
friend class Debugger;
friend struct BreakpointContext;
protected:
void* state;
// HANDLE hProcess;
// HANDLE hThread;
// CONTEXT context;
public:
ThreadBreakpoint breakpoint;
bool atCheckPoint;
bool checkFailed;
void* State() const { return state; }
size_t EIP() const { return /*context.Eip*/0; } // !! temporal
size_t Frame() { return /*context.Ebp - offset * */4; } // !! temporal
size_t Local(int offset) { return /*context.Ebp - offset * */4; } // !! temporal
size_t Current(int offset) { return /*context.Esp + offset * */4; }// !! temporal
size_t ClassVMT(size_t address);
size_t VMTFlags(size_t address);
size_t ObjectPtr(size_t address);
size_t LocalPtr(int offset) { return ObjectPtr(Local(offset)); }
size_t CurrentPtr(int offset) { return ObjectPtr(Current(offset)); }
void readDump(size_t address, char* dump, size_t length);
void writeDump(size_t address, char* dump, size_t length);
size_t readDWord(size_t address) { return 0; } // !! temporal
size_t readWord(size_t address) { return 0; } // !! temporal
void refresh();
void setCheckPoint();
void setTrapFlag();
void resetTrapFlag();
void setHardwareBreakpoint(size_t breakpoint);
unsigned char setSoftwareBreakpoint(size_t breakpoint);
void setEIP(size_t address);
void clearHardwareBreakpoint();
void clearSoftwareBreakpoint(size_t breakpoint, char substitute);
// ThreadContext(HANDLE hProcess, HANDLE hThread);
};
// --- BreakpointContext ---
struct BreakpointContext
{
Map<size_t, char> breakpoints;
void addBreakpoint(size_t address, ThreadContext* context, bool started);
void removeBreakpoint(size_t address, ThreadContext* context, bool started);
void setSoftwareBreakpoints(ThreadContext* context);
void setHardwareBreakpoint(size_t address, ThreadContext* context, bool withStackLevelControl);
bool processStep(ThreadContext* context, bool stepMode);
bool processBreakpoint(ThreadContext* context);
void clear();
BreakpointContext();
};
// --- Debugger ---
class Debugger
{
// typedef Map<int, ThreadContext*> ThreadContextes;
//
// DWORD threadId;
//
bool started;
bool trapped;
// bool stepMode;
// bool needToHandle;
// bool exitCheckPoint;
//
// BreakpointContext breakpoints;
//
// ThreadContextes threads;
// ThreadContext* current;
//
// DWORD dwCurrentProcessId;
// DWORD dwCurrentThreadId;
//
// size_t minAddress, maxAddress;
//// size_t vmhookAddress; // =0 - hook is turned off, =-1 : waiting for initializing, >0 hook address
//
// MemoryMap<int, void*> steps;
//
// ProcessException exception;
//
// bool startProcess(const TCHAR* exePath, const TCHAR* cmdLine);
// void processEvent(size_t timeout);
// void processException(EXCEPTION_DEBUG_INFO* exception);
// void continueProcess();
//
// void processStep();
public:
bool isStarted() const { return started; }
bool isTrapped() const { return trapped; }
// !! temporal
bool isInitBreakpoint() const { return /*vmhookAddress == current->context.Eip;*/ false; }
ThreadContext* Context() { return /*current*/NULL; }
ProcessException* Exception() { return /*exception.code == 0 ? */NULL/* : &exception*/; } // !! temporal
void resetException() { /*exception.code = 0;*/ }
void addStep(size_t address, void* state);
void addBreakpoint(size_t address);
void removeBreakpoint(size_t address);
void clearBreakpoints();
void setStepMode();
void setBreakpoint(size_t address, bool withStackLevelControl);
void setCheckMode();
bool startThread(_DebugController* controller);
bool start(const char* exePath, const char* cmdLine);
void run();
bool proceed(size_t timeout);
void stop();
void processVirtualStep(void* step);
bool proceedCheckPoint();
void reset();
void activate();
// !! temporal
void initHook() { /*vmhookAddress = -1;*/ }
bool initDebugInfo(bool standalone, StreamReader& reader, size_t& debugInfoPtr);
size_t findEntryPoint(const char* programPath);
bool findSignature(char* signature);
Debugger();
};
} // _ELENA_
#endif // gtkdebuggerH
|
bencz/cpu-simulator
|
elena_lang/elenasrc2/ide/gtk-linux32/debugger.h
|
C
|
apache-2.0
| 5,831
|
jQuery(document).ready(function($) {
$('#addmoreitem').click(function() {
var lastid = $('.uploadevent').last().attr('id');
for(var i = 1; i < 5; i++){
var addId = Number(lastid)+Number(i);
var addHtml = '<div class="panel-group" id="accordion"><div class="panel panel-default"><div class="panel-heading"><div class="input-group"><input type="text" name="vote_item_name['+addId+']" class="form-control" placeholder="选项'+addId+'"><div class="input-group-btn"><a type="button" class="btn btn-default uploadevent" data-toggle="collapse" data-parent="#accordion" href="#add_info_'+addId+'">添加详情</a></div></div></div><div id="add_info_'+addId+'" class="panel-collapse collapse"><div class="panel-body"><input type="hidden" name="vote_item_attach['+addId+']" id="vote_item_attach_'+addId+'"><button type="button" class="btn btn-info uploadevent" tabindex="-1" data-toggle="modal" data-target="#model_upload" id="'+addId+'">上传附件</button><br><br><textarea class="form-control" rows="2" name="vote_item_description['+addId+']" placeholder="选项描述"></textarea></div></div></div></div>';
$('#vote-item').append(addHtml);
if(addId == 20){
$('#addmoreitem').css({
display: 'none'
});
}
}
});
$('.date').datepicker({
format: "yyyy-mm-dd"
});
$('#vote_type1').click(function(){
$('#vote_limit_number_div').remove();
});
$('#vote_type2').click(function(){
var divnum = $('#vote_limit_number_div');
if(!divnum.length){
var addHtml = '<div class="form-group" id="vote_limit_number_div"><br><label for="vote-topic">限投票数:</label><input type="text" name="vote_limit_number" class="form-control" placeholder="限投票数"></div>';
$('#vote_num_more').append(addHtml);
}
});
$('.vote-item-more-info').click(function() {
alert('ss');
});
});
$(document).ready(function(){
$("#votepostuploader").uploadFile({
url:"/herald_vote/index.php/Admin/Index/addVotePost/",
allowedTypes:"jpg,png,gif,jpeg,mp4",
fileName:"vote_post",
showAbort:true,
uploadButtonClass:"btn btn-success",
onSuccess:function(files,data,xhr){
var uploadid = $('#uploadid').val();
var inputid = '#vote_item_attach_'+uploadid;
var btnid = '#'+uploadid;
$(inputid).val(data);
$(btnid).html('添加成功').removeClass('btn-info').removeAttr('data-target').addClass('btn-success').attr('disabled', 'disabled');;
}
});
$('#vote_post_name').click(function() {
$('#uploadid').val(0);
});
$('body').on('click','.uploadevent', function() {
var upid = $(this).attr('id');
$('#uploadid').val(upid);
});
// $('.uploadevent').click(function() {
// var upid = $(this).attr('id');
// $('#uploadid').val(upid);
// });
$('.delete_vote').click(function() {
var delid = $(this).attr('id');
$.ajax({
url: '/herald_vote/index.php/Admin/Index/deleteVote/',
type: 'post',
data: {'vote_id': delid},
success:function(data){
$('#vote_info_tr_'+delid).hide("slow");
},
})
});
});
|
HeraldStudio/herald_vote
|
Public/Js/herald-vote.js
|
JavaScript
|
apache-2.0
| 3,032
|
/*
* 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.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.*;
/**
* BatchUpdateLinkAttributes JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class BatchUpdateLinkAttributesJsonUnmarshaller implements Unmarshaller<BatchUpdateLinkAttributes, JsonUnmarshallerContext> {
public BatchUpdateLinkAttributes unmarshall(JsonUnmarshallerContext context) throws Exception {
BatchUpdateLinkAttributes batchUpdateLinkAttributes = new BatchUpdateLinkAttributes();
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 null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("TypedLinkSpecifier", targetDepth)) {
context.nextToken();
batchUpdateLinkAttributes.setTypedLinkSpecifier(TypedLinkSpecifierJsonUnmarshaller.getInstance().unmarshall(context));
}
if (context.testExpression("AttributeUpdates", targetDepth)) {
context.nextToken();
batchUpdateLinkAttributes.setAttributeUpdates(new ListUnmarshaller<LinkAttributeUpdate>(LinkAttributeUpdateJsonUnmarshaller.getInstance())
.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 batchUpdateLinkAttributes;
}
private static BatchUpdateLinkAttributesJsonUnmarshaller instance;
public static BatchUpdateLinkAttributesJsonUnmarshaller getInstance() {
if (instance == null)
instance = new BatchUpdateLinkAttributesJsonUnmarshaller();
return instance;
}
}
|
aws/aws-sdk-java
|
aws-java-sdk-clouddirectory/src/main/java/com/amazonaws/services/clouddirectory/model/transform/BatchUpdateLinkAttributesJsonUnmarshaller.java
|
Java
|
apache-2.0
| 3,242
|
package org.wapache.json.transform.mapper;
import javax.json.JsonValue;
public interface Skipper {
public boolean skip(int index, String name, JsonValue value);
}
|
wapache/wason
|
api/src/main/java/org/wapache/json/transform/mapper/Skipper.java
|
Java
|
apache-2.0
| 171
|
package com.bl.locodroid.localisation.domain;
import java.io.Serializable;
public class Location implements Serializable {
public Location(String lat, String lng) {
super();
this.lat = lat;
this.lng = lng;
}
public String lat;
public String lng;
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLng() {
return lng;
}
public void setLng(String lng) {
this.lng = lng;
}
/**
* Constructor Location
*/
public Location()
{
}
}
|
nmalesic/LocoDroid
|
app/src/main/java/com/bl/locodroid/localisation/domain/Location.java
|
Java
|
apache-2.0
| 522
|
## SeetaFace Detection
[](../LICENSE)
### Brief Description
SeetaFace Detection is an implementation of **Fu**nnel-**St**ructured cascade, which is designed for real-time multi-view face detection.
FuSt aims at a good trade-off between accuracy and speed by using a coarse-to-fine structure.
It consists of multiple view-specific fast LAB cascade classifiers at early stages, followed by coarse Multilayer Perceptron (MLP) cascades at later stages.
The final stage is one unified fine MLP cascade, processing all proposed windows in a centralized style.
The open source version of FuSt includes codes for face detection as well as a model for detecting near-frontal faces
(also with reasonable capability to detect non-frontal faces), which is trained with approximately 200K face images.
Please note that the implementation is slightly different from that described in the corresponding [paper](#citation):
(1) The fine MLP cascade uses SURF feature instead of SIFT; (2) Non-Maximal Suprresion (NMS) is added;
(3) Landmark prediction is replaced by bounding box regression (For facial landmark localization,
see [SeetaFace Alignment](https://github.com/seetaface/SeetaFaceEngine/tree/master/FaceAlignment)).
The code is written in C++ without dependence on any third-party libraries.
Currently it is only tested on Windows, but it does not include any Windows-specific headers.
Parallelization is used partially, and more will be introduced in the future.
### Performance Evaluation
The discrete ROC curve on FDDB of the SeetaFace Detector is shown below (curves of other methods are obtained from
[FDDB official site](http://vis-www.cs.umass.edu/fddb/results.html)).
To achieve the results in this figure with SeetaFace Detector, the minimum size of faces to detect should be set to 20,
step of sliding window is set to 2 or 4 (as shown in the legend), and the scaling factor is set to 0.8 (or 1.25 if defined as that used in OpenCV).

The speed comparison is given in the following table, taking VGA input images(640x480) as example.
The step of sliding window of SeetaFace detector is set to 4, with scaling factor 0.8.
Cascade CNN uses an image pyramid with a scaling factor of 0.7 (or 1.414 as defined in OpenCV).
The reported speed of SeetaFace Detector is tested on a single 3.40GHz i7-3770 CPU, and those of other methods
are cited directrly from the corresponding paper (Briefly, the CPU speed of Cascade CNN is tested on a 2.0 GHz CPU core.
The GPU speed is tested on NVIDIA Titan Black GPU.).
Detector | Min Face Size | Speed on CPU | Speed on GPU
-------- | ------------- | ------------ | ------------
SeetaFace Detector | 40x40 | 16.0 FPS | n/a
SeetaFace Detector | 80x80 | 55.0 FPS | n/a
Cascade CNN [1] | 80x80 | 9.1 FPS | 100 FPS
FacenessNet [2] | 80x80 | n/a | 20 FPS
> [1] Haoxiang Li, Zhe Lin, Xiaohui Shen, Jonathan Brandt, and Gang Hua. A convolutional neural network cascade for face detection. CVPR 2015.
> [2] Shuo Yang, Ping Luo, Chen Change Loy, and Xiaoou Tang. From Facial Parts Responses to Face Detection: A Deep Learning Approach. ICCV 2015.
### How to Build Shared Lib with Visual Studio
1. Create a dll project: New Project -> Visual C++ -> Win32 Console Application -> DLL.
2. *(Optional) Create and switch to x64 platform.*
3. Add additional include directories: (Project) Properities -> Configuration Properties -> C/C++ -> General -> Additional Include Directories.
4. Add source files: all `*.cpp` files in `src` except for those in `src/test`.
5. Define `SEETA_EXPORTS` macro: (Project) Properities -> Configuration Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions.
6. *(Optional) Switch to Intel C++ (for better code optimization).*
7. *(Optional) Enable OpenMP support: (Project) Properities -> Configuration Properties -> C/C++ -> Language -> Open MP Support (or ... C/C++ -> Language [Intel C++] -> OpenMP Support). Define `USE_OPENMP` macro if necessary.*
8. Build.
**A Visual Studio 2013 solution is provided in the subdirectory [examples](./examples).**
### How to Build in Linux
- Build
```shell
mkdir build
cd build
cmake ..
make -j${nproc}
```
- Run demo
```shell
./build/facedet_test image_file model/seeta_fd_frontal_v1.0.bin
```
### How to run SeetaFace Detector
The class for face detection is included in `seeta` namespace. To detect faces on an image, one should first
instantiate an object of `seeta::FaceDetection` with path of the model file.
```c++
seeta::FaceDetection face_detector("seeta_fd_frontal_v1.0.bin");
```
After an image is read and converted to grayscale, one needs to pack the image data with `seeta::ImageData`.
Note that the pixel values should stored in a continuous 1D array in row-major style.
```c++
seeta::ImageData img_data(width, height);
img_data.data = img_data_buf;
```
Then one can call `Detect()` to detect faces, which will be returned as a `vector` of [`seeta::FaceInfo`](./include/common.h).
```c++
std::vector<seeta::FaceInfo> faces = face_detector.Detect(img_data);
```
See an [example test file](./src/test/facedetection_test.cpp) for details.
### How to Configure the SeetaFace Detector
* Set minimum and maximum size of faces to detect (Default: 20, Not Limited)
- `face_detector.SetMinFaceSize(size);`
- `face_detector.SetMaxFaceSize(size);`
* Set step size of sliding window (Default: 4)
- `face_detector.SetWindowStep(step_x, step_y);`
* Set scaling factor of image pyramid (0 < `factor` < 1, Default: 0.8)
- `face_detector.SetImagePyramidScaleFactor(factor);`
* Set score threshold of detected faces (Default: 2.0)
- `face_detector.SetScoreThresh(thresh);`
See comments in the [header file](./include/face_detection.h) for details.
### Citation
If you find SeetaFace Detection (FuSt) useful in your research work, please consider citing:
@article{wu2016fust,
Author = {Wu, Shuzhe and Kan, Meina and He, Zhenliang and Shan, Shiguang and Chen, Xilin},
Journal = {Neurocomputing (under review)},
Title = {Funnel-Structured Cascade for Multi-View Face Detection with Alignment-Awareness},
Year = {2016}
}
The arXiv preprint of the paper can be found at [http://arxiv.org/abs/1609.07304](http://arxiv.org/abs/1609.07304).
### License
SeetaFace Detection is released under the [BSD 2-Clause license](../LICENSE).
|
yippeesoft/NotifyTools
|
SeetaFaceEngine/FaceDetection/README.md
|
Markdown
|
apache-2.0
| 6,395
|
package xxxxx.yyyyy.zzzzz.op.domain.shared._experimental.specification;
import java.util.List;
public interface CompositeSpecification<T> extends Specification<T> {
CompositeSpecification<T> with(Specification<T> specification);
default CompositeSpecification<T> with(List<Specification<T>> specifications) {
if (specifications == null) {
throw new IllegalArgumentException("'specifications' must not be null");
}
specifications.stream().forEach(this::with);
return this;
}
List<Specification<T>> unmodifiableComponents();
}
|
namioka/spring-boot-multiple-modules-example
|
xyz-domain/src/main/java/xxxxx/yyyyy/zzzzz/op/domain/shared/_experimental/specification/CompositeSpecification.java
|
Java
|
apache-2.0
| 590
|
<?php
$cssAnsScriptFilesTheme = array(
//Select2
//autosize
//Select2
'/plugins/select2/select2.css',
'/plugins/select2/select2.min.js',
//autosize
'/plugins/autosize/jquery.autosize.min.js',
'/plugins/jQuery-Knob/js/jquery.knob.js',
'/plugins/perfect-scrollbar/src/perfect-scrollbar.css',
);
HtmlHelper::registerCssAndScriptsFiles($cssAnsScriptFilesTheme,Yii::app()->request->baseUrl);
?>
<div class="panel panel-white">
<div class="panel-heading border-ligh bg-purple">
<h4 class="panel-title"><i class="fa <?php echo Project::ICON ?> "></i> <?php echo Yii::t("project","Projects",null,Yii::app()->controller->module->id) ?></h4>
</div>
<div class="panel-tools">
<?php if( @$authorised || $openEdition && isset(Yii::app()->session["userId"]) ) { ?>
<a href="javascript:dyFObj.openForm('project','sub')" class="btn btn-xs btn-light-blue tooltips" data-toggle="tooltip" data-placement="top" title="Add a project" alt="Add a project"><i class="fa fa-plus"></i> Créer un nouveau projet</a>
<?php } ?>
<a id="showHideOldProject" class="tooltips btn btn-xs btn-light-blue" href="javascript:;" data-placement="top" data-toggle="tooltip" data-original-title="<?php echo Yii::t("project","Display/Hide old projects",null,Yii::app()->controller->module->id) ?>" onclick="toogleOldProject()">
<i class="fa fa-history"></i> <?php echo Yii::t("project","Old projects",null,Yii::app()->controller->module->id) ?>
</a>
</div>
<div class="panel-body no-padding">
<div class="panel-scroll height-230 ps-container" style="overflow-y: scroll;">
<?php
$nbOldProjects = 0;
$nbProjectsVisible = 0;
if(isset($projects) && count($projects)>0){ ?>
<table class="table table-striped table-hover" id="projects">
<tbody>
<?php
foreach ($projects as $e) {
if (!empty($e["endDate"])) {
$endDate = strtotime($e["endDate"]);
}
if (empty($e["endDate"]) || $endDate > time()) {
$projectStyle = "";
$projectClass = "";
$nbProjectsVisible++;
} else {
$projectStyle = "display:none;";
$projectClass = "oldProject";
$nbOldProjects++;
}
?>
<tr class="<?php echo $projectClass ?>" style="<?php echo $projectStyle ?>" id="project<?php echo (string)$e["_id"];?>" style="padding:5px 0px;">
<td class="center" style="padding-left: 15px;">
<?php $url = '#page.type.'.Project::COLLECTION.'.id.'.$e["_id"];?>
<a href="<?php echo $url?>" class="lbh text-dark">
<?php if ($e && isset($e["imagePath"])){ ?>
<img width="50" height="50" alt="image" class="img-circle" src="<?php echo $e["imagePath"]; ?>">
<?php } else { ?>
<i class="fa fa-lightbulb-o fa-2x text-purple"></i>
<?php } ?>
</a>
</td>
<td>
<a href="<?php echo $url?>" class="lbh text-dark">
<?php if(isset($e["name"]))echo $e["name"]?>
</a>
</td>
<td class="center">
<div class="visible-md visible-lg visible-lg" >
<?php if( @$authorised ) { ?>
<a href="#" class="removeProjectbtn btn btn-xs btn-grey tooltips delBtn" data-id="<?php echo (string)$e["_id"];?>" data-name="<?php echo (string)$e["name"];?>" data-placement="top" data-original-title="Remove"><i class="fa fa-times fa fa-white"></i></a>
<?php }; ?>
</div>
</td>
</tr>
<?php } ?>
</tbody>
</table>
<?php } ?>
<?php if(isset($projects) && count($projects) > 0 ){ ?>
<div class="ps-scrollbar-y-rail" style="top: 0px; right: 3px; height: 230px; display: inherit;"><div class="ps-scrollbar-y" style="top: 11px; height: 200px;"></div></div>
<?php } ?>
<?php if($nbOldProjects==0 && $nbProjectsVisible==0) {?>
<div id="info" class="padding-10">
<blockquote>
<!--Créez des projets ...-->
<?php echo Yii::t("project","Create or Contribute <br>Build Things<br>Find Help<br>Organize<br>Local or distant<br>Projects") ?>
</blockquote>
</div>
<?php } ?>
<?php if($nbProjectsVisible==0 && $nbOldProjects > 0) {?>
<div id="infoLastButNotNew" class="padding-10">
<blockquote>
<?php echo Yii::t("project","Create new projects <br>To show your current activity<br>And what's happened around people") ?>
</blockquote>
</div>
<?php } ?>
</div>
</div>
</div>
<script type="text/javascript">
var nbOldProjects = <?php echo (String) @$nbOldProjects;?>;
jQuery(document).ready(function() {
if (nbOldProjects == 0) $("#showHideOldProject").hide();
bindBtnRemoveProject();
});
function bindBtnRemoveProject() {
$(".removeProjectbtn").off().on("click",function () {
$(".disconnectBtnIcon").removeClass("fa-unlink").addClass("fa-spinner fa-spin");
var idProject = $(this).data("id");
bootbox.confirm("Are you sure you want to delete <span class='text-grey'>"+$(this).data("name")+"</span> project ?",
function(result) {
if (!result) {
$(".disconnectBtnIcon").removeClass("fa-spinner fa-spin").addClass("fa-unlink");
return;
}
mylog.log(idProject);
$.ajax({
type: "POST",
url: baseUrl+"/"+moduleId+"/project/removeproject/projectId/"+idProject+"",
dataType: "json",
success: function(data){
if ( data && data.result ) {
toastr.info("PROJECT REMOVED SUCCESFULLY!!");
$("#project"+idProject).remove();
if ($("#projects tr").length == 0) {
$("#info").show();
}
} else {
toastr.error(data.msg);
}
},
error: function(data) {
toastr.error("Something went wrong!! Contact your administrator");
}
});
});
$(".disconnectBtnIcon").removeClass("fa-spinner fa-spin").addClass("fa-unlink");
});
}
function toogleOldProject() {
$(".oldProject").toggle("slow");
$("#infoLastButNotNew").toggle("slow");
}
</script>
|
pixelhumain/co2
|
views/pod/projectsList.php
|
PHP
|
apache-2.0
| 5,856
|
#XMVideo
>
>1,数据源来自jsoup爬虫
>2,线程控制使用rxjava+rxandroid
>3,使用md控件
>4,数据库使用realm
>5,图片使用Glide
#程序截图

### 关于我
<a href="https://github.com/ximencx" target="_blank">github主页-ximencx</a> | <a href="mailto:454366460@qq.com" target="_blank">个人邮箱:454366460@qq.com</a> |<a href="http://blog.csdn.net/ximencx" target="_blank"> CSDN博客:ximencx</a>
## License
Copyright 2015 ximencx
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.
|
ximencx/XMVideo
|
README.md
|
Markdown
|
apache-2.0
| 1,115
|
/**
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.bitcoin.core;
import java.util.List;
/**
* Default no-op implementation of {@link BlockChainListener}.
*/
public class AbstractBlockChainListener implements BlockChainListener {
@Override
public void notifyNewBestBlock(StoredBlock block) throws VerificationException {
}
@Override
public void reorganize(StoredBlock splitPoint, List<StoredBlock> oldBlocks, List<StoredBlock> newBlocks) throws VerificationException {
}
@Override
public boolean isTransactionRelevant(Transaction tx) throws ScriptException {
return false;
}
@Override
public void receiveFromBlock(Transaction tx, StoredBlock block, SPVBlockChain.NewBlockType blockType,
int relativityOffset) throws VerificationException {
}
@Override
public void notifyTransactionIsInBlock(Sha256Hash txHash, StoredBlock block, SPVBlockChain.NewBlockType blockType,
int relativityOffset) throws VerificationException {
}
}
|
PeterNSteinmetz/peternsteinmetz-bitcoinj
|
core/src/main/java/com/google/bitcoin/core/AbstractBlockChainListener.java
|
Java
|
apache-2.0
| 1,639
|
# Sloanea forrestii W.W.Sm. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Oxalidales/Elaeocarpaceae/Sloanea/Sloanea forrestii/README.md
|
Markdown
|
apache-2.0
| 175
|
# Oligomeris spathulata E.Mey. ex Harv. & Sond. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Brassicales/Resedaceae/Oligomeris/Oligomeris spathulata/README.md
|
Markdown
|
apache-2.0
| 195
|
# Aureobasidium pullulans var. melanigenum Herm.-Nijh. VARIETY
#### Status
SYNONYM
#### According to
Index Fungorum
#### Published in
null
#### Original name
Aureobasidium pullulans var. melanigenum Herm.-Nijh.
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Ascomycota/Dothideomycetes/Dothideales/Dothioraceae/Aureobasidium/Aureobasidium pullulans/ Syn. Aureobasidium pullulans melanigenum/README.md
|
Markdown
|
apache-2.0
| 232
|
# Hypoderma hederae (T. Nees ex Mart.) De Not., 1847 SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
G. bot. ital. 2(7-8): 36 (1847)
#### Original name
Hysterium hederae T. Nees ex Mart., 1817
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Ascomycota/Leotiomycetes/Rhytismatales/Rhytismataceae/Hypoderma/Hypoderma hederae/README.md
|
Markdown
|
apache-2.0
| 271
|
# Arabisphaera Hemer & Nygreen GENUS
#### Status
ACCEPTED
#### According to
World Register of Marine Species
#### Published in
Micropaleontology 13: 186.
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Protozoa/Acritarcha/Arabisphaera/README.md
|
Markdown
|
apache-2.0
| 199
|
# Cuscuta domingensis Urb. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Solanales/Convolvulaceae/Cuscuta/Cuscuta domingensis/README.md
|
Markdown
|
apache-2.0
| 174
|
# Matthiola parviflora var. maris-mortui Zohary VARIETY
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Brassicales/Brassicaceae/Matthiola/Matthiola parviflora/ Syn. Matthiola parviflora maris-mortui/README.md
|
Markdown
|
apache-2.0
| 202
|
# Polycarpon urbanianum Muschl. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Caryophyllaceae/Polycarpon/Polycarpon urbanianum/README.md
|
Markdown
|
apache-2.0
| 179
|
# Sphaeria favacea Fr., 1823 SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
Sphaeria favacea Fr., 1823
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Ascomycota/Sordariomycetes/Xylariales/Diatrypaceae/Diatrypella/Diatrypella favacea/ Syn. Sphaeria favacea/README.md
|
Markdown
|
apache-2.0
| 205
|
# Pteromimosa hemiendyta (Rose & Robinson) Britton SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Mimosa/Mimosa bahamensis/ Syn. Pteromimosa hemiendyta/README.md
|
Markdown
|
apache-2.0
| 205
|
# Ixora yaouhensis Schltr. SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Ixora/Ixora yaouhensis/README.md
|
Markdown
|
apache-2.0
| 182
|
# Sciniatosporium sicynum (Thüm.) Morgan-Jones SPECIES
#### Status
ACCEPTED
#### According to
Index Fungorum
#### Published in
Can. J. Bot. 49(6): 1005 (1971)
#### Original name
Sporidesmium sicynum Thüm.
### Remarks
null
|
mdoering/backbone
|
life/Fungi/Ascomycota/Sordariomycetes/Xylariales/Amphisphaeriaceae/Sciniatosporium/Sciniatosporium sicynum/README.md
|
Markdown
|
apache-2.0
| 228
|
# Geranium parodii I.M. Johnst. SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Geraniales/Geraniaceae/Geranium/Geranium parodii/README.md
|
Markdown
|
apache-2.0
| 187
|
# Spirotheca passifloroides Cuatrec. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Malvales/Bombacaceae/Spirotheca/Spirotheca passifloroides/README.md
|
Markdown
|
apache-2.0
| 184
|
# Nonatelia varians (Thwaites) Kuntze SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Lasianthus/Lasianthus varians/ Syn. Nonatelia varians/README.md
|
Markdown
|
apache-2.0
| 192
|
# Sarotheca Nees GENUS
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Acanthaceae/Sarotheca/README.md
|
Markdown
|
apache-2.0
| 162
|
# Fremya speciosa Brongn. & Gris SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Myrtales/Myrtaceae/Xanthostemon/Xanthostemon gugerlii/ Syn. Fremya speciosa/README.md
|
Markdown
|
apache-2.0
| 187
|
# Polypodium dryopteris var. disjunctum Rupr. VARIETY
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Pteridophyta/Polypodiopsida/Polypodiales/Polypodiaceae/Polypodium/Polypodium dryopteris/Polypodium dryopteris disjunctum/README.md
|
Markdown
|
apache-2.0
| 193
|
# Calytrix faucicola Craven SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Myrtales/Myrtaceae/Calytrix/Calytrix faucicola/README.md
|
Markdown
|
apache-2.0
| 183
|
using System;
using System.Collections.Generic;
using System.Xml;
namespace FluentTc.Locators
{
public interface IMoreOptionsHavingBuilder
{
IMoreOptionsHavingBuilder WithCleanSources();
IMoreOptionsHavingBuilder RebuildAllDependencies();
IMoreOptionsHavingBuilder QueueAtTop();
IMoreOptionsHavingBuilder AsPersonal();
IMoreOptionsHavingBuilder WithComment(string comment);
}
internal class MoreOptionsHavingBuilder : IMoreOptionsHavingBuilder
{
private string m_Comment;
private readonly TriggeringOptions m_TriggeringOptions;
public MoreOptionsHavingBuilder()
{
m_TriggeringOptions = new TriggeringOptions();
}
public IMoreOptionsHavingBuilder WithCleanSources()
{
// <triggeringOptions cleanSources="true"/>
m_TriggeringOptions.CleanSources = true;
return this;
}
public IMoreOptionsHavingBuilder RebuildAllDependencies()
{
// <triggeringOptions rebuildAllDependencies="true"/>
m_TriggeringOptions.RebuildAllDependencies = true;
return this;
}
public IMoreOptionsHavingBuilder QueueAtTop()
{
// <triggeringOptions queueAtTop="true"/>
m_TriggeringOptions.QueueAtTop = true;
return this;
}
public IMoreOptionsHavingBuilder AsPersonal()
{
m_TriggeringOptions.Personal = true;
return this;
}
public IMoreOptionsHavingBuilder WithComment(string comment)
{
m_Comment = comment;
return this;
}
public string GetComment()
{
return m_Comment;
}
public TriggeringOptions TriggeringOptions
{
get { return m_TriggeringOptions; }
}
}
public class TriggeringOptions
{
public bool? QueueAtTop { get; set; }
public bool? RebuildAllDependencies { get; set; }
public bool? CleanSources { get; set; }
public bool? Personal { get; set; }
}
}
|
GibbOne/FluentTc
|
FluentTc/Locators/MoreOptionsHavingBuilder.cs
|
C#
|
apache-2.0
| 2,146
|
# Pact junit runner
## Dependency
The library is available on maven central using:
* group-id = `au.com.dius.pact.provider`
* artifact-id = `junit`
* version-id = `4.1.x`
## Overview
Library provides ability to play contract tests against a provider service in JUnit fashionable way.
Supports:
- Out-of-the-box convenient ways to load pacts
- Easy way to change assertion strategy
- **org.junit.BeforeClass**, **org.junit.AfterClass** and **org.junit.ClassRule** JUnit annotations, that will be run
once - before/after whole contract test suite.
- **org.junit.Before**, **org.junit.After** and **org.junit.Rule** JUnit annotations, that will be run before/after
each test of an interaction.
- **au.com.dius.pact.provider.junit.State** custom annotation - before each interaction that requires a state change,
all methods annotated by `@State` with appropriate the state listed will be invoked. These methods must either take
no parameters or a single Map parameter.
## Example of HTTP test
```java
@RunWith(PactRunner.class) // Say JUnit to run tests with custom Runner
@Provider("myAwesomeService") // Set up name of tested provider
@PactFolder("pacts") // Point where to find pacts (See also section Pacts source in documentation)
public class ContractTest {
// NOTE: this is just an example of embedded service that listens to requests, you should start here real service
@ClassRule //Rule will be applied once: before/after whole contract test suite
public static final ClientDriverRule embeddedService = new ClientDriverRule(8332);
@BeforeClass //Method will be run once: before whole contract test suite
public static void setUpService() {
//Run DB, create schema
//Run service
//...
}
@Before //Method will be run before each test of interaction
public void before() {
// Rest data
// Mock dependent service responses
// ...
embeddedService.addExpectation(
onRequestTo("/data"), giveEmptyResponse()
);
}
@State("default", "no-data") // Method will be run before testing interactions that require "default" or "no-data" state
public void toDefaultState() {
// Prepare service before interaction that require "default" state
// ...
System.out.println("Now service in default state");
}
@State("with-data") // Method will be run before testing interactions that require "with-data" state
public void toStateWithData(Map data) {
// Prepare service before interaction that require "with-data" state. The provider state data will be passed
// in the data parameter
// ...
System.out.println("Now service in state using data " + data);
}
@TestTarget // Annotation denotes Target that will be used for tests
public final Target target = new HttpTarget(8332); // Out-of-the-box implementation of Target (for more information take a look at Test Target section)
}
```
## Example of Message test
```java
@RunWith(PactRunner.class) // Say JUnit to run tests with custom Runner
@Provider("myAwesomeService") // Set up name of tested provider
@PactBroker(host="pactbroker", port = "80")
public class ConfirmationKafkaContractTest {
@TestTarget // Annotation denotes Target that will be used for tests
public final Target target = new MessageTarget(); // Out-of-the-box implementation of Target (for more information take a look at Test Target section)
@BeforeClass //Method will be run once: before whole contract test suite
public static void setUpService() {
//Run DB, create schema
//Run service
//...
}
@Before //Method will be run before each test of interaction
public void before() {
// Message data preparation
// ...
}
@PactVerifyProvider('an order confirmation message')
String verifyMessageForOrder() {
Order order = new Order()
order.setId(10000004)
order.setPrice(BigDecimal.TEN)
order.setUnits(15)
def message = new ConfirmationKafkaMessageBuilder()
.withOrder(order)
.build()
JsonOutput.toJson(message)
}
}
```
### Example of Message test that verifies metadata
To have the message metadata - such as the topic - also verified you need to return a `MessageAndMetadata` from
the invoked method that contains the payload and metadata to be validation. For example, to verify the metadata of an
integration using the Spring [Message](https://docs.spring.io/spring-integration/reference/html/message.html) interface,
you can do something like the following:
```java
...
@PactVerifyProvider("a product event update")
public MessageAndMetadata verifyMessageForOrder() {
ProductEvent product = new ProductEvent("id1", "product name", "product type", "v1", EventType.CREATED);
Message<String> message = new ProductMessageBuilder().withProduct(product).build();
return generateMessageAndMetadata(message);
}
private MessageAndMetadata generateMessageAndMetadata(Message<String> message) {
HashMap<String, Object> metadata = new HashMap<String, Object>();
message.getHeaders().forEach((k, v) -> metadata.put(k, v));
return new MessageAndMetadata(message.getPayload().getBytes(), metadata);
}
```
_NOTE: this requires you to add medadata expections in your consumer test_
## Provider state callback methods
For the provider states in the pact being verified, you can define methods to be invoked to setup the correct state
for each interaction. Just annotate a method with the `au.com.dius.pact.provider.junit.State` annotation and the
method will be invoked before the interaction is verified.
For example:
```java
@State("SomeProviderState") // Must match the state description in the pact file
public void someProviderState() {
// Do what you need to set the correct state
}
```
If there are parameters in the pact file, just add a Map parameter to the method to be able to access those parameters.
```java
@State("SomeProviderState")
public void someProviderState(Map<String, Object> providerStateParameters) {
// Do what you need to set the correct state
}
```
### Provider state teardown methods
If you need to tear down your provider state, you can annotate a method with the `@State` annotation with the action
set to `StateChangeAction.TEARDOWN` and it will be invoked after the interaction is verified.
```java
@State("SomeProviderState", action = StateChangeAction.TEARDOWN)
public void someProviderStateCleanup() {
// Do what you need to to teardown the state
}
```
#### Returning values that can be injected
You can have values from the provider state callbacks be injected into most places (paths, query parameters, headers,
bodies, etc.). This works by using the V3 spec generators with provider state callbacks that return values. One example
of where this would be useful is API calls that require an ID which would be auto-generated by the database on the
provider side, so there is no way to know what the ID would be beforehand.
There are methods on the consumer DSLs that can provider an expression that contains variables (like '/api/user/${id}'
for the path). The provider state callback can then return a map for values, and the `id` attribute from the map will
be expanded in the expression. For this to work, just make your provider state method return a Map of the values.
### Using multiple classes for the state change methods
If you have a large number of state change methods, you can split things up by moving them to other classes. There are
two ways you can do this:
#### Use interfaces
You can put the state change methods on interfaces and then have your test class implement those interfaces.
See [StateAnnotationsOnInterfaceTest](https://github.com/DiUS/pact-jvm/blob/master/provider/junit/src/test/java/au/com/dius/pact/provider/junit/StateAnnotationsOnInterfaceTest.java)
for an example.
#### Specify the additional classes on the test target
You can provide the additional classes to the test target with the `withStateHandler` or `setStateHandlers` methods. See
[BooksPactProviderTest](https://github.com/DiUS/pact-jvm/blob/master/provider/spring/src/test/java/au/com/dius/pact/provider/spring/BooksPactProviderTest.java) for an example.
## Pact source
The Pact runner will automatically collect pacts based on annotations on the test class. For this purpose there are 3
out-of-the-box options (files from a directory, files from a set of URLs or a pact broker) or you can easily add your
own Pact source.
If you need to load a single pact file from the file system, use the `PactUrl` with the URL set to the file path.
**Note:** You can only define one source of pacts per test class.
### Download pacts from a pact-broker
To use pacts from a Pact Broker, annotate the test class with `@PactBroker(host="host.of.pact.broker.com", port = "80")`.
You can also specify the protocol, which defaults to "http".
The pact broker will be queried for all pacts with the same name as the provider annotation.
For example, test all pacts for the "Activity Service" in the pact broker:
```java
@RunWith(PactRunner.class)
@Provider("Activity Service")
@PactBroker(host = "localhost", port = "80")
public class PactJUnitTest {
@TestTarget
public final Target target = new HttpTarget(5050);
}
```
#### Using Java System properties
The pact broker loader was updated to allow system properties to be used for the hostname, port or protocol. The port
was changed to a string to allow expressions to be set.
To use a system property or environment variable, you can place the property name in `${}` expression de-markers:
```java
@PactBroker(host="${pactbroker.hostname}", port = "80")
```
You can provide a default value by separating the property name with a colon (`:`):
```java
@PactBroker(host="${pactbroker.hostname:localhost}", port = "80")
```
#### More Java System properties
The default values of the `@PactBroker` annotation now enable variable interpolation.
The following keys may be managed through the environment
* `pactbroker.host`
* `pactbroker.port`
* `pactbroker.scheme`
* `pactbroker.tags` (comma separated)
* `pactbroker.auth.username` (for basic auth)
* `pactbroker.auth.password` (for basic auth)
* `pactbroker.auth.token` (for bearer auth)
* `pactbroker.consumers` (comma separated list to filter pacts by consumer; if not provided, will fetch all pacts for the provider)
#### Using tags with the pact broker
The pact broker allows different versions to be tagged. To load all the pacts:
```java
@PactBroker(host="pactbroker", port = "80", tags = {"latest", "dev", "prod"})
```
The default value for tags is `latest` which is not actually a tag but instead corresponds to the latest version ignoring the tags. If there are multiple consumers matching the name specified in the provider annotation then the latest pact for each of the consumers is loaded.
For any other value the latest pact tagged with the specified tag is loaded.
Specifying multiple tags is an OR operation. For example if you specify `tags = {"dev", "prod"}` then both the latest pact file tagged with `dev` and the latest pact file taggged with `prod` is loaded.
In 4.1.4+, tags was deprecated in favor of consumerVersionSelectors. Consumer version selectors give you the ability to
include pacts for the latest version of a tag, or all versions of a tag.
```java
@PactBroker(
host="pactbroker",
port="80",
consumerVersionSelectors={
@ConsumerVersionSelector(tag = "dev"), // Verify the latest version tagged with dev
@ConsumerVersionSelector(tag = "prod", latest = "false") // Verify all versions tagged with prod
}
)
```
#### Using authentication with the with the pact broker
You can use basic authentication with the `@PactBroker` annotation by setting the `authentication` value to a `@PactBrokerAuth`
annotation. For example:
```java
@PactBroker(host = "${pactbroker.url:localhost}", port = "1234", tags = {"latest", "prod", "dev"},
authentication = @PactBrokerAuth(username = "test", password = "test"))
```
Bearer tokens are also supported. For example:
```java
@PactBroker(host = "${pactbroker.url:localhost}", port = "1234", tags = {"latest", "prod", "dev"},
authentication = @PactBrokerAuth(token = "test"))
```
The `token`, `username` and `password` values also take Java system property expressions.
Preemptive Authentication can be enabled by setting the `pact.pactbroker.httpclient.usePreemptiveAuthentication` Java
system property to `true`.
### Allowing just the changed pact specified in a webhook to be verified [4.0.6+]
When a consumer publishes a new version of a pact file, the Pact broker can fire off a webhook with the URL of the changed
pact file. To allow only the changed pact file to be verified, you can override the URL by adding the annotation
`@AllowOverridePactUrl` to your test class and then setting using the `pact.filter.consumers` and `pact.filter.pacturl`
values as either Java system properties or environment variables. If you have annotated your test class with `@Consumer`
you don't need to provide `pact.filter.consumers`.
### Pact Url
To use pacts from urls annotate the test class with
```java
@PactUrl(urls = {"http://build.server/zoo_app-animal_service.json"})
```
If you need to load a single pact file from the file system, you can use the `PactUrl` with the URL set to the file path.
For authenticated URLs, specify the authentication on the annotation
```java
@PactUrl(urls = {"http://build.server/zoo_app-animal_service.json"}, authentication = @Authentication(token = "1234ABCD"))
```
You can use either bearer token scheme (by setting the `token`), or basic auth by setting the `username` and `password`.
JVM system properties or environment variables can also be used by placing the property/variable name in `${}` expressions.
```java
@PactUrl(urls = {"http://build.server/zoo_app-animal_service.json"}, authentication = @Authentication(token = "${TOKEN}"))
```
### Pact folder
To use pacts from a resource folder of the project annotate test class with
```java
@PactFolder("subfolder/in/resource/directory")
```
### Custom pacts source
It's possible to use a custom Pact source. For this, implement interface `au.com.dius.pact.provider.junit.loader.PactLoader`
and annotate the test class with `@PactSource(MyOwnPactLoader.class)`. **Note:** class `MyOwnPactLoader` must have a default empty constructor or a constructor with one argument of class `Class` which at runtime will be the test class so you can get custom annotations of test class.
### Filtering the interactions that are verified
By default, the pact runner will verify all pacts for the given provider. You can filter the pacts and interactions by
the following methods.
#### Filtering by Consumer
You can run only those pacts for a particular consumer by adding a `@Consumer` annotation to the test class.
For example:
```java
@RunWith(PactRunner.class)
@Provider("Activity Service")
@Consumer("Activity Consumer")
@PactBroker(host = "localhost", port = "80")
public class PactJUnitTest {
@TestTarget
public final Target target = new HttpTarget(5050);
}
```
#### Interaction Filtering
You can filter the interactions that are executed by adding a `@PactFilter` annotation to your test class. The pact
filter annotation will then only verify interactions that have a matching value, by default provider state.
You can provide multiple values to match with.
The filter criteria is defined by the filter property. The filter must implement the
`au.com.dius.pact.provider.junit.filter.InteractionFilter` interface. Also check the `InteractionFilter` interface
for default filter implementations.
For example:
```java
@RunWith(PactRunner.class)
@PactFilter("Activity 100 exists in the database")
public class PactJUnitTest {
}
```
You can also use regular expressions with the filter. For example:
```java
@RunWith(PactRunner.class)
@PactFilter(values = {"^\\/somepath.*"}, filter = InteractionFilter.ByRequestPath.class)
public class PactJUnitTest {
}
```
**NOTE!** You will only be able to publish the verification results if all interactions have been verified. If an interaction is not covered because it was filtered out, you will not be able to publish.
##### Filtering the interactions that are run
**(version 4.1.2+)**
You can filter the interactions that are run by setting the JVM system property `pact.filter.description`. This propery
takes a regular expression to match against the interaction description.
**NOTE!** this property needs to be set on the test JVM if your build is running with Gradle or Maven.
### Setting the test to not fail when no pacts are found
By default the pact runner will fail the verification test if no pact files are found to verify. To change the
failure into a warning, add a `@IgnoreNoPactsToVerify` annotation to your test class.
#### Ignoring IO errors loading pact files
You can also set the test to ignore any IO and parser exceptions when loading the pact files by setting the
`ignoreIoErrors` attribute on the annotation to `"true"` or setting the JVM system property `pact.verification.ignoreIoErrors`
to `true`.
** WARNING! Do not enable this on your CI server, as this could result in your build passing with no providers
having been verified due to a configuration error. **
### Overriding the handling of a body data type
**NOTE: version 4.1.3+**
By default, bodies will be handled based on their content types. For binary contents, the bodies will be base64
encoded when written to the Pact file and then decoded again when the file is loaded. You can change this with
an override property: `pact.content_type.override.<TYPE>.<SUBTYPE>=text|binary`. For instance, setting
`pact.content_type.override.application.pdf=text` will treat PDF bodies as a text type and not encode/decode them.
## Test target
The field in test class of type `au.com.dius.pact.provider.junit.target.Target` annotated with `au.com.dius.pact.provider.junit.target.TestTarget`
will be used for actual Interaction execution and asserting of contract.
**Note:** there must be exactly 1 such field, otherwise an `InitializationException` will be thrown.
### HttpTarget
`au.com.dius.pact.provider.junit.target.HttpTarget` - out-of-the-box implementation of `au.com.dius.pact.provider.junit.target.Target`
that will play pacts as http request and assert response from service by matching rules from pact.
You can also specify the protocol, defaults to "http".
### MessageTarget
`au.com.dius.pact.provider.junit.target.MessageTarget` - out-of-the-box implementation of `au.com.dius.pact.provider.junit.target.Target`
that will play pacts as an message and assert response from service by matching rules from pact.
**Note for Maven users:** If you use Maven to run your tests, you will have to make sure that the Maven Surefire plugin is at least
version 2.22.1 uses an isolated classpath.
For example, configure it by adding the following to your POM:
```xml
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
<configuration>
<useSystemClassLoader>false</useSystemClassLoader>
</configuration>
</plugin>
```
#### Modifying the requests before they are sent
**NOTE: `@TargetRequestFilter` is only for JUnit 4. For JUnit 5 see [JUnit 5 docs](/provider/junit5/README.md#modifying-the-requests-before-they-are-sent).**
Sometimes you may need to add things to the requests that can't be persisted in a pact file. Examples of these would
be authentication tokens, which have a small life span. The HttpTarget supports request filters by annotating methods
on the test class with `@TargetRequestFilter`. These methods must be public void methods that take a single HttpRequest
parameter.
For example:
```java
@TargetRequestFilter
public void exampleRequestFilter(HttpRequest request) {
request.addHeader("Authorization", "OAUTH hdsagasjhgdjashgdah...");
}
```
__*Important Note:*__ You should only use this feature for things that can not be persisted in the pact file. By modifying
the request, you are potentially modifying the contract from the consumer tests!
#### Turning off URL decoding of the paths in the pact file
By default the paths loaded from the pact file will be decoded before the request is sent to the provider. To turn this
behaviour off, set the system property `pact.verifier.disableUrlPathDecoding` to `true`.
__*Important Note:*__ If you turn off the url path decoding, you need to ensure that the paths in the pact files are
correctly encoded. The verifier will not be able to make a request with an invalid encoded path.
### Custom Test Target
It's possible to use custom `Target`, for that interface `Target` should be implemented and this class can be used instead of `HttpTarget`.
# Verification Reports
The default test behaviour is to display the verification being done to the console, and pass or fail the test via the normal
JUnit mechanism. Additional reports can be generated from the tests.
## Enabling additional reports via annotations on the test classes
A `@VerificationReports` annotation can be added to any pact test class which will control the verification output. The
annotation takes a list report types and an optional report directory (defaults to "target/pact/reports").
The currently supported report types are `console`, `markdown` and `json`.
For example:
```java
@VerificationReports({"console", "markdown"})
public class MyPactTest {
```
will enable the markdown report in addition to the normal console output. And,
```java
@VerificationReports(value = {"markdown"}, reportDir = "/myreports")
public class MyPactTest {
```
will disable the normal console output and write the markdown reports to "/myreports".
## Enabling additional reports via Java system properties or environment variables
The additional reports can also be enabled with Java System properties or environment variables. The following two
properties have been introduced: `pact.verification.reports` and `pact.verification.reportDir`.
`pact.verification.reports` is the comma separated list of report types to enable (e.g. `console,json,markdown`).
`pact.verification.reportDir` is the directory to write reports to (defaults to "target/pact/reports").
## Additional Reports
The following report types are available in addition to console output (`console`, which is enabled by default):
`markdown`, `json`.
You can also provide a fully qualified classname as report so custom reports are also supported.
This class must implement `au.com.dius.pact.provider.reporters.VerifierReporter` interface in order to be correct custom implementation of a report.
# Publishing verification results to a Pact Broker
For pacts that are loaded from a Pact Broker, the results of running the verification can be published back to the
broker against the URL for the pact. You will be able to see the result on the Pact Broker home screen. You need to
set the version of the provider that is verified using the `pact.provider.version` system property.
To enable publishing of results, set the Java system property or environment variable `pact.verifier.publishResults` to `true`.
## Tagging the provider before verification results are published [4.0.1+]
You can have a tag pushed against the provider version before the verification results are published. To do this
you need set the `pact.provider.tag` JVM system property to the tag value.
From 4.1.8+, you can specify multiple tags with a comma separated string for the `pact.provider.tag`
system property.
# Pending Pact Support (version 4.1.3 and later)
If your Pact broker supports pending pacts, you can enable support for that by enabling that on your Pact broker annotation or with JVM system properties. You also need to provide the tags that will be published with your provider's verification results. The broker will then label any pacts found that don't have a successful verification result as pending. That way, if they fail verification, the verifier will ignore those failures and not fail the build.
For example, with annotation:
```java
@Provider("Activity Service")
@PactBroker(host = "test.pactflow.io", tags = {"test"}, scheme = "https",
enablePendingPacts = "true",
providerTags = "master"
)
public class PactJUnitTest {
```
You can also use the `pactbroker.enablePending` and `pactbroker.providerTags` JVM system properties.
Then any pending pacts will not cause a build failure.
# Work In Progress (WIP) Pact Support (version 4.1.5 and later)
If your Pact broker supports wip pacts, you can enable support by enabling it on your Pact broker annotation, or with
JVM system properties. You also need to enable pending pacts. Once enabled, your provider will verify any "work in progress"
pacts that have been published since a given date. A WIP pact is a pact that is the latest for its tag that does not have
any successful verification results with the provider tag.
```java
@Provider("Activity Service")
@PactBroker(host = "test.pactflow.io", tags = {"test"}, scheme = "https",
enablePendingPacts = "true",
providerTags = "master"
includeWipPactsSince = "2020-06-19"
)
public class PactJUnitTest {
```
You can also use the `pactbroker.includeWipPactsSince` JVM system property.
Since all WIP pacts are also pending pacts, failed verifications will not cause a build failure.
|
DiUS/pact-jvm
|
provider/junit/README.md
|
Markdown
|
apache-2.0
| 25,878
|
/* DbProperties.scala
Copyright 2011 Tommy Skodje (http://www.antares.no)
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 no.antares.dbunit
import org.slf4j.{LoggerFactory, Logger}
import java.sql.{DriverManager, Connection}
import org.dbunit.database.{IDatabaseConnection, DatabaseConnection}
import java.util.Properties
import collection.mutable.ListBuffer
/** Simple wrapper for Database connection db.
@author Tommy Skodje
*/
class DbProperties(
val driver: String,
val dbUrl: String,
val username: String,
val password: String,
val schema: String
) extends Db {
def this( driver: String, dbUrl: String, username: String, password: String ) = this( driver, dbUrl, username, password, "" );
private final val logger: Logger = LoggerFactory.getLogger( classOf[DbWrapper] )
loadDriver( driver );
val connectionProperties = new Properties();
connectionProperties.put( "user", username );
connectionProperties.put( "username", username );
connectionProperties.put( "password", password );
protected val dbConnection: Connection = DriverManager.getConnection( dbUrl, connectionProperties );
override def runSqlScript( script: String ): Boolean = {
val runner = new ScriptRunner( driver, dbUrl, username, password );
doInTransaction { () => runner.executeSql( script ) }
}
override def getDbUnitConnection(): IDatabaseConnection = {
val dbuConnection =
if ( schema.isEmpty )
new DatabaseConnection( dbConnection );
else
new DatabaseConnection( dbConnection, schema );
val config = dbuConnection.getConfig();
dbUnitProperties.foreach( property => config.setProperty( property._1, property._2 ) );
dbuConnection
}
/**
* Loads the appropriate JDBC driver for this environment/framework. For
* example, if we are in an embedded environment, we load Derby's
* embedded Driver, <code>org.apache.derby.jdbc.EmbeddedDriver</code>.
*/
private def loadDriver( driver: String ): Unit = {
/*
* The JDBC driver is loaded by loading its class.
* If you are using JDBC 4.0 (Java SE 6) or newer, JDBC drivers may
* be automatically loaded, making this code optional.
*
* In an embedded environment, this will also start up the Derby
* engine (though not any databases), since it is not already
* running. In a client environment, the Derby engine is being run
* by the network server framework.
*
* In an embedded environment, any static Derby system db
* must be set before loading the driver to take effect.
*/
try {
Class.forName(driver).newInstance();
logger.debug( "Loaded the appropriate driver" );
} catch {
case ex: ClassNotFoundException => {
logger.error( "\nUnable to load the JDBC driver " + driver + "\nPlease check your CLASSPATH." , ex );
}
case ex: InstantiationException => {
logger.error( "\nUnable to instantiate the JDBC driver " + driver, ex );
}
case ex: IllegalAccessException => {
logger.error( "\nNot allowed to access the JDBC driver " + driver, ex );
}
}
}
}
|
2my/test-data-control
|
src/main/scala/no/antares/dbunit/DbProperties.scala
|
Scala
|
apache-2.0
| 3,658
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/iottwinmaker/model/OrderByTime.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>
using namespace Aws::Utils;
namespace Aws
{
namespace IoTTwinMaker
{
namespace Model
{
namespace OrderByTimeMapper
{
static const int ASCENDING_HASH = HashingUtils::HashString("ASCENDING");
static const int DESCENDING_HASH = HashingUtils::HashString("DESCENDING");
OrderByTime GetOrderByTimeForName(const Aws::String& name)
{
int hashCode = HashingUtils::HashString(name.c_str());
if (hashCode == ASCENDING_HASH)
{
return OrderByTime::ASCENDING;
}
else if (hashCode == DESCENDING_HASH)
{
return OrderByTime::DESCENDING;
}
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
overflowContainer->StoreOverflow(hashCode, name);
return static_cast<OrderByTime>(hashCode);
}
return OrderByTime::NOT_SET;
}
Aws::String GetNameForOrderByTime(OrderByTime enumValue)
{
switch(enumValue)
{
case OrderByTime::ASCENDING:
return "ASCENDING";
case OrderByTime::DESCENDING:
return "DESCENDING";
default:
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
}
return {};
}
}
} // namespace OrderByTimeMapper
} // namespace Model
} // namespace IoTTwinMaker
} // namespace Aws
|
aws/aws-sdk-cpp
|
aws-cpp-sdk-iottwinmaker/source/model/OrderByTime.cpp
|
C++
|
apache-2.0
| 1,969
|
package com.vectorprint.configuration.binding;
/*-
* #%L
* Config
* %%
* Copyright (C) 2015 - 2018 VectorPrint
* %%
* 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.
* #L%
*/
import java.util.ServiceLoader;
/**
* Completely stateless and Threadsafe helper class for (de)serialization.
*
* @see #getInstance() that uses ServiceLoader mechanism
*/
public interface BindingHelper {
ServiceLoader<BindingHelper> loader = ServiceLoader.load(BindingHelper.class);
/**
* returns the first BindingHelper found by {@link #loader}.
* @return
*/
public static BindingHelper getInstance() {
return loader.iterator().next();
}
/**
* use this from {@link #serializeValue(java.lang.Object) } if you need to
* escape syntax specific characters. Note that overriding only this method
* when extending {@link AbstractBindingHelperDecorator} will not work,
* because the overridden method will not be called by the encapsulated
* {@link BindingHelper}.
*
* @see #setEscapeChars(char[])
* @param value
* @return
*/
public String escape(String value);
/**
* set characters to be escaped, do this from the constructors when
* extending {@link AbstractBindingHelperDecorator}.
*
* @param chars
*/
public void setEscapeChars(char[] chars);
/**
* supports arrays of primitives and their wrappers, enums, URL, Color,
* Date, Pattern and String
*
* @param <T>
* @param values
* @param clazz
* @return
*/
<T> T convert(String[] values, Class<T> clazz);
/**
* supports primitives and their wrappers, enums, URL, Color, Date, Pattern
* and String
*
* @param <T>
* @param value
* @param clazz
* @return
*/
<T> T convert(String value, Class<T> clazz);
/**
* set separator to be used for array values, do this from the constructors
* when extending {@link AbstractBindingHelperDecorator}.
*
* @param separator
*/
public void setArrayValueSeparator(char separator);
char getArrayValueSeparator();
/**
* Serialize Objects and arrays of Objects and primitives in a specific
* syntax. Array values will be separated by the
* {@link #setArrayValueSeparator(char) separator}.
*
* @param value
* @return the String
*/
String serializeValue(Object value);
}
|
eduarddrenth/Configuration
|
src/main/java/com/vectorprint/configuration/binding/BindingHelper.java
|
Java
|
apache-2.0
| 2,956
|
#pragma once
#include "Holder.h"
#include "CircularBuffer.h"
|
Silexars/VeritasAudio
|
include/Veritas/Audio/Utils/Utils.h
|
C
|
apache-2.0
| 63
|
#include "Blaziken.h"
#include "j1App.h"
#include "j1Pathfinding.h"
#include "j1Audio.h"
#include "j1Scene.h"
#include "j1Gui.h"
#include "j1GuiEntity.h"
#include "j1GuiElements.h"
Blaziken::Blaziken()
{
type = CREATURE;
}
Blaziken::~Blaziken()
{
}
bool Blaziken::Awake(pugi::xml_node &conf)
{
std::string temp = conf.attribute("dir").as_string("");
if (temp == "up")
direction = UP;
else if (temp == "down")
direction = DOWN;
else if (temp == "left")
direction = LEFT;
else
direction = RIGHT;
cooldown = conf.attribute("cooldown").as_int(0);
hp = conf.attribute("hp").as_int(0);
attack = conf.attribute("attack").as_int(0);
speed = conf.attribute("speed").as_int(0);
name = conf.attribute("name").as_string("");
position.x = conf.attribute("pos_x").as_int(0);
position.y = conf.attribute("pos_y").as_int(0);
active = conf.attribute("active").as_bool(false);
sp_damage = conf.attribute("special_attack").as_int(0);
defense = conf.attribute("defense").as_int(0);
return true;
}
bool Blaziken::Start()
{
state = PC_IDLE;
anim_state = PC_IDLE;
scale = App->win->GetScale();
offset_x = 7;
offset_y = 17;
timetoplay = SDL_GetTicks();
movable = true;
collision_feet = App->collision->AddCollider({ position.x - offset_x, position.y - offset_y, 15, 15 }, COLLIDER_POKECOMBAT, this);
timetoplay = SDL_GetTicks();
reset_distance = false;
sp_attacking = false;
reset_run = true;
return true;
}
bool Blaziken::Update(float dt)
{
BROFILER_CATEGORY("Upcate_Collision", Profiler::Color::Lime);
// STATE MACHINE ------------------
if (App->scene->gamestate == INGAME)
{
//pokemon controlled by player
switch (state)
{
case PC_IDLE:
{
Idle();
break;
}
case PC_WALKING:
{
Walking(dt);
break;
}
case PC_ATTACKING:
{
Attack();
break;
}
case PC_SPECIAL:
{
Special_Attack();
break;
}
case PC_HIT:
{
Movebyhit(4);
break;
}
case PC_STUNNED:
{
Stunned();
break;
}
case PC_COLLISION:
{
Movebyhit(1);
break;
}
default:
{
break;
}
}
}
else if (App->scene->gamestate == INMENU)
{
}
if (App->combatmanager->pokemon_active_trainer->name != "DUSCLOPS")
{
dusclops_special = false;
}
if (dusclops_special == false && App->combatmanager->pokemon_active_trainer->name == "DUSCLOPS" && App->combatmanager->pokemon_active_trainer->Special_inUse())
{
dusclops_special = true;
autoAttack.Start();
}
if (dusclops_special)
{
if (autoAttack.ReadSec() > 0.5)
{
autoAttack.Start();
hp -= 5;
App->scene->pokecombat->GetDamage(1, true);
}
}
//Collision follow the player
collision_feet->SetPos(position.x - offset_x, position.y - offset_y);
return true;
}
void Blaziken::Draw()
{
BROFILER_CATEGORY("Draw_Blaziquen", Profiler::Color::HotPink);
App->anim_manager->Drawing_Manager(anim_state, direction, position, BLAZIKEN);
}
bool Blaziken::CleanUp()
{
return true;
}
void Blaziken::OnCollision(Collider* c1, Collider* c2)
{
if (c1 != nullptr && c2 != nullptr)
{
PokemonCombat* pokemon_1 = (PokemonCombat*)c1->callback;
PokemonCombat* pokemon_2 = (PokemonCombat*)c2->callback;
if (pokemon_1 != nullptr && pokemon_2 != nullptr)
{
if (pokemon_1->active && pokemon_2->active)
{
if (c1 == sp_attack && c2->type == COLLIDER_POKECOMBAT && getdamage == false && pokemon_2->GetState() != PC_SPECIAL)
{
pokemon_2->knockback_time.Start();
pokemon_2->hp -= sp_damage;
getdamage = true;
App->scene->pokecombat->GetDamage(sp_damage, false);
pokemon_2->SetState(PC_HIT);
pokemon_2->SetAnimState(PC_HIT);
pokemon_2->dir_hit = c1->callback->direction;
pokemon_2->prev_position = pokemon_2->position;
}
if (c1 == collision_attack && c2->type == COLLIDER_POKECOMBAT && getdamage == false && pokemon_2->GetState() != PC_SPECIAL)
{
pokemon_2->knockback_time.Start();
pokemon_2->hp -= attack;
getdamage = true;
App->scene->pokecombat->GetDamage(attack, false);
pokemon_2->SetState(PC_HIT);
pokemon_2->SetAnimState(PC_HIT);
pokemon_2->dir_hit = c1->callback->direction;
pokemon_2->prev_position = pokemon_2->position;
}
if (c1 == collision_feet && c2->type == COLLIDER_POKECOMBAT)
{
state = PC_COLLISION;
anim_state = PC_IDLE;
dir_hit = pokemon_2->direction;
knockback_time.Start();
if (pokemon_2->GetState() != PC_SPECIAL)
{
pokemon_2->SetState(PC_COLLISION);
pokemon_2->SetAnimState(PC_IDLE);
if (pokemon_2->direction == UP)
{
pokemon_2->dir_hit = DOWN;
}
else if (pokemon_2->direction == DOWN)
{
pokemon_2->dir_hit = UP;
}
else if (pokemon_2->direction == RIGHT)
{
pokemon_2->dir_hit = LEFT;
}
else
{
pokemon_2->dir_hit = RIGHT;
}
pokemon_2->knockback_time.Start();
}
}
}
}
}
}
bool Blaziken::Idle()
{
//IDLE BLAZIKEN
if (App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MLEFT) == EVENTSTATE::E_REPEAT ||
App->input->GetKey(SDL_SCANCODE_DOWN) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MDOWN) == EVENTSTATE::E_REPEAT ||
App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MRIGHT) == EVENTSTATE::E_REPEAT ||
App->input->GetKey(SDL_SCANCODE_UP) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MUP) == EVENTSTATE::E_REPEAT)
{
state = PC_WALKING;
anim_state = PC_WALKING;
}
else if (App->input->GetKey(SDL_SCANCODE_Q) == KEY_DOWN || App->input_manager->EventPressed(INPUTEVENT::BUTTON_B) == EVENTSTATE::E_DOWN)
{
if (App->scene->pokecombat->cooldown == false)
{
App->scene->pokecombat->cooldown = true;
state = PC_SPECIAL;
anim_state = PC_SPECIAL;
current_animation = App->anim_manager->GetAnimation(anim_state, direction, BLAZIKEN);
current_animation->Reset();
App->scene->pokecombat->cdtime.y = App->scene->pokecombat->cdtime.x;
}
}
else if (App->input->GetKey(SDL_SCANCODE_E) == KEY_DOWN || App->input_manager->EventPressed(INPUTEVENT::BUTTON_X) == EVENTSTATE::E_DOWN)
{
state = PC_ATTACKING;
anim_state = PC_ATTACKING;
current_animation = App->anim_manager->GetAnimation(anim_state, direction, BLAZIKEN);
current_animation->Reset();
}
else
{
state = PC_IDLE;
anim_state = PC_IDLE;
}
return true;
}
bool Blaziken::Walking(float dt)
{
walking = false;
Move(dt);
if (walking == false)
{
state = PC_IDLE;
anim_state = PC_IDLE;
}
else if (App->input->GetKey(SDL_SCANCODE_Q) == KEY_DOWN || App->input_manager->EventPressed(INPUTEVENT::BUTTON_B) == EVENTSTATE::E_DOWN)
{
if (App->scene->pokecombat->cooldown == false)
{
App->scene->pokecombat->cooldown = true;
state = PC_SPECIAL;
anim_state = PC_SPECIAL;
current_animation = App->anim_manager->GetAnimation(anim_state, direction, BLAZIKEN);
current_animation->Reset();
App->scene->pokecombat->cdtime.y = App->scene->pokecombat->cdtime.x;
}
}
else if (App->input->GetKey(SDL_SCANCODE_E) == KEY_DOWN || App->input_manager->EventPressed(INPUTEVENT::BUTTON_X) == EVENTSTATE::E_DOWN)
{
state = PC_ATTACKING;
anim_state = PC_ATTACKING;
current_animation = App->anim_manager->GetAnimation(anim_state, direction, BLAZIKEN);
current_animation->Reset();
}
else
{
state = PC_WALKING;
anim_state = PC_WALKING;
}
return false;
}
bool Blaziken::Move(float dt)
{
if (App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MLEFT) == EVENTSTATE::E_REPEAT)
{
direction = LEFT;
int temp = App->map->MovementCost(collision_feet->rect.x - speed, collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, LEFT);
if (temp == 0)
{
position.x -= speed;
}
walking = true;
}
if (App->input->GetKey(SDL_SCANCODE_DOWN) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MDOWN) == EVENTSTATE::E_REPEAT)
{
direction = DOWN;
int temp = App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y + collision_feet->rect.h + speed, collision_feet->rect.w, collision_feet->rect.h, DOWN);
if (temp == 0)
{
position.y += speed;
}
walking = true;
}
if (App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MRIGHT) == EVENTSTATE::E_REPEAT)
{
direction = RIGHT;
int temp = App->map->MovementCost(collision_feet->rect.x + collision_feet->rect.w + speed, collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, RIGHT);
if (temp == 0)
{
position.x += speed;
}
walking = true;
}
if (App->input->GetKey(SDL_SCANCODE_UP) == KEY_REPEAT || App->input_manager->EventPressed(INPUTEVENT::MUP) == EVENTSTATE::E_REPEAT)
{
direction = UP;
//int temp = App->map->MovementCost(position.x, position.y - speed, UP);
int temp = App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y - speed, collision_feet->rect.w, collision_feet->rect.h, UP);
if (temp == 0)
{
position.y -= speed;
}
walking = true;
}
return walking;
}
bool Blaziken::Attack()
{
if (attacker)
{
if (current_animation->Finished())
{
App->collision->EraseCollider(collision_attack);
collision_attack = nullptr;
attacker = false;
current_animation->Reset();
current_animation = nullptr;
state = PC_IDLE;
anim_state = PC_IDLE;
if (getdamage)
{
getdamage = false;
}
}
}
else
{
attacker = true;
if (direction == UP)
{
collision_attack = App->collision->AddCollider({ position.x - 11, position.y - 35, 22, 8 }, COLLIDER_POKEMON_ATTACK, this);
}
else if (direction == RIGHT)
{
collision_attack = App->collision->AddCollider({ position.x + 15, position.y - 26, 8, 22 }, COLLIDER_POKEMON_ATTACK, this);
}
else if (direction == DOWN)
{
collision_attack = App->collision->AddCollider({ position.x - 10, position.y, 22, 8 }, COLLIDER_POKEMON_ATTACK, this);
}
else if (direction == LEFT)
{
collision_attack = App->collision->AddCollider({ position.x - 23, position.y - 26, 8, 22 }, COLLIDER_POKEMON_ATTACK, this);
}
App->audio->PlayFx(9);
}
return true;
}
bool Blaziken::Special_Attack()
{
if (sp_attacking)
{
if (current_animation->Finished())
{
App->collision->EraseCollider(sp_attack);
sp_attacking = false;
current_animation->Reset();
current_animation = nullptr;
state = PC_IDLE;
anim_state = PC_IDLE;
if (getdamage)
{
getdamage = false;
}
}
}
else
{
sp_attacking = true;
if (direction == UP)
{
sp_attack = App->collision->AddCollider({ position.x - 11, position.y - 35, 22, 8 }, COLLIDER_POKEMON_SPECIAL_ATTACK, this);
}
else if (direction == RIGHT)
{
sp_attack = App->collision->AddCollider({ position.x + 15, position.y - 26, 8, 22 }, COLLIDER_POKEMON_SPECIAL_ATTACK, this);
}
else if (direction == DOWN)
{
sp_attack = App->collision->AddCollider({ position.x - 10, position.y, 22, 8 }, COLLIDER_POKEMON_SPECIAL_ATTACK, this);
}
else if (direction == LEFT)
{
sp_attack = App->collision->AddCollider({ position.x - 23, position.y - 26, 8, 22 }, COLLIDER_POKEMON_SPECIAL_ATTACK, this);
}
App->audio->PlayFx(7);
}
return true;
}
void Blaziken::Stunned()
{
if (hp <= 0)
{
state = PC_DYING;
anim_state = PC_DYING;
}
else
{
if (time_stunned.ReadSec() >= 1)
{
state = PC_IDLE;
anim_state = PC_IDLE;
}
if (dir_hit == UP)
{
if (App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y - 4, collision_feet->rect.w, collision_feet->rect.h, UP) == 0)
{
position.y -= 2;
}
}
else if (dir_hit == DOWN)
{
if (App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y + collision_feet->rect.h + 4, collision_feet->rect.w, collision_feet->rect.h, DOWN) == 0)
{
position.y += 2;
}
}
else if (dir_hit == LEFT)
{
if (App->map->MovementCost(collision_feet->rect.x - 4, collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, LEFT) == 0)
{
position.x -= 2;
}
}
else if (dir_hit == RIGHT)
{
if (App->map->MovementCost(collision_feet->rect.x + collision_feet->rect.w + 4, collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, RIGHT) == 0)
{
position.x += 2;
}
}
}
}
bool Blaziken::Movebyhit(int speed)
{
if (hp <= 0)
{
state = PC_DYING;
anim_state = PC_DYING;
return true;
}
if (knockback_time.ReadSec() >= 0.2)
{
state = PC_IDLE;
anim_state = PC_IDLE;
return true;
}
if (dir_hit == UP)
{
if (App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y - 4, collision_feet->rect.w, collision_feet->rect.h, UP) == 0)
{
position.y -= speed;
}
}
else if (dir_hit == DOWN)
{
if (App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y + collision_feet->rect.h + 4, collision_feet->rect.w, collision_feet->rect.h, DOWN) == 0)
{
position.y += speed;
}
}
else if (dir_hit == LEFT)
{
if (App->map->MovementCost(collision_feet->rect.x - 4, collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, LEFT) == 0)
{
position.x -= speed;
}
}
else if (dir_hit == RIGHT)
{
if (App->map->MovementCost(collision_feet->rect.x + collision_feet->rect.w + 4, collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, RIGHT) == 0)
{
position.x += speed;
}
}
/*if (position.x > (prev_position.x + 65) ||
position.x < (prev_position.x + 65) ||
position.y >(prev_position.y + 65) ||
position.y < (prev_position.y + 65))
{
state = IDLE;
}*/
return true;
}
|
NontendoSL/Zelda-a-Link-to-the-Past-TRIBUTE
|
Motor2D/Blaziken.cpp
|
C++
|
apache-2.0
| 13,635
|
/*
* Copyright 2013 Gregory Graham.
*
* 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 nz.co.gregs.dbvolution.databases.definitions;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LineSegment;
import com.vividsolutions.jts.geom.Polygon;
import com.vividsolutions.jts.geom.LineString;
import com.vividsolutions.jts.geom.MultiPoint;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.io.WKTReader;
import java.sql.ResultSet;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import nz.co.gregs.dbvolution.DBDatabase;
import nz.co.gregs.dbvolution.DBRecursiveQuery;
import nz.co.gregs.dbvolution.DBRow;
import nz.co.gregs.dbvolution.datatypes.DBInteger;
import nz.co.gregs.dbvolution.datatypes.DBNumber;
import nz.co.gregs.dbvolution.datatypes.QueryableDatatype;
import nz.co.gregs.dbvolution.datatypes.spatial2D.DBLine2D;
import nz.co.gregs.dbvolution.datatypes.spatial2D.DBMultiPoint2D;
import nz.co.gregs.dbvolution.datatypes.spatial2D.DBPoint2D;
import nz.co.gregs.dbvolution.datatypes.spatial2D.DBPolygon2D;
import nz.co.gregs.dbvolution.exceptions.AutoIncrementFieldClassAndDatatypeMismatch;
import nz.co.gregs.dbvolution.exceptions.IncorrectGeometryReturnedForDatatype;
import nz.co.gregs.dbvolution.expressions.DBExpression;
import nz.co.gregs.dbvolution.expressions.DateRepeatExpression;
import nz.co.gregs.dbvolution.expressions.NumberExpression;
import nz.co.gregs.dbvolution.expressions.StringExpression;
import nz.co.gregs.dbvolution.generation.DBTableClassGenerator;
import nz.co.gregs.dbvolution.generation.DBTableField;
import nz.co.gregs.dbvolution.internal.datatypes.DateRepeatImpl;
import nz.co.gregs.dbvolution.internal.properties.PropertyWrapper;
import nz.co.gregs.dbvolution.query.QueryOptions;
import nz.co.gregs.dbvolution.query.RowDefinition;
import nz.co.gregs.dbvolution.results.Line2DResult;
import org.joda.time.Period;
/**
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @author Gregory Graham
*/
public abstract class DBDefinition {
/**
* Transforms the Date instance into a SQL snippet that can be used as a date
* in a query.
*
* <p>
* For instance the date might be transformed into a string like "
* DATETIME('2013-03-23 00:00:00') "
*
* @param date date
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the date formatted as a string that the database will correctly
* interpret as a date.
*/
public abstract String getDateFormattedForQuery(Date date);
/**
* Transforms the Date instance into UTC time zone date.
*
* @param date the local date to be rolled to UTC.
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL that creates this Date as a UTC date in the database.
*/
@SuppressWarnings("deprecation")
public String getUTCDateFormattedForQuery(Date date) {
Double zoneOffset = (0.0 + date.getTimezoneOffset()) / 60.0;
int hourPart = zoneOffset.intValue() * 100;
int minutePart = (int) ((zoneOffset - (zoneOffset.intValue())) * 60);
return doAddMinutesTransform(doAddHoursTransform(getDateFormattedForQuery(date), "" + hourPart), "" + minutePart);
}
/**
* Formats the raw column name to the required convention of the database.
*
* <p>
* The default implementation does not change the column name.
*
* @param columnName columnName
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the column name formatted for the database.
*/
public String formatColumnName(String columnName) {
return formatNameForDatabase(columnName);
}
/**
* Returns the standard beginning of a string value in the database.
*
* <p>
* The default method returns "'", that is a single quote.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the formatting required at the beginning of a string value.
*/
public String beginStringValue() {
return "'";
}
/**
* Returns the standard ending of a string value in the database.
*
* <p>
* The default method returns "'", that is a single quote.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the formatting required at the end of a string value.
*/
public String endStringValue() {
return "'";
}
/**
* Returns the standard beginning of a number value in the database.
*
* <p>
* The default method returns "", that is an empty string.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the formatting required at the beginning of a number value.
*/
public String beginNumberValue() {
return "";
}
/**
* Returns the standard end of a number value in the database.
*
* <p>
* The default method returns "", that is an empty string.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the formatting required at the end of a number value.
*/
public String endNumberValue() {
return "";
}
/**
*
* Formats the table and column name pair correctly for this database.
*
* <p>
* This should only be used for column names in the select query when aliases
* are not being used. Which is probably never.
* <p>
* e.g table, column => TABLE.COLUMN
*
* @param table table
* @param columnName columnName
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a string of the table and column name for the select clause
*/
public String formatTableAndColumnName(DBRow table, String columnName) {
return formatTableName(table) + "." + formatColumnName(columnName);
}
/**
*
* Formats the table alias and column name pair correctly for this database.
* <p>
* This should be used for column names in the select query.
* <p>
* e.g table, column => TABLEALIAS.COLUMN
*
* @param table table
* @param columnName columnName
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a string of the table and column name for the select clause
*/
public String formatTableAliasAndColumnName(RowDefinition table, String columnName) {
return getTableAlias(table) + "." + formatColumnName(columnName);
}
/**
*
* Formats the table and column name pair correctly for this database
*
* This should be used for column names in the select clause, that is to say
* between SELECT and FROM
*
* e.g table, column => TABLEALIAS.COLUMN COLUMNALIAS
*
* @param table table
* @param columnName columnName
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a string of the table and column name for the select clause
*/
public String formatTableAliasAndColumnNameForSelectClause(DBRow table, String columnName) {
final String tableAliasAndColumn = formatTableAliasAndColumnName(table, columnName);
return tableAliasAndColumn + " " + formatForColumnAlias(tableAliasAndColumn);
}
/**
* Formats the table name correctly for this database.
*
* <p>
* Used wherever a table alias is inappropriate, for instance UPDATE
* statements.
*
* @param table table
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a string of the table name formatted for this database definition
*/
public String formatTableName(DBRow table) {
return formatNameForDatabase(table.getTableName());
}
/**
* Provides the column name as named in the SELECT clause and ResultSet.
*
* <p>
* This is the column alias that matches the result to the query. It must be
* consistent, unique, and deterministic.
*
* @param table table
* @param columnName columnName
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the table alias and the column name formatted correctly for this
* database.
*/
public String formatColumnNameForDBQueryResultSet(RowDefinition table, String columnName) {
final String actualName = formatTableAliasAndColumnName(table, columnName);
return formatForColumnAlias(actualName);
}
/**
* Apply standard formatting of the column alias to avoid issues with the
* database's column naming issues.
*
* @param actualName actualName
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the column alias formatted for this database.
*/
public String formatForColumnAlias(final String actualName) {
String formattedName = actualName.replaceAll("\\.", "__");
return formatNameForDatabase("DB" + formattedName.hashCode()).replaceAll("-", "_");
}
/**
* Apply standard object name transformations required by the database.
*
* <p>
* This methods helps support database specific naming rules by allowing
* post-processing of the object names to conform to the rules.
*
* @param sqlObjectName the Java object name to be transformed into a database
* object name.
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the object name formatted for use with this database
*/
protected String formatNameForDatabase(final String sqlObjectName) {
return sqlObjectName;
}
/**
* Apply standard formatting of the expression alias to avoid issues with the
* database's alias naming issues.
*
* @param key key
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the alias of the key formatted correctly.
*/
public String formatExpressionAlias(Object key) {
return ("DB" + key.hashCode()).replaceAll("-", "_");
}
/**
* Apply necessary transformations on the string to avoid it being used for an
* SQL injection attack.
*
* <p>
* The default method changes every single quote (') into 2 single quotes
* ('').
*
* @param toString toString
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the string value safely escaped for use in an SQL query.
*/
public String safeString(String toString) {
return toString.replaceAll("'", "''");
}
/**
*
* returns the required SQL to begin a line within the WHERE or ON Clause for
* conditions.
*
* usually, but not always " and "
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a string for the start of a where clause line
*/
public String beginWhereClauseLine() {
return beginAndLine();
}
/**
*
* returns the required SQL to begin a line within the WHERE or ON Clause for
* conditions.
*
* usually, but not always " and "
*
* @param options options
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a string for the start of a where clause line
*/
public String beginConditionClauseLine(QueryOptions options) {
if (options.isMatchAllConditions()) {
return beginAndLine();
} else {
return beginOrLine();
}
}
/**
*
* returns the required SQL to begin a line within the WHERE or ON Clause for
* joins.
*
* usually, but not always " and "
*
* @param options options
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a string for the start of a where clause line
*/
public String beginJoinClauseLine(QueryOptions options) {
if (options.isMatchAllRelationships()) {
return beginAndLine();
} else {
return beginOrLine();
}
}
/**
* Indicates that the database does not accept named GROUP BY columns and the
* query generator should create the GROUP BY clause using indexes instead.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return TRUE if the database needs indexes for the group by columns, FALSE
* otherwise.
*/
public boolean prefersIndexBasedGroupByClause() {
return false;
}
/**
* Returns the start of an AND line for this database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return " AND " or the equivalent for this database.
*/
public String beginAndLine() {
return " AND ";
}
/**
* Returns the start of an OR line for this database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return " OR " or the equivalent for this database.
*/
public String beginOrLine() {
return " OR ";
}
/**
* Provides the start of the DROP TABLE expression for this database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "DROP TABLE " or equivalent for the database.
*/
public String getDropTableStart() {
return "DROP TABLE ";
}
/**
* Returns the start of the PRIMARY KEY clause of the CREATE TABLE statement.
*
* <p>
* This is the clause within the column definition clause after the columns
* themselves, i.e. CREATE TABLE tab (col integer<b>, PRIMARY KEY(col)</b>)
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return ", PRIMARY KEY (" or the equivalent for this database.
*/
public String getCreateTablePrimaryKeyClauseStart() {
return ",PRIMARY KEY (";
}
/**
* Returns the separator between the columns in the PRIMARY KEY clause of the
* CREATE TABLE statement.
*
* <p>
* This is the clause within the column definition clause after the columns
* themselves, i.e. CREATE TABLE tab (col integer<b>, PRIMARY KEY(col)</b>)
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return ", " or the equivalent for this database.
*/
public String getCreateTablePrimaryKeyClauseMiddle() {
return ", ";
}
/**
* Returns the conclusion of the PRIMARY KEY clause of the CREATE TABLE
* statement.
*
* <p>
* This is the clause within the column definition clause after the columns
* themselves, i.e. CREATE TABLE tab (col integer<b>, PRIMARY KEY(col)</b>)
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return ")" or the equivalent for this database.
*/
public String getCreateTablePrimaryKeyClauseEnd() {
return ")";
}
/**
* Returns the start of the CREATE TABLE statement.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "CREATE TABLE " or the equivalent for this database.
*/
public String getCreateTableStart() {
return "CREATE TABLE ";
}
/**
* Returns the start of the column list within the CREATE TABLE statement.
*
* <p>
* This is the clause within the CREATE TABLE that defines the columns
* themselves, i.e. CREATE TABLE tab <b>(col integer, PRIMARY KEY(col))</b>
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "(" or the equivalent for this database.
*/
public String getCreateTableColumnsStart() {
return "(";
}
/**
* Returns the separator between column definitions in the column list of the
* CREATE TABLE statement.
*
* <p>
* This is the clause within the CREATE TABLE that defines the columns
* themselves, i.e. CREATE TABLE tab <b>(col integer, PRIMARY KEY(col))</b>
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return ", " or the equivalent for this database.
*/
public String getCreateTableColumnsSeparator() {
return ", ";
}
/**
* Returns the separator between the column name and the column datatype
* within the column definitions in the column list of the CREATE TABLE
* statement.
*
* <p>
* This is the clause within the CREATE TABLE that defines the columns
* themselves, i.e. CREATE TABLE tab <b>(col integer, PRIMARY KEY(col))</b>
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return " " or the equivalent for this database.
*/
public String getCreateTableColumnsNameAndTypeSeparator() {
return " ";
}
/**
* Returns the end of the column list within the CREATE TABLE statement.
*
* <p>
* This is the clause within the CREATE TABLE that defines the columns
* themselves, i.e. CREATE TABLE tab <b>(col integer, PRIMARY KEY(col))</b>
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return ")" or the equivalent for this database.
*/
public Object getCreateTableColumnsEnd() {
return ")";
}
/**
* Wraps the SQL snippet provided in the LOWER operator of the database.
*
* @param sql sql
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return " lower("+string+")"
*/
public String toLowerCase(String sql) {
return " lower(" + sql + ")";
}
/**
* Returns the beginning of an INSERT statement for this database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "INSERT INTO " or equivalent.
*/
public String beginInsertLine() {
return "INSERT INTO ";
}
/**
* Returns the end of an INSERT statement for this database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return ";" or equivalent.
*/
public String endInsertLine() {
return ";";
}
/**
* Returns the beginning of the column list of an INSERT statement for this
* database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "(" or equivalent.
*/
public String beginInsertColumnList() {
return "(";
}
/**
* Returns the end of the column list of an INSERT statement for this
* database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return ") " or equivalent.
*/
public String endInsertColumnList() {
return ") ";
}
/**
* Returns the beginning of a DELETE statement for this database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "DELETE FROM " or equivalent.
*/
public String beginDeleteLine() {
return "DELETE FROM ";
}
/**
* Returns the end of a DELETE statement for this database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return ";" or equivalent.
*/
public String endDeleteLine() {
return ";";
}
/**
* The EQUALS operator for this database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return " = " or equivalent
*/
public String getEqualsComparator() {
return " = ";
}
/**
* The NOT EQUALS operator for this database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return " <> " or equivalent
*/
public String getNotEqualsComparator() {
return " <> ";
}
/**
* Returns the beginning of a WHERE clause for this database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return " WHERE " or equivalent.
*/
public String beginWhereClause() {
return " WHERE ";
}
/**
* Returns the beginning of an UPDATE statement for this database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "UPDATE " or equivalent.
*/
public String beginUpdateLine() {
return "UPDATE ";
}
/**
* Returns the beginning of a SET clause of an UPDATE statement for this
* database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return " SET " or equivalent.
*/
public String beginSetClause() {
return " SET ";
}
/**
* Returns the initial separator of a SET sub-clause of an UPDATE statement
* for this database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "" or equivalent.
*/
public String getStartingSetSubClauseSeparator() {
return "";
}
/**
* Returns the subsequent separator of a SET sub-clause of an UPDATE statement
* for this database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "," or equivalent.
*/
public String getSubsequentSetSubClauseSeparator() {
return ",";
}
/**
* Returns the initial separator of a ORDER BY sub-clause of a SELECT
* statement for this database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "" or equivalent.
*/
public String getStartingOrderByClauseSeparator() {
return "";
}
/**
* Returns the subsequent separator of a ORDER BY sub-clause of a SELECT
* statement for this database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "," or equivalent.
*/
public String getSubsequentOrderByClauseSeparator() {
return ",";
}
/**
* Returns the initial clause of a WHERE clause of a SELECT statement for this
* database.
*
* <p>
* DBvolution inserts a constant operation to every WHERE clause to simplify
* the production of the query. This method returns a condition that always
* evaluates to true.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a SQL snippet representing a TRUE operation.
* @see #getTrueOperation()
*/
public String getWhereClauseBeginningCondition() {
return getTrueOperation();
}
/**
* Returns the initial clause of a WHERE clause of a SELECT statement for this
* database.
*
* <p>
* DBvolution inserts a constant operation to every WHERE clause to simplify
* the production of the query. This method checks the options parameter and
* returns a TRUE operation or a FALSE operation depending on the query
* requirements.
*
* @param options options
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the required initial condition.
* @see #getTrueOperation()
* @see #getFalseOperation()
*/
public String getWhereClauseBeginningCondition(QueryOptions options) {
if (options.isMatchAllConditions()) {
return getTrueOperation();
} else {
return getFalseOperation();
}
}
/**
* An SQL snippet that always evaluates to FALSE for this database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return " 1=0 " or equivalent
*/
public String getFalseOperation() {
return " (1=0) ";
}
/**
* An SQL snippet that always evaluates to TRUE for this database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return " 1=1 " or equivalent
*/
public String getTrueOperation() {
return " (1=1) ";
}
/**
* An SQL snippet that represents NULL for this database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return " NULL " or equivalent
*/
public String getNull() {
return " NULL ";
}
/**
* Returns the beginning of a SELECT statement for this database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "SELECT " or equivalent.
*/
public String beginSelectStatement() {
return " SELECT ";
}
/**
* Returns the beginning of the FROM clause of a SELECT statement for this
* database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "FROM " or equivalent.
*/
public String beginFromClause() {
return " FROM ";
}
/**
* Returns the default ending of an SQL statement for this database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return ";" or equivalent.
*/
public Object endSQLStatement() {
return ";";
}
/**
* Returns the initial separator of the column list sub-clause of a SELECT
* statement for this database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "" or equivalent.
*/
public String getStartingSelectSubClauseSeparator() {
return "";
}
/**
* Returns the subsequent separator of the column list sub-clause of a SELECT
* statement for this database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "," or equivalent.
*/
public String getSubsequentSelectSubClauseSeparator() {
return ",";
}
/**
* The COUNT(*) clause for this database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "COUNT(*)" or equivalent.
*/
public String countStarClause() {
return " COUNT(*) ";
}
/**
* Provides an opportunity for the definition to insert a row limiting
* statement before the query.
* <p>
* for example H2DB uses SELECT TOP 10 ... FROM ... WHERE ... ;
* <p>
* Based on the example for H2DB this method should return " TOP 10 "
* <p>
* If the database does not support row limiting this method should throw an
* exception when rowLimit is not null
* <p>
* The default implementation returns "".
*
* @param options options
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a string for the row limit sub-clause or ""
*/
public Object getLimitRowsSubClauseDuringSelectClause(QueryOptions options) {
return "";
}
/**
* Returns the beginning of the ORDER BY clause of a SELECT statement for this
* database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return " ORDER BY " or equivalent.
*/
public String beginOrderByClause() {
return " ORDER BY ";
}
/**
* Returns the end of the ORDER BY clause of a SELECT statement for this
* database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return " " or equivalent.
*/
public String endOrderByClause() {
return " ";
}
/**
* Returns the appropriate ascending or descending keyword for this database
* given the sort order.
*
* @param sortOrder sortOrder
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return " ASC " for TRUE, " DESC " for false or equivalent
*/
public Object getOrderByDirectionClause(Boolean sortOrder) {
if (sortOrder == null) {
return "";
} else if (sortOrder) {
return " ASC ";
} else {
return " DESC ";
}
}
/**
* Used during the creation of an ANSI join to add a table with a normal, or
* "required" join.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns " INNER JOIN ".
*/
public String beginInnerJoin() {
return " INNER JOIN ";
}
/**
* Used during the creation of an ANSI join to add an optional table using a
* Left Outer Join.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns " LEFT OUTER JOIN "
*/
public String beginLeftOuterJoin() {
return " LEFT OUTER JOIN ";
}
/**
* Used during the creation of an ANSI join to add an optional table using a
* Full Outer Join.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns " FULL OUTER JOIN ".
*/
public String beginFullOuterJoin() {
return " FULL OUTER JOIN ";
}
/**
* Used during the creation of an ANSI join to add the criteria of an optional
* table using an ON clause.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns " ON( ".
*/
public String beginOnClause() {
return " ON( ";
}
/**
* Used during the creation of an ANSI join to complete the criteria of an
* optional table by closing the ON clause.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns " ) ".
*/
public String endOnClause() {
return " ) ";
}
private String getSQLTypeOfDBDatatype(PropertyWrapper field) {
return getDatabaseDataTypeOfQueryableDatatype(field.getQueryableDatatype());
}
/**
* Supplied to allow the DBDefintion to override the standard QDT datatype.
*
* <p>
* When the
*
* @param qdt qdt
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the databases type for the QDT as a string
*/
protected String getDatabaseDataTypeOfQueryableDatatype(QueryableDatatype qdt) {
return qdt.getSQLDatatype();
}
/**
* Provides an opportunity for the definition to insert a row limiting
* statement after the query
*
* for example MySQL/MariaDB use SELECT ... FROM ... WHERE ... LIMIT 10 ;
*
* Based on the example for MySQL/MariaDB this method should return " LIMIT 10
* "
*
* If the database does not support row limiting this method should throw an
* exception when rowLimit is not null
*
* If the database does not limit rows after the where clause this method
* should return ""
*
* @param options options
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the row limiting sub-clause or ""
*/
public Object getLimitRowsSubClauseAfterWhereClause(QueryOptions options) {
int rowLimit = options.getRowLimit();
Integer pageNumber = options.getPageIndex();
if (rowLimit > 0 && supportsPagingNatively(options)) {
long offset = pageNumber * rowLimit;
return "LIMIT " + rowLimit + " OFFSET " + offset;
} else {
return "";
}
}
/**
*
* The place holder for variables inserted into a prepared statement, usually
* " ? "
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the place holder for variables as a string
*/
public String getPreparedVariableSymbol() {
return " ? ";
}
/**
* Indicates whether this database distinguishes between upper and lowercase
* letters in column names.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns FALSE.
*/
public boolean isColumnNamesCaseSensitive() {
return false;
}
/**
* Used during output of BLOB columns to avoid complications in some
* scenarios.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns "/*"
*/
public String startMultilineComment() {
return "/*";
}
/**
* Used during output of BLOB columns to avoid complications in some
* scenarios.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns "*\/"
*/
public String endMultilineComment() {
return "*/";
}
/**
* Used within DBInsert to start the VALUES clause of the INSERT statement.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns " VALUES( ".
*/
public String beginValueClause() {
return " VALUES ( ";
}
/**
* Used within DBInsert to end the VALUES clause of the INSERT statement.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns " ) ".
*/
public Object endValueClause() {
return ")";
}
/**
* Used within DBInsert to separate the values within the VALUES clause of the
* INSERT statement.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns ",".
*/
public String getValuesClauseValueSeparator() {
return ",";
}
/**
* Used within DBInsert to separate the columns within the INSERT clause of
* the INSERT statement.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns ",".
*/
public String getValuesClauseColumnSeparator() {
return ",";
}
/**
* Used during the creation of ANSI queries to separate the table and its
* alias.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns " AS ".
*/
public String beginTableAlias() {
return " AS ";
}
/**
* Used during the creation of ANSI queries to conclude the table alias.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns " ".
*/
public String endTableAlias() {
return " ";
}
/**
* Transforms the table name into the unique and deterministic table alias.
*
* @param tabRow tabRow
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the table alias.
*/
public String getTableAlias(RowDefinition tabRow) {
return formatTableAlias("" + tabRow.getClass().getSimpleName().hashCode());
}
/**
* Formats the suggested table alias provided by DBvolution for the particular
* database..
*
* @param suggestedTableAlias suggestedTableAlias
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the table alias.
*/
public String formatTableAlias(String suggestedTableAlias) {
return "_" + suggestedTableAlias.replaceAll("-", "_");
}
/**
* Defines the function used to get the current date (excluding time) from the
* database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns " CURRENT_DATE "
*/
protected String getCurrentDateOnlyFunctionName() {
return " CURRENT_DATE";
}
/**
* Defines the function used to get the current timestamp from the database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns " CURRENT_TIMESTAMP "
*/
protected String getCurrentDateTimeFunction() {
return " CURRENT_TIMESTAMP ";
}
/**
* Creates the CURRENTTIMESTAMP function for this database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a String of the SQL required to get the CurrentDateTime value.
*/
public String doCurrentDateTimeTransform() {
return getCurrentDateTimeFunction();
}
/**
* Defines the function used to get the current time from the database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns " CURRENT_TIMESTAMP "
*/
protected String getCurrentTimeFunction() {
return " CURRENT_TIMESTAMP ";
}
/**
* Creates the CURRENTTIME function for this database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a String of the SQL required to get the CurrentTime value.
*/
public String doCurrentTimeTransform() {
return getCurrentTimeFunction();
}
/**
* Provides the SQL statement required to drop the named database.
*
* @param databaseName databaseName
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation does not support dropping databases.
*
*/
public String getDropDatabase(String databaseName) throws UnsupportedOperationException {
throw new UnsupportedOperationException("DROP DATABASE is not supported by this DBDatabase implementation");
}
/**
* Wraps the provided SQL snippet in a statement that performs trims all
* spaces from the left of the value of the snippet.
*
* @param enclosedValue enclosedValue
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL snippet
*/
public String doLeftTrimTransform(String enclosedValue) {
return " LTRIM(" + enclosedValue + ") ";
}
/**
* Wraps the provided SQL snippet in a statement that changes the value of the
* snippet to lowercase characters.
*
* @param enclosedValue enclosedValue
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL snippet
*/
public String doLowercaseTransform(String enclosedValue) {
return " LOWER(" + enclosedValue + ") ";
}
/**
* Wraps the provided SQL snippet in a statement that trims all spaces from
* the right of the value of the snippet.
*
* @param enclosedValue enclosedValue
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL snippet
*/
public String doRightTrimTransform(String enclosedValue) {
return " RTRIM(" + enclosedValue + " )";
}
/**
* Wraps the provided SQL snippet in a statement that the length of the value
* of the snippet.
*
* @param enclosedValue enclosedValue
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL snippet
*/
public String doStringLengthTransform(String enclosedValue) {
return " " + getStringLengthFunctionName() + "( " + enclosedValue + " ) ";
}
/**
* Wraps the provided SQL snippet in a statement that performs trims all
* spaces from the left and right of the value of the snippet.
*
* @param enclosedValue enclosedValue
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL snippet
*/
public String doTrimFunction(String enclosedValue) {
return " TRIM(" + enclosedValue + ") ";
}
/**
* Wraps the provided SQL snippet in a statement that changes the characters
* of the value of the snippet to their uppercase equivalent.
*
* @param enclosedValue enclosedValue
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL snippet
*/
public String doUppercaseTransform(String enclosedValue) {
return " UPPER(" + enclosedValue + ") ";
}
/**
* Wraps the provided SQL snippets in a statement that joins the two snippets
* into one SQL snippet.
*
* @param firstString firstString
* @param secondString secondString
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL snippet
* @see StringExpression#append(java.lang.String)
* @see StringExpression#append(java.lang.Number)
* @see StringExpression#append(nz.co.gregs.dbvolution.results.StringResult)
* @see StringExpression#append(nz.co.gregs.dbvolution.results.NumberResult)
*/
public String doConcatTransform(String firstString, String secondString) {
return firstString + "||" + secondString;
}
/**
* Returns the function name of the function used to return the next value of
* a sequence.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "NEXTVAL"
* @see NumberExpression#getNextSequenceValue(java.lang.String)
* @see NumberExpression#getNextSequenceValue(java.lang.String,
* java.lang.String)
*/
public String getNextSequenceValueFunctionName() {
return "NEXTVAL";
}
/**
* Returns the function name of the function used to remove all the spaces
* padding the end of the value.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "RTRIM"
*/
public String getRightTrimFunctionName() {
return "RTRIM";
}
/**
* Returns the function name of the function used to change the case of all
* the letters in the value to lower case.
*
* <p>
* Usually databases only support lower and upper case functions for ASCII
* characters. Support for change the case of unicode characters is dependent
* on the underlying database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "LOWER"
*/
public String getLowercaseFunctionName() {
return "LOWER";
}
/**
* Returns the function name of the function used to change the case of all
* the letters in the value to upper case.
*
* <p>
* Usually databases only support lower and upper case functions for ASCII
* characters. Support for change the case of unicode characters is dependent
* on the underlying database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "UPPER"
*/
public String getUppercaseFunctionName() {
return "UPPER";
}
/**
* Returns the function name of the function used to determine the number of
* characters in the value.
*
* <p>
* DBvolution tries to ensure that the character length of a value is equal to
* the character length of an equivalent Java String.
*
* <p>
* That is to say: DBV.charlength() === java.lang.String.length()
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "LOWER"
*/
public String getStringLengthFunctionName() {
return "CHAR_LENGTH";
}
/**
* Returns the function used to determine the username of the user currently
* logged into the database.
*
* <p>
* Usually this is the same username supplied when you created the DBDatabase
* instance.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "CURRENT_USER'
*/
public String getCurrentUserFunctionName() {
return "CURRENT_USER";
}
/**
* Transforms a SQL snippet that is assumed to be a date into an SQL snippet
* that provides the year part of the date.
*
* @param dateExpression dateExpression
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a SQL snippet that will produce the year of the supplied date.
*/
public String doYearTransform(String dateExpression) {
return "EXTRACT(YEAR FROM " + dateExpression + ")";
}
/**
* Transforms a SQL snippet that is assumed to be a date into an SQL snippet
* that provides the month part of the date.
*
* @param dateExpression dateExpression
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a SQL snippet that will produce the month of the supplied date.
*/
public String doMonthTransform(String dateExpression) {
return "EXTRACT(MONTH FROM " + dateExpression + ")";
}
/**
* Transforms a SQL snippet that is assumed to be a date into an SQL snippet
* that provides the day part of the date.
*
* <p>
* Day in this sense is the number of the day within the month: that is the 23
* part of Monday 25th of August 2014
*
* @param dateExpression dateExpression
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a SQL snippet that will produce the day of the supplied date.
*/
public String doDayTransform(String dateExpression) {
return "EXTRACT(DAY FROM " + dateExpression + ")";
}
/**
* Transforms a SQL snippet that is assumed to be a date into an SQL snippet
* that provides the hour part of the date.
*
* @param dateExpression dateExpression
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a SQL snippet that will produce the hour of the supplied date.
*/
public String doHourTransform(String dateExpression) {
return "EXTRACT(HOUR FROM " + dateExpression + ")";
}
/**
* Transforms a SQL snippet that is assumed to be a date into an SQL snippet
* that provides the minute part of the date.
*
* @param dateExpression dateExpression
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a SQL snippet that will produce the minute of the supplied date.
*/
public String doMinuteTransform(String dateExpression) {
return "EXTRACT(MINUTE FROM " + dateExpression + ")";
}
/**
* Transforms a SQL snippet that is assumed to be a date into an SQL snippet
* that provides the second part of the date.
*
* @param dateExpression dateExpression
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a SQL snippet that will produce the second of the supplied date.
*/
public String doSecondTransform(String dateExpression) {
return "EXTRACT(SECOND FROM " + dateExpression + ")";
}
/**
* Returns the partial second value from the date.
*
* <p>
* This should return the most detailed possible value less than a second for
* the date expression provided. It should always return a value less than 1s.
*
* @param dateExpression the date from which to get the subsecond part of.
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doSubsecondTransform(String dateExpression) {
return "(EXTRACT(MILLISECOND FROM " + dateExpression + ")/1000.0000)";
}
/**
* Transforms an SQL snippet into an SQL snippet that provides the index of
* the string to find.
*
* @param originalString originalString
* @param stringToFind stringToFind
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a SQL snippet that will produce the index of the find string.
*/
public String doPositionInStringTransform(String originalString, String stringToFind) {
return "POSITION(" + stringToFind + " IN " + originalString + ")";
}
/**
* Provides the function name of the COALESCE, IFNULL, or NVL function.
*
* <p>
* This provides the function name for this database that transforms a NULL
* into another value.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "COALESCE"
*/
public String getIfNullFunctionName() {
return "COALESCE";
}
/**
* Indicates whether the database supports statements that compares to boolean
* values using EQUALS, NOT EQUALS, etc.
*
* <p>
* If the database supports statements that resolve to "true = true", this
* method will return TRUE.
*
* <p>
* Internally this method is used to allow DBvolution to alter the SQL for MS
* SQLServer so that DBBoolean columns can be compared like with other
* databases.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return TRUE if this database can compare boolean values, FALSE otherwise.
*/
public boolean supportsComparingBooleanResults() {
return true;
}
/**
* Returns the function name of the function that negates boolean values.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "NOT"
*/
public String getNegationFunctionName() {
return "NOT";
}
/**
* Provides the separator between GROUP BY clause items.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return ", "
*/
public String getSubsequentGroupBySubClauseSeparator() {
return ", ";
}
/**
* Provides the key words and syntax that start the GROUP BY clause.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return " GROUP BY "
*/
public String beginGroupByClause() {
return " GROUP BY ";
}
/**
* Provides the function of the function that provides the average of a
* selection.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "AVG"
*/
public String getAverageFunctionName() {
return "AVG";
}
/**
* Provides the function of the function that provides the count of items in a
* selection.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "COUNT"
*/
public String getCountFunctionName() {
return "COUNT";
}
/**
* Provides the function of the function that provides the maximum value in a
* selection.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "MAX"
*/
public String getMaxFunctionName() {
return "MAX";
}
/**
* Provides the function of the function that provides the minimum value in a
* selection.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "MIN"
*/
public String getMinFunctionName() {
return "MIN";
}
/**
* Provides the function of the function that provides the sum of a selection.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "SUM"
*/
public String getSumFunctionName() {
return "SUM";
}
/**
* Provides the function of the function that provides the standard deviation
* of a selection.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "stddev"
*/
public String getStandardDeviationFunctionName() {
return "STDDEV";
}
/**
* Indicates whether the database prefers (probably exclusively) the ORDER BY
* clause to use column indexes rather than column names.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns FALSE.
*/
public boolean prefersIndexBasedOrderByClause() {
return false;
}
/**
* Indicates whether the the database supports a form of paging natively.
*
* <p>
* Databases that don't support paging will have paging handled by the java
* side. Unfortunately this causes some problems as the entire dataset will be
* retrieved with the first call, making the first call expensive in time and
* memory. Subsequent calls will be more efficient but that probably won't
* help your developers.
*
* @param options options
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns TRUE.
*/
public boolean supportsPagingNatively(QueryOptions options) {
return true;
}
/**
* Indicates that this database supports the JDBC generated keys API.
*
* <p>
* Generated keys are the preferred method for retrieving auto-increment
* primary keys.
*
* <p>
* Alternatively the DBDefinition can overload {@link #supportsRetrievingLastInsertedRowViaSQL()
* } and {@link #getRetrieveLastInsertedRowSQL() }
*
* <p>
* If both {@link #supportsGeneratedKeys()
* } and {@link #supportsRetrievingLastInsertedRowViaSQL() } return false
* DBvolution will not retrieve auto-incremented primary keys.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return TRUE if this database supports the generated keys API, FLASE
* otherwise.
*/
public boolean supportsGeneratedKeys() {
return true;
}
/**
* Provides the name of the function that removes the decimal part of a real
* number.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "trunc"
*/
public String getTruncFunctionName() {
return "trunc";
}
/**
* Transforms 2 SQL snippets that represent a real number and a integer into a
* real number with the decimal places reduced to the integer.
*
* <p>
* 0 decimal places transforms the real number into an integer.
*
* @param realNumberExpression realNumberExpression
* @param numberOfDecimalPlacesExpression numberOfDecimalPlacesExpression
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return an expression that reduces the realNumberExpression to only the
* number of decimal places in numberOfDecimalPlacesExpression.
*/
public String doTruncTransform(String realNumberExpression, String numberOfDecimalPlacesExpression) {
return getTruncFunctionName() + "(" + realNumberExpression + ", " + numberOfDecimalPlacesExpression + ")";
}
/**
* Returns the SQL required to directly compare 2 strings.
*
* @param firstSQLExpression firstSQLExpression
* @param secondSQLExpression secondSQLExpression
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL snippet comparing the 2 strings
*/
public String doStringEqualsTransform(String firstSQLExpression, String secondSQLExpression) {
return firstSQLExpression + " = " + secondSQLExpression;
}
/**
* Transforms a bit expression into an integer expression.
*
* <p>
* Used to allow comparison of bit columns in some databases.
*
* @param booleanExpression bitExpression
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the transformation necessary to transform bitExpression into an
* integer expression in the SQL.
*/
public String doBooleanToIntegerTransform(String booleanExpression) {
return doIfThenElseTransform(booleanExpression, "" + 1, "" + 0);
}
/**
* Transforms a integer expression into an bit expression.
*
* <p>
* Used to allow comparison of integer columns in some databases.
*
* @param bitExpression bitExpression
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the transformation necessary to transform bitExpression into an
* integer expression in the SQL.
*/
public String doIntegerToBitTransform(String bitExpression) {
return bitExpression;
}
/**
* Returns the suffix added to a column definition to support
* auto-incrementing a column.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return " GENERATED BY DEFAULT AS IDENTITY "
*/
public String getColumnAutoIncrementSuffix() {
return " GENERATED BY DEFAULT AS IDENTITY ";
}
/**
* Indicates whether the database prefers to use triggers and sequences to
* maintain auto-incrementing identities.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns FALSE.
* @see Oracle11XEDBDefinition#prefersTriggerBasedIdentities()
*/
public boolean prefersTriggerBasedIdentities() {
return false;
}
/**
* Provides all the SQL necessary to create a trigger and sequence based
* auto-incrementing identity.
*
* @param db db
* @param table table
* @param column column
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns an empty list.
* @see
* Oracle11XEDBDefinition#getTriggerBasedIdentitySQL(nz.co.gregs.dbvolution.DBDatabase,
* java.lang.String, java.lang.String)
*/
public List<String> getTriggerBasedIdentitySQL(DBDatabase db, String table, String column) {
return new ArrayList<String>();
}
/**
* Provides the SQL type and modifiers required to create the column
* associated with the provided field.
*
* @param field the field of the column being created.
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the datatype and appropriate modifiers.
* @see PropertyWrapper#isAutoIncrement()
* @see
* #propertyWrapperConformsToAutoIncrementType(nz.co.gregs.dbvolution.internal.properties.PropertyWrapper)
* @see #hasSpecialAutoIncrementType()
* @see #getSpecialAutoIncrementType()
* @see
* #getSQLTypeOfDBDatatype(nz.co.gregs.dbvolution.internal.properties.PropertyWrapper)
* @see #getColumnAutoIncrementSuffix()
* @see AutoIncrementFieldClassAndDatatypeMismatch
*/
public final String getSQLTypeAndModifiersOfDBDatatype(PropertyWrapper field) {
if (field.isAutoIncrement()) {
if (propertyWrapperConformsToAutoIncrementType(field)) {
if (hasSpecialAutoIncrementType()) {
return getSpecialAutoIncrementType();
} else if (hasSpecialPrimaryKeyTypeForDBDatatype(field)) {
return getSpecialPrimaryKeyTypeOfDBDatatype(field) + getColumnAutoIncrementSuffix();
} else {
return getSQLTypeOfDBDatatype(field) + getColumnAutoIncrementSuffix();
}
} else {
throw new AutoIncrementFieldClassAndDatatypeMismatch(field);
}
}
if (field.isPrimaryKey()) {
if (hasSpecialPrimaryKeyTypeForDBDatatype(field)) {
return getSpecialPrimaryKeyTypeOfDBDatatype(field);
} else {
return getSQLTypeOfDBDatatype(field);
}
} else {
return getSQLTypeOfDBDatatype(field);
}
}
/**
* Provides the name that DBvolution will use for the sequence of a
* trigger-based auto-increment implementation.
*
* @param table table
* @param column column
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the name of the primary key sequence to be created.
*/
public String getPrimaryKeySequenceName(String table, String column) {
return formatNameForDatabase(table + "_" + column + "dsq");
}
/**
* Provides the name that DBvolution will use for the trigger of a
* trigger-based auto-increment implementation.
*
* @param table table
* @param column column
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the name of the trigger to be created.
*/
public String getPrimaryKeyTriggerName(String table, String column) {
return formatNameForDatabase(table + "_" + column + "dtg");
}
/**
* Indicates whether the database uses a special type for it's auto-increment
* columns.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns FALSE.
*/
protected boolean hasSpecialAutoIncrementType() {
return false;
}
/**
* Indicates whether field provided can be used as a auto-incrementing column
* in this database
*
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return true if the QDT field can be used with this database's
* autoincrement feature.
*/
private boolean propertyWrapperConformsToAutoIncrementType(PropertyWrapper field) {
final QueryableDatatype qdt = field.getQueryableDatatype();
return propertyWrapperConformsToAutoIncrementType(qdt);
}
/**
* Indicates whether {@link QueryableDatatype} provided can be used as a
* auto-incrementing column in this database
*
* @param qdt qdt
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns TRUE for DBNumber or DBString,
* FALSE otherwise.
*/
protected boolean propertyWrapperConformsToAutoIncrementType(QueryableDatatype qdt) {
return (qdt instanceof DBNumber) || (qdt instanceof DBInteger);
}
/**
* Provides the special auto-increment type used by this database if it has
* one.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns ""
*/
protected String getSpecialAutoIncrementType() {
return "";
}
/**
* Indicates whether the database prefers the primary key to be defined at the
* end of the CREATE TABLE statement.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns TRUE.
*/
public boolean prefersTrailingPrimaryKeyDefinition() {
return true;
}
/**
* Indicates whether the database requires LargeObjects to be encoded as
* Base64 CLOBS using the CharacterStream method to read the value.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns FALSE.
*/
public boolean prefersLargeObjectsReadAsBase64CharacterStream() {
return false;
}
/**
* Indicates whether the database prefers reading BLOBs using the getBytes()
* method.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns FALSE
*/
public boolean prefersLargeObjectsReadAsBytes() {
return false;
}
/**
* Indicates whether the database prefers reading BLOBs using the getClob()
* method.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns FALSE
*/
public boolean prefersLargeObjectsReadAsCLOB() {
return false;
}
/**
* Indicates whether the database prefers reading BLOBs using the getBlob()
* method.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns FALSE
*/
public boolean prefersLargeObjectsReadAsBLOB() {
return false;
}
/**
* Transforms the arguments into a SQL snippet that produces a substring of
* the originalString from the start for length characters.
*
* @param originalString originalString
* @param start start
* @param length length
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return an expression that will produce an appropriate substring of the
* originalString.
*/
public String doSubstringTransform(String originalString, String start, String length) {
return " SUBSTRING("
+ originalString
+ " FROM "
+ start
+ (length.trim().isEmpty() ? "" : " FOR " + length)
+ ") ";
}
/**
* Indicates that the database prefers Large Object values to be set using the
* setCharacterStream method.
*
* <p>
* If both {@link #prefersLargeObjectsSetAsCharacterStream() } and
* {@link #prefersLargeObjectsSetAsBase64String()} return FALSE, DBvolution
* will use the setBinaryStream method to set the value.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns FALSE.
*/
public boolean prefersLargeObjectsSetAsCharacterStream() {
return false;
}
/**
* Indicates that the database prefers Large Object values to be set using the
* setBLOB method.
*
* <p>
* If both {@link #prefersLargeObjectsSetAsCharacterStream() } and
* {@link #prefersLargeObjectsSetAsBase64String()} return FALSE, DBvolution
* will use the setBinaryStream method to set the value.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns FALSE.
*/
public boolean prefersLargeObjectsSetAsBLOB() {
return false;
}
/**
* Indicates that the database prefers Large Object values to be set using the
* setCharacterStream method.
*
* <p>
* If both {@link #prefersLargeObjectsSetAsCharacterStream() } and
* {@link #prefersLargeObjectsSetAsBase64String()} return FALSE, DBvolution
* will use the setBinaryStream method to set the value.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns FALSE.
*/
public boolean prefersLargeObjectsSetAsBase64String() {
return false;
}
/**
* Provides the name of the function that will choose the largest value from a
* list of options.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return " GREATEST "
*/
public String getGreatestOfFunctionName() {
return " GREATEST ";
}
/**
* Provides the name of the function that will choose the smallest value from
* a list of options.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return " LEAST "
*/
public String getLeastOfFunctionName() {
return " LEAST ";
}
/**
* Provides Cheeseburger.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a cheeseburger.
*/
public String getCheezBurger() {
return " LOL! De beez dont makes cheezburger.";
}
/**
* Indicates whether the database prefers date values to be read as Strings.
*
* <p>
* Normally dates are read as dates but this method switches DBvolution to
* using a text mode.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns false.
* @see #parseDateFromGetString(java.lang.String)
*/
public boolean prefersDatesReadAsStrings() {
return false;
}
/**
* returns the date format used when reading dates as strings.
*
* <p>
* Normally dates are read as dates but this method allows DBvolution to read
* them using a text mode.
*
* @param getStringDate a date retrieved with {@link ResultSet#getString(java.lang.String)
* }
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return return the date format required to interpret strings as dates.
* @throws java.text.ParseException SimpleDateFormat may throw a parse
* exception
* @see #prefersDatesReadAsStrings()
*/
public Date parseDateFromGetString(String getStringDate) throws ParseException {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(getStringDate);
}
/**
* Provides an opportunity to tweak the generated DBTableField before creating
* the Java classes
*
* @param dbTableField the current field being processed by
* DBTableClassGenerator
*/
@SuppressWarnings("empty-statement")
public void sanityCheckDBTableField(DBTableField dbTableField) {
;
}
/**
* Indicates whether this DBDefinition supports retrieving the primary key of
* the last inserted row using SQL.
*
* <p>
* Preferably the database should support
* {@link #supportsGeneratedKeys() generated keys} but if it doesn't this and {@link #getRetrieveLastInsertedRowSQL()
* }
* allow the DBDefinition to provide raw SQL for retrieving the last created
* primary key.
*
* <p>
* The database should support either generated keys or last inserted row SQL.
*
* <p>
* If both {@link #supportsGeneratedKeys()
* } and {@link #supportsRetrievingLastInsertedRowViaSQL() } return false
* DBvolution will not retrieve auto-incremented primary keys.
*
* <p>
* Originally provided for the SQLite-JDBC driver.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return TRUE if the database supports retrieving the last generated key
* using a SQL script, FALSE otherwise.
*/
public boolean supportsRetrievingLastInsertedRowViaSQL() {
return false;
}
/**
* Provides the SQL required to retrieve that last inserted row if {@link #supportsRetrievingLastInsertedRowViaSQL()
* } returns TRUE.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns "".
*/
public String getRetrieveLastInsertedRowSQL() {
return "";
}
/**
* Provides the database's version of an empty string.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return '' or the database's equivalent.
*/
public String getEmptyString() {
return beginStringValue() + endStringValue();
}
/**
* Indicates whether the database supports the standard DEGREES function.
*
* <p>
* The default implementation returns TRUE.
*
* <p>
* If the database does not support the standard function then the definition
* may override {@link #doDegreesTransform(java.lang.String) } to implement
* the required functionality.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return TRUE if the database supports the standard DEGREES function,
* otherwise FALSE.
*/
public boolean supportsDegreesFunction() {
return true;
}
/**
* Indicates whether the database supports the standard RADIANS function.
*
* <p>
* The default implementation returns TRUE.
*
* <p>
* If the database does not support the standard function then the definition
* may override {@link #doRadiansTransform(java.lang.String) } to implement
* the required functionality.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return TRUE if the database supports the standard RADIANS function,
* otherwise FALSE.
*/
public boolean supportsRadiansFunction() {
return true;
}
/**
* Implements the degrees to radians transformation using simple maths.
*
* <p>
* If the database does not support the standard RADIANS function this method
* provides another method of providing the function.
*
* @param degreesSQL degreesSQL
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the degrees expression transformed into a radians expression
*/
public String doRadiansTransform(String degreesSQL) {
return " (" + degreesSQL + ") * 0.0174532925 ";
}
/**
* Implements the radians to degrees transformation using simple maths.
*
* <p>
* If the database does not support the standard DEGREES function this method
* provides another method of providing the function.
*
* @param radiansSQL radiansSQL
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the radians expression transformed into a degrees expression
*/
public String doDegreesTransform(String radiansSQL) {
return " " + radiansSQL + " * 57.2957795 ";
}
/**
* Provides the name of the function that raises e to the power of the
* provided value.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "EXP"
*/
public String getExpFunctionName() {
return "EXP";
}
/**
* Indicates whether the database has a built-in EXP function.
*
* <p>
* If the database does not support EXP, then DBvolution will use an
* expression to calculate the value.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns TRUE.
*/
public boolean supportsExpFunction() {
return true;
}
/**
* Indicates whether the database supports the standard deviation function.
*
* <p>
* DBvolution will use a terrible approximation of standard deviation if the
* database neither has a built-in function nor supports another method of
* implementing it.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns TRUE.
*/
public boolean supportsStandardDeviationFunction() {
return true;
}
/**
* Indicates whether the database supports the modulus function.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the default implementation returns TRUE.
*/
public boolean supportsModulusFunction() {
return true;
}
/**
* Implements the integer division remainder (mod) function.
*
* @param firstNumber firstNumber
* @param secondNumber secondNumber
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the SQL required to get the integer division remainder.
*/
public String doModulusTransform(String firstNumber, String secondNumber) {
return "(" + firstNumber + ") % (" + secondNumber + ")";
}
/**
* Does the required transformation to produce an SQL snippet that adds
* numberOfSeconds seconds to the dateValue.
*
* @param dateValue dateValue
* @param numberOfSeconds numberOfSeconds
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return an SQL snippet
*/
public String doAddSecondsTransform(String dateValue, String numberOfSeconds) {
return "DATE_ADD(" + dateValue + ", INTERVAL (" + numberOfSeconds + ") SECOND )";
}
/**
* Does the required transformation to produce an SQL snippet that adds
* numberOfMinutes minutes to the dateValue.
*
* @param dateValue dateValue
* @param numberOfMinutes numberOfMinutes
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return an SQL snippet
*/
public String doAddMinutesTransform(String dateValue, String numberOfMinutes) {
return "DATE_ADD(" + dateValue + ", INTERVAL (" + numberOfMinutes + ") MINUTE )";
}
/**
* Does the required transformation to produce an SQL snippet that adds
* numberOfdays days to the dateValue.
*
* @param dateValue dateValue
* @param numberOfDays numberOfDays
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return an SQL snippet
*/
public String doAddDaysTransform(String dateValue, String numberOfDays) {
return "DATE_ADD(" + dateValue + ", INTERVAL (" + numberOfDays + ") DAY )";
}
/**
* Does the required transformation to produce an SQL snippet that adds
* numberOfHours hours to the dateValue.
*
* @param dateValue dateValue
* @param numberOfHours numberOfHours
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return an SQL snippet
*/
public String doAddHoursTransform(String dateValue, String numberOfHours) {
return "DATE_ADD(" + dateValue + ", INTERVAL (" + numberOfHours + ") HOUR )";
}
/**
* Does the required transformation to produce an SQL snippet that adds
* numberOfWeeks weeks to the dateValue.
*
* @param dateValue dateValue
* @param numberOfWeeks numberOfWeeks
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return an SQL snippet
*/
public String doAddWeeksTransform(String dateValue, String numberOfWeeks) {
return "DATE_ADD(" + dateValue + ", INTERVAL (" + numberOfWeeks + ") WEEK )";
}
/**
* Does the required transformation to produce an SQL snippet that adds
* numberOfMonths months to the dateValue.
*
* @param dateValue dateValue
* @param numberOfMonths numberOfMonths
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return an SQL snippet
*/
public String doAddMonthsTransform(String dateValue, String numberOfMonths) {
return "DATE_ADD(" + dateValue + ", INTERVAL (" + numberOfMonths + ") MONTH )";
}
/**
* Does the required transformation to produce an SQL snippet that adds
* numberOfYears years to the dateValue.
*
* @param dateValue dateValue
* @param numberOfYears numberOfYears
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return an SQL snippet
*/
public String doAddYearsTransform(String dateValue, String numberOfYears) {
return "DATE_ADD(" + dateValue + ", INTERVAL (" + numberOfYears + ") YEAR )";
}
/**
* Transform a Java Boolean into the equivalent in an SQL snippet.
*
* @param boolValue boolValue
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return an SQL snippet
*/
public String doBooleanValueTransform(Boolean boolValue) {
if (boolValue == null) {
return getNull();
} else if (boolValue) {
return getTrueValue();
} else {
return getFalseValue();
}
// return beginNumberValue() + (boolValue ? 1 : 0) + endNumberValue();
}
/**
* Indicates whether the database supports use of the "^" operator to perform
* boolean XOR.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return TRUE if the database supports "^" as XOR, FALSE otherwise.
*/
public boolean supportsXOROperator() {
return false;
}
/**
* Transform a set of SQL snippets into the database's version of the LEAST
* function.
*
* <p>
* The LEAST function takes a list of values and returns the smallest value.
*
* <p>
* Not to be confused with the MIN aggregate function.
*
* @param strs strs
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a String of the SQL required to find the smallest value in the list
* provided.
*/
public String doLeastOfTransformation(List<String> strs) {
if (supportsLeastOfNatively()) {
StringBuilder sql = new StringBuilder(getLeastOfFunctionName() + "(");
String comma = "";
for (String str : strs) {
sql.append(comma).append(str);
comma = ", ";
}
return sql.append(")").toString();
} else {
return fakeLeastOfTransformation(strs);
}
}
private String fakeLeastOfTransformation(List<String> strs) {
String sql = "";
String prevCase = null;
if (strs.size() == 1) {
return strs.get(0);
}
for (String str : strs) {
if (prevCase == null) {
prevCase = "(" + str + ")";
} else {
sql = "(case when " + str + " < " + prevCase + " then " + str + " else " + prevCase + " end)";
}
}
return sql;
}
/**
* Transform a set of SQL snippets into the database's version of the GREATEST
* function.
*
* <p>
* The GREATEST function takes a list of values and returns the largest value.
*
* <p>
* Not to be confused with the MAX aggregate function.
*
* @param strs strs
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a String of the SQL required to get the largest value in the
* supplied list.
*/
public String doGreatestOfTransformation(List<String> strs) {
if (supportsGreatestOfNatively()) {
StringBuilder sql = new StringBuilder(getGreatestOfFunctionName() + "(");
String comma = "";
for (String str : strs) {
sql.append(comma).append(str);
comma = ", ";
}
return sql.append(")").toString();
} else {
return fakeGreatestOfTransformation(strs);
}
}
private String fakeGreatestOfTransformation(List<String> strs) {
String sql = "";
String prevCase = null;
if (strs.size() == 1) {
return strs.get(0);
}
for (String str : strs) {
if (prevCase == null) {
prevCase = "(" + str + ")";
} else {
sql = "(case when " + str + " > " + prevCase + " then " + str + " else " + prevCase + " end)";
}
}
return sql;
}
/**
* Returns the SQL string used to replace the value of a substring with
* another string.
*
* @param withinString search within this value
* @param findString search for this value
* @param replaceString replace with this value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "REPLACE(withinString, findString, replaceString)"
* @see StringExpression#replace(java.lang.String, java.lang.String)
* @see StringExpression#replace(java.lang.String,
* nz.co.gregs.dbvolution.results.StringResult)
* @see StringExpression#replace(nz.co.gregs.dbvolution.results.StringResult,
* java.lang.String)
* @see StringExpression#replace(nz.co.gregs.dbvolution.results.StringResult,
* nz.co.gregs.dbvolution.results.StringResult)
*/
public String doReplaceTransform(String withinString, String findString, String replaceString) {
return "REPLACE(" + withinString + "," + findString + "," + replaceString + ")";
}
/**
* Transforms a SQL snippet of a number expression into a character expression
* for this database.
*
* @param numberExpression numberExpression
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a String of the SQL required to transform the number supplied into
* a character or String type.
*/
public String doNumberToStringTransform(String numberExpression) {
return doConcatTransform(getEmptyString(), numberExpression);
}
/**
* Creates the CURRENTDATE function for this database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a String of the SQL required to get the CurrentDateOnly value.
*/
public String doCurrentDateOnlyTransform() {
return getCurrentDateOnlyFunctionName().trim() + "()";
}
/**
* Convert the boolean array of bit values into the SQL equivalent.
*
* @param booleanArray booleanArray
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL snippet.
*/
public String doBitsValueTransform(boolean[] booleanArray) {
String result = "";
String separator = "ARRAY(";
for (boolean c : booleanArray) {
if (c) {
result += separator + "true";
} else {
result += separator + "false";
}
separator = ",";
}
if (!separator.equals("(")) {
result += ")";
}
return result;
}
/**
* Convert the 2 SQL date values into a difference in days.
*
* @param dateValue dateValue
* @param otherDateValue otherDateValue
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doDayDifferenceTransform(String dateValue, String otherDateValue) {
return "(DATEDIFF('DAY', " + dateValue + "," + otherDateValue + "))";
}
/**
* Convert the 2 SQL date values into a difference in days.
*
* @param dateValue dateValue
* @param otherDateValue otherDateValue
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doWeekDifferenceTransform(String dateValue, String otherDateValue) {
return "(" + doDayDifferenceTransform(dateValue, otherDateValue) + "/7)";
}
/**
* Convert the 2 SQL date values into a difference in months.
*
* @param dateValue dateValue
* @param otherDateValue otherDateValue
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doMonthDifferenceTransform(String dateValue, String otherDateValue) {
return "(DATEDIFF('MONTH', " + dateValue + "," + otherDateValue + "))";
}
/**
* Convert the 2 SQL date values into a difference in years.
*
* @param dateValue dateValue
* @param otherDateValue otherDateValue
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doYearDifferenceTransform(String dateValue, String otherDateValue) {
return "(DATEDIFF('YEAR', " + dateValue + "," + otherDateValue + "))";
}
/**
* Convert the 2 SQL date values into a difference in hours.
*
* @param dateValue dateValue
* @param otherDateValue otherDateValue
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doHourDifferenceTransform(String dateValue, String otherDateValue) {
return "(DATEDIFF('HOUR', " + dateValue + "," + otherDateValue + "))";
}
/**
* Convert the 2 SQL date values into a difference in minutes.
*
* @param dateValue dateValue
* @param otherDateValue otherDateValue
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doMinuteDifferenceTransform(String dateValue, String otherDateValue) {
return "(DATEDIFF('MINUTE', " + dateValue + "," + otherDateValue + "))";
}
/**
* Convert the 2 SQL date values into a difference in whole seconds.
*
* @param dateValue dateValue
* @param otherDateValue otherDateValue
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doSecondDifferenceTransform(String dateValue, String otherDateValue) {
return "(DATEDIFF('SECOND', " + dateValue + "," + otherDateValue + "))";
}
/**
* Convert the 2 SQL date values into a difference in milliseconds.
*
* @param dateValue dateValue
* @param otherDateValue otherDateValue
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
// public String doMillisecondDifferenceTransform(String dateValue, String otherDateValue) {
// return "(DATEDIFF('MILLISECOND', " + dateValue + "," + otherDateValue + "))";
// }
/**
* Create a foreign key clause for use in a CREATE TABLE statement from the
* {@link PropertyWrapper} provided.
*
* @param field field
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return The default implementation returns something like " FOREIGN KEY
* (column) REFERENCES table(reference_column) "
*/
public String getForeignKeyClauseForCreateTable(PropertyWrapper field) {
if (field.isForeignKey()) {
return " FOREIGN KEY (" + field.columnName() + ") REFERENCES " + field.referencedTableName() + "(" + field.referencedColumnName() + ") ";
}
return "";
}
/**
* Produce SQL that will provide return the second value if the first is NULL.
*
* @param possiblyNullValue possiblyNullValue
* @param alternativeIfNull alternativeIfNull
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doStringIfNullTransform(String possiblyNullValue, String alternativeIfNull) {
return this.getIfNullFunctionName() + "(" + possiblyNullValue
+ ","
+ (alternativeIfNull == null ? "NULL" : alternativeIfNull)
+ ")";
}
/**
* Produce SQL that will provide return the second value if the first is NULL.
*
* @param possiblyNullValue possiblyNullValue
* @param alternativeIfNull alternativeIfNull
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doNumberIfNullTransform(String possiblyNullValue, String alternativeIfNull) {
return doStringIfNullTransform(possiblyNullValue, alternativeIfNull);
}
/**
* Produce SQL that will provide return the second value if the first is NULL.
*
* @param possiblyNullValue possiblyNullValue
* @param alternativeIfNull alternativeIfNull
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doDateIfNullTransform(String possiblyNullValue, String alternativeIfNull) {
return doStringIfNullTransform(possiblyNullValue, alternativeIfNull);
}
/**
* Produce SQL that will compare the first value to all the other values using
* the IN operator.
*
* @param comparableValue comparableValue
* @param values values
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL similar to "comparableValue IN (value, value, value)"
*/
public String doInTransform(String comparableValue, List<String> values) {
StringBuilder builder = new StringBuilder();
builder
.append(comparableValue)
.append(" IN ( ");
String separator = "";
for (String val : values) {
if (val != null) {
builder.append(separator).append(val);
}
separator = ", ";
}
builder.append(")");
return builder.toString();
}
/**
* Returns FROM clause to be used for this table.
*
* @param table the table to transform into a FROM clause.
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a SQL snippet for a FROM clause.
*/
public String getFromClause(DBRow table) {
String recursiveTableAlias = table.getRecursiveTableAlias();
if (recursiveTableAlias != null) {
return recursiveTableAlias;
} else {
return formatTableName(table) + beginTableAlias() + getTableAlias(table) + endTableAlias();
}
}
/**
* The beginning of the WITH variant supported by this database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "WITH RECURSIVE" by default.
*/
public String beginWithClause() {
return " WITH RECURSIVE ";
}
/**
* Define the table to be used during a recursive query.
*
* @param recursiveTableAlias the table alias used during the recursive query.
* @param recursiveColumnNames all the columns in the recursive part of the
* query.
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return by default something like: ALIAS(COL1, COL2, ... )
*/
public String formatWithClauseTableDefinition(String recursiveTableAlias, String recursiveColumnNames) {
return recursiveTableAlias + "(" + recursiveColumnNames + ")" + " \n";
}
/**
* Return the default preamble to the priming query of a
* {@link DBRecursiveQuery}.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return " AS ("
*/
public String beginWithClausePrimingQuery() {
return " AS (";
}
/**
* Return the necessary connector between the priming query and the recursive
* query used in a {@link DBRecursiveQuery}.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return " \n UNION ALL "
*/
public String endWithClausePrimingQuery() {
return " \n UNION ALL ";
}
/**
* Return the default preamble to the recursive query of a
* {@link DBRecursiveQuery}.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return ""
*/
public String beginWithClauseRecursiveQuery() {
return "";
}
/**
* Return the default preamble to the recursive query of a
* {@link DBRecursiveQuery}.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return " \n ) \n"
*/
public String endWithClauseRecursiveQuery() {
return " \n ) \n";
}
/**
* Return the default select clause for the final query of a
* {@link DBRecursiveQuery}.
*
* @param recursiveTableAlias the table alias used in the recursive query.
* @param recursiveAliases all the column aliases used in the recursive query.
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return " SELECT ... FROM ... ORDER BY ... ASC; ";
*/
public String doSelectFromRecursiveTable(String recursiveTableAlias, String recursiveAliases) {
return " SELECT " + recursiveAliases + ", " + getRecursiveQueryDepthColumnName() + " FROM " + recursiveTableAlias + " ORDER BY " + getRecursiveQueryDepthColumnName() + " ASC; ";
}
/**
* Indicates whether this database needs the recursive query to use table
* aliases.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return TRUE
*/
public boolean requiresRecursiveTableAlias() {
return true;
}
/**
* Return the default name for the depth column generated during a
* {@link DBRecursiveQuery}.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return " DBDEPTHCOLUMN "
*/
public String getRecursiveQueryDepthColumnName() {
return " DBDEPTHCOLUMN ";
}
/**
* Expresses whether the database has a particular datatype for primary key
* columns.
*
* @param field the property to check
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return FALSE by default
*/
protected boolean hasSpecialPrimaryKeyTypeForDBDatatype(PropertyWrapper field) {
return false;
}
/**
* Return the necessary SQL data type for this field to be a primary key in
* this database.
*
* @param field the property to check
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return by default DBvolution returns the standard datatype for this field.
*/
protected String getSpecialPrimaryKeyTypeOfDBDatatype(PropertyWrapper field) {
return getSQLTypeOfDBDatatype(field);
}
/**
* Indicates whether the LEASTOF operator is supported by the database or
* needs to be emulated.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return TRUE by default.
*/
protected boolean supportsLeastOfNatively() {
return true;
}
/**
* Indicates whether the GREATESTOF operator is supported by the database or
* needs to be emulated.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return TRUE by default.
*/
protected boolean supportsGreatestOfNatively() {
return true;
}
/**
* Indicates whether the database supports grouping by columns that don't
* involve any tables.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return TRUE by default.
*/
public boolean supportsPurelyFunctionalGroupByColumns() {
return true;
}
/**
* Creates a pattern that will exclude system tables during DBRow class
* generation i.e. {@link DBTableClassGenerator}.
*
* <p>
* By default this method returns ".*" as system tables are not a problem for
* most databases.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return default is ".*" so all tables are included.
*/
public String getSystemTableExclusionPattern() {
return ".*";
}
/**
* Allows the database to have a different format for the primary key column
* name.
*
* <p>
* Most databases do not have a problem with this method but PostgreSQL likes
* the column name to be lowercase in this particular instance.
*
* @param primaryKeyColumnName the name of the primary key column formatted
* for this database
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the Primary Key formatted for this database.
*/
public String formatPrimaryKeyForRetrievingGeneratedKeys(String primaryKeyColumnName) {
return primaryKeyColumnName;
}
/**
* Choose a string option based on the number in the first parameter.
*
* <p>
* Based on the MS SQLserver CHOOSE function, this method allows the first
* parameter to determine which string is appropriate. If the number is 1, the
* first string is returned, 2 returns the second and so forth. If the number
* exceeds the number of strings the last string is returned.s
*
* @param numberToChooseWith the index to use
* @param strs the options to choose from.
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doChooseTransformation(String numberToChooseWith, List<String> strs) {
if (supportsChooseNatively()) {
StringBuilder sql = new StringBuilder(getChooseFunctionName() + "(" + numberToChooseWith);
String comma = ", ";
for (String str : strs) {
sql.append(comma).append(str);
}
return sql.append(")").toString();
} else {
return fakeChooseTransformation(numberToChooseWith, strs);
}
}
private String fakeChooseTransformation(String numberToChooseWith, List<String> strs) {
String sql = "(case ";
String prevCase = null;
if (strs.size() == 1) {
return strs.get(0);
}
String op = " <= ";
for (int index = 0; index < strs.size(); index++) {
String str = strs.get(index);
if (index == strs.size() - 1) {
sql += " else " + str + " end)";
} else {
sql += " when " + numberToChooseWith + op + (index + 1) + " then " + str + System.getProperty("line.separator");
op = " = ";
}
}
return sql;
}
/**
* Allows the DBDatabase instance to provide the database-specific name for
* the CHOOSE function.
*
* <p>
* Used by {@link #doChooseTransformation(java.lang.String, java.util.List)
* } to connect to the correct database function.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String getChooseFunctionName() {
return "";
}
/**
* Switchs the
* {@link #doChooseTransformation(java.lang.String, java.util.List)} to using
* the database's native function.
*
* <p>
* Override this method and return TRUE if the database has a native
* equivalent to the CHOOSE function as used by {@link #doChooseTransformation(java.lang.String, java.util.List) }.
*
* <p>
* You will also need to implement {@link #getChooseFunctionName() }.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return TRUE if the database has a CHOOSE equivalent, otherwise FALSE
*/
protected boolean supportsChooseNatively() {
return false;
}
/**
* Implements functionality similar to IF THEN ELSE probably using CASE.
*
* <p>
* Returns the second parameter if the first is TRUE, otherwise returns the
* third parameter.
*
* @param booleanTest the true/false test
* @param thenResult the result to return if the test returns TRUE
* @param elseResult the result to return if the test returns FALSE
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return IF the booleanTest is TRUE returns the thenResult, otherwise
* returns elseResult.
*/
public String doIfThenElseTransform(String booleanTest, String thenResult, String elseResult) {
return "(CASE WHEN " + booleanTest + " THEN " + thenResult + " ELSE " + elseResult + " END)";
}
/**
* Extracts the weekday from the date provided as a number from 1 to 7.
*
* <p>
* Provides access to the day of the week as a number from 1 for Sunday to 7
* for Saturday.
*
* @param dateSQL the date to get the day of the week for.
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a number between 1 and 7 for the weekday.
*/
abstract public String doDayOfWeekTransform(String dateSQL);
/**
* Provides the CREATE INDEX clause for this database.
*
* <p>
* Used in {@link DBDatabase#createIndexesOnAllFields(nz.co.gregs.dbvolution.DBRow)
* } to create indexes for the fields of the table.
*
* @param field the field to generate an index for
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String getIndexClauseForCreateTable(PropertyWrapper field) {
return "CREATE INDEX " + formatNameForDatabase("DBI_" + field.tableName() + "_" + field.columnName()) + " ON " + formatNameForDatabase(field.tableName()) + "(" + formatNameForDatabase(field.columnName()) + ")";
}
/**
* Transforms the array of booleans into the database format.
*
* <p>
* The default implementation changes the array into a string of 0s and 1s.
*
* @param bools all the true/false values
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a string of 1s and 0s representing the boolean array.
*/
public String doBooleanArrayTransform(Boolean[] bools) {
StringBuilder str = new StringBuilder();
for (Boolean bool : bools) {
str.append((bool == true ? "1" : "0"));
}
return "'" + str.toString() + "'";
}
/**
* Reverses the {@link #doBooleanArrayTransform(java.lang.Boolean[]) } and
* creates an array of booleans.
*
* <p>
* The default implementation transforms a string of 0s and 1s into an array
* of Booleans.
*
* @param stringOfBools all the true/false values
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return an array of Booleans.
*/
public Boolean[] doBooleanArrayResultInterpretation(String stringOfBools) {
if (stringOfBools != null && stringOfBools.length() > 0) {
Boolean[] result = new Boolean[stringOfBools.length()];
for (int i = 0; i < stringOfBools.length(); i++) {
result[i] = (stringOfBools.substring(i, i + 1)).equals("1");
}
return result;
} else {
return null;
}
}
/**
* Indicates if the database supports ARRAYs natively and the functionality
* has been implemented.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return TRUE by default.
*/
public boolean supportsArraysNatively() {
return true;
}
/**
* Implement this method if the database implements ARRAYs but not BOOLEAN.
*
* @param objRepresentingABoolean an object to be used in the boolean array
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a boolean derived from objRepresentingABoolean.
*/
public Boolean doBooleanArrayElementTransform(Object objRepresentingABoolean) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Transform the to numbers to compare then with equals.
*
* <p>
* The default implementation is {@code leftHandSide + " = " + rightHandSide}.
*
* @param leftHandSide the first value to compare
* @param rightHandSide the second value to compare
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the SQL required to compare the two numbers.
*/
public String doNumberEqualsTransform(String leftHandSide, String rightHandSide) {
return "" + leftHandSide + " = " + rightHandSide + "";
}
/**
* Creates the ALTER TABLE statement required to add a FOREIGN KEY constraint.
*
* <p>
* Remember to check {@code field.isForeignKey()} first.
*
* @param newTableRow the table to be altered.
* @param field the field to add a foreign key from
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the SQL to add a foreign key.
*/
public String getAlterTableAddForeignKeyStatement(DBRow newTableRow, PropertyWrapper field) {
if (field.isForeignKey()) {
return "ALTER TABLE " + this.formatTableName(newTableRow) + " ADD " + this.getForeignKeyClauseForCreateTable(field);
}
return "";
}
/**
* Creates the ALTER TABLE statement required to remove a FOREIGN KEY
* constraint.
*
* <p>
* Remember to check {@code field.isForeignKey()} first.
*
* @param newTableRow the table to be altered.
* @param field the field to remove the foreign key from.
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the SQL to remove a foreign key.
*/
public String getAlterTableDropForeignKeyStatement(DBRow newTableRow, PropertyWrapper field) {
if (field.isForeignKey()) {
return "ALTER TABLE " + this.formatTableName(newTableRow) + " DROP FOREIGN KEY " + field.columnName();
}
return "";
}
/**
* Perform necessary transformations on the stored value to make it readable
* by Java.
*
* <p>
* Primarily used on Spatial types, this method allows a data type unknown to
* JDBC to be transformed into the necessary type (usually a String) to be
* read by Java and DBvolution.
*
* @param qdt the DBV value to be stored
* @param selectableName the selectable value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doColumnTransformForSelect(QueryableDatatype qdt, String selectableName) {
return selectableName;
}
/**
* Creates a string representation of a DateRepeat from the Period
*
* @param interval the interval to be transformed into a DateRepeat.
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a DateRpeat as an SQL string
*/
public String transformPeriodIntoDateRepeat(Period interval) {
StringBuilder str = new StringBuilder();
str.append("'").append(DateRepeatExpression.INTERVAL_PREFIX);
str.append(interval.getYears()).append(DateRepeatExpression.YEAR_SUFFIX);
str.append(interval.getMonths()).append(DateRepeatExpression.MONTH_SUFFIX);
str.append(interval.getDays() + (interval.getWeeks() * 7)).append(DateRepeatExpression.DAY_SUFFIX);
str.append(interval.getHours()).append(DateRepeatExpression.HOUR_SUFFIX);
str.append(interval.getMinutes()).append(DateRepeatExpression.MINUTE_SUFFIX);
str.append(interval.getSeconds()).append(DateRepeatExpression.SECOND_SUFFIX);
str.append("'");
return str.toString();
}
/**
* Create a DateRepeat by subtracting the 2 dates.
*
* @param leftHandSide the first date
* @param rightHandSide the second date to subtract from the first
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the SQL required to create a DateRepeat from the dates
*/
public String doDateMinusToDateRepeatTransformation(String leftHandSide, String rightHandSide) {
return "(" + leftHandSide + " - " + rightHandSide + ")";
}
/**
* Compare 2 DateRepeats using EQUALS.
*
* @param leftHandSide the first value to compare
* @param rightHandSide the second value to compare
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the SQL required to create to compare DateRepeats
*/
public String doDateRepeatEqualsTransform(String leftHandSide, String rightHandSide) {
return "(" + leftHandSide + " = " + rightHandSide + ")";
}
/**
* Compare 2 DateRepeats using NOT EQUALS.
*
* @param leftHandSide the first DateRepeat value to compare
* @param rightHandSide the second DateRepeat value to compare
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the SQL required to create to compare DateRepeats
*/
public String doDateRepeatNotEqualsTransform(String leftHandSide, String rightHandSide) {
return "(" + leftHandSide + " <> " + rightHandSide + ")";
}
/**
* Compare 2 DateRepeats using LESSTHAN.
*
* @param leftHandSide the first DateRepeat value to compare
* @param rightHandSide the second DateRepeat value to compare
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the SQL required to create to compare DateRepeats
*/
public String doDateRepeatLessThanTransform(String leftHandSide, String rightHandSide) {
return "(" + leftHandSide + " < " + rightHandSide + ")";
}
/**
* Compare 2 DateRepeats using LESSTHANEQUALS.
*
* @param leftHandSide the first DateRepeat value to compare
* @param rightHandSide the second DateRepeat value to compare
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the SQL required to create to compare DateRepeats
*/
public String doDateRepeatLessThanEqualsTransform(String leftHandSide, String rightHandSide) {
return "(" + leftHandSide + " <= " + rightHandSide + ")";
}
/**
* Compare 2 DateRepeats using GREATERTHAN.
*
* @param leftHandSide the first DateRepeat value to compare
* @param rightHandSide the second DateRepeat value to compare
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the SQL required to create to compare DateRepeats
*/
public String doDateRepeatGreaterThanTransform(String leftHandSide, String rightHandSide) {
return "(" + leftHandSide + " > " + rightHandSide + ")";
}
/**
* Compare 2 DateRepeats using GREATERTHANEQUALS.
*
* @param leftHandSide the first DateRepeat value to compare
* @param rightHandSide the second DateRepeat value to compare
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the SQL required to create to compare DateRepeats
*/
public String doDateRepeatGreaterThanEqualsTransform(String leftHandSide, String rightHandSide) {
return "(" + leftHandSide + " >= " + rightHandSide + ")";
}
/**
* Offset the date by the DateRepeat.
*
* @param leftHandSide the first DateRepeat value to compare
* @param rightHandSide the second DateRepeat value to compare
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the SQL required to change the date by the required amount.
*/
public String doDatePlusDateRepeatTransform(String leftHandSide, String rightHandSide) {
return "(" + leftHandSide + " + " + rightHandSide + ")";
}
/**
* Offset the date by subtracting the DateRepeat.
*
* @param leftHandSide the first DateRepeat value to compare
* @param rightHandSide the second DateRepeat value to compare
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the SQL required to change the date by the required amount.
*/
public String doDateMinusDateRepeatTransform(String leftHandSide, String rightHandSide) {
return leftHandSide + "-" + rightHandSide;
}
/**
* Create a Period from the database version of the DateRepeat.
*
* @param intervalStr the DateRepeat value to convert into a Jodatime Period
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a Period.
*/
public Period parseDateRepeatFromGetString(String intervalStr) {
return DateRepeatImpl.parseDateRepeatFromGetString(intervalStr);
}
/**
* Compare 2 polygons with EQUALS.
*
* @param firstGeometry the first polygon2d value to compare
* @param secondGeometry the second polygon2d value to compare
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doPolygon2DEqualsTransform(String firstGeometry, String secondGeometry) {
throw new UnsupportedOperationException("Spatial Operations Haven't Been Defined Yet");
}
/**
* Creates a Polygon2D representing the intersection of the Polygon2Ds.
*
* @param firstGeometry the first polygon2d value to compare
* @param secondGeometry the second polygon2d value to compare
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL that represents a polygon of the intersection, null if there is
* no intersection.
*/
public String doPolygon2DIntersectionTransform(String firstGeometry, String secondGeometry) {
throw new UnsupportedOperationException("Spatial Operations Haven't Been Defined Yet");
}
/**
* Test whether the 2 polygons intersect.
*
* @param firstGeometry the first polygon2d value to compare
* @param secondGeometry the second polygon2d value to compare
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL that returns TRUE if they intersect.
*/
public String doPolygon2DIntersectsTransform(String firstGeometry, String secondGeometry) {
throw new UnsupportedOperationException("Spatial Operations Haven't Been Defined Yet");
}
/**
* Test whether the first polygon completely contains the second polygon.
*
* @param firstGeometry the first polygon2d value to compare
* @param secondGeometry the second polygon2d value to compare
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL that is TRUE if the first polygon contains the second.
*/
public String doPolygon2DContainsPolygon2DTransform(String firstGeometry, String secondGeometry) {
throw new UnsupportedOperationException("Geometry Operations Have Not Been Defined For This Database Yet.");
}
/**
* Inverse of {@link #doPolygon2DIntersectsTransform(java.lang.String, java.lang.String)
* }, tests whether the 2 polygons are non-coincident.
*
* @param firstGeometry the first polygon2d value to compare
* @param secondGeometry the second polygon2d value to compare
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL that is FALSE if the polygons intersect.
*/
public String doPolygon2DDoesNotIntersectTransform(String firstGeometry, String secondGeometry) {
throw new UnsupportedOperationException("Geometry Operations Have Not Been Defined For This Database Yet.");
}
/**
* Test whether the 2 polygons intersect but not contained or within.
*
* @param firstGeometry the first polygon2d value to compare
* @param secondGeometry the second polygon2d value to compare
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL that is TRUE if the polygons have intersecting and
* non-intersecting parts.
*/
public String doPolygon2DOverlapsTransform(String firstGeometry, String secondGeometry) {
throw new UnsupportedOperationException("Geometry Operations Have Not Been Defined For This Database Yet.");
}
/**
* Tests whether the polygons touch.
*
* <p>
* Checks that a) the polygons have at least on point in common and b) that
* their interiors do not overlap.
*
* @param firstGeometry the first polygon2d value to compare
* @param secondGeometry the second polygon2d value to compare
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL snippet
*/
public String doPolygon2DTouchesTransform(String firstGeometry, String secondGeometry) {
throw new UnsupportedOperationException("Geometry Operations Have Not Been Defined For This Database Yet.");
}
/**
* Test whether the first polygon is completely within the second polygon.
*
* <p>
* Compare this to {@link #doPolygon2DContainsPolygon2DTransform(java.lang.String, java.lang.String)
* }
*
* @param firstGeometry the first polygon2d value to compare
* @param secondGeometry the second polygon2d value to compare
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL that is TRUE if the first polygon is within the second.
*/
public String doPolygon2DWithinTransform(String firstGeometry, String secondGeometry) {
//indicate whether g1 is spatially within g2. This is the inverse of Contains().
// i.e. G1.within(G2) === G2.contains(G1)
throw new UnsupportedOperationException("Geometry Operations Have Not Been Defined For This Database Yet.");
}
/**
* Returns the dimension of the polygon.
*
* <p>
* This will be "2"
*
* @param polygon2DSQL a polygon2d value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "2" unless something has gone horribly wrong.
*/
public String doPolygon2DMeasurableDimensionsTransform(String polygon2DSQL) {
throw new UnsupportedOperationException("Geometry Operations Have Not Been Defined For This Database Yet.");
}
/**
* Create a simple four sided bounding for the polygon.
*
* @param polygon2DSQL a polygon2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the SQL required to create a bounding box for the polygon.
*/
public String doPolygon2DGetBoundingBoxTransform(String polygon2DSQL) {
throw new UnsupportedOperationException("Geometry Operations Have Not Been Defined For This Database Yet.");
}
/**
* Retrieve the area of the polygon.
*
* @param polygon2DSQL a polygon2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL that will return the area of the Polygon2D
*/
public String doPolygon2DGetAreaTransform(String polygon2DSQL) {
throw new UnsupportedOperationException("Geometry Operations Have Not Been Defined For This Database Yet.");
}
/**
* Defines the transformation require to transform an SQL Polygon2D into a
* linestring representing the exterior ring of the polygon.
*
* @param polygon2DSQL a polygon2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doPolygon2DGetExteriorRingTransform(String polygon2DSQL) {
throw new UnsupportedOperationException("Geometry Operations Have Not Been Defined For This Database Yet.");
}
/**
* Indicates that this database supports hyperbolic functions natively.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return TRUE by default.
*/
public boolean supportsHyperbolicFunctionsNatively() {
return true;
}
/**
* Provides the ARCTAN2 function name for this database.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "atan2" by default.
*/
public String getArctan2FunctionName() {
return "atan2";
}
/**
* Get the year part of the DateRepeat, an integer
*
* @param dateRepeatSQL a date repeat value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doDateRepeatGetYearsTransform(String dateRepeatSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Get the month part of the DateRepeat, an integer
*
* @param dateRepeatSQL a date repeat value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doDateRepeatGetMonthsTransform(String dateRepeatSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Get the Days part of the DateRepeat, an integer
*
* @param dateRepeatSQL a date repeat value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doDateRepeatGetDaysTransform(String dateRepeatSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Get the hour part of the DateRepeat, an integer
*
* @param dateRepeatSQL a date repeat value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doDateRepeatGetHoursTransform(String dateRepeatSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Get the minute part of the DateRepeat, an integer
*
* @param dateRepeatSQL a date repeat value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doDateRepeatGetMinutesTransform(String dateRepeatSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Get the seconds part of the DateRepeat, a decimal number
*
* @param dateRepeatSQL a date repeat value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doDateRepeatGetSecondsTransform(String dateRepeatSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Transform the DateRepeat into it's character based equivalent.
*
* @param dateRepeatSQL a date repeat value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doDateRepeatToStringTransform(String dateRepeatSQL) {
return doConcatTransform(getEmptyString(), dateRepeatSQL);
}
/**
* Provide SQL to interpret the String value as a number.
*
* <p>
* Full of ways to fail this is.
*
* @param stringResultContainingANumber a number value to be coerced to string
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL that converts the string value into number.
*/
public String doStringToNumberTransform(String stringResultContainingANumber) {
return "(0.0+(" + stringResultContainingANumber + "))";
}
/**
* Indicates that the database supports the ARCSINE function.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return true by default.
*/
public boolean supportsArcSineFunction() {
return true;
}
/**
* Indicates that the database supports the COTANGENT function.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return true by default.
*/
public boolean supportsCotangentFunction() {
return true;
}
/**
* Transform a datatype not supported by the database into a type that the
* database does support.
*
* <p>
* Used mostly to turn Booleans into numbers.
*
* <p>
* By default this method just returns the input DBExpression.
*
* @param columnExpression a column expression that might need to change type
* for this database
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return The DBExpression as a DBExpression supported by the database.
*/
public DBExpression transformToStorableType(DBExpression columnExpression) {
return columnExpression;
}
/**
* Provide the SQL to compare 2 Point2Ds
*
* @param firstPoint a point2d value to compare
* @param secondPoint a point2d value to compare
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doPoint2DEqualsTransform(String firstPoint, String secondPoint) {
throw new UnsupportedOperationException("Spatial Operations Haven't Been Defined Yet");
}
/**
* Provide the SQL to return the X coordinate of the Point2D
*
* @param pont2DSQL a point2d value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doPoint2DGetXTransform(String pont2DSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Provide the SQL to return the Y coordinate of the Point2D
*
* @param point2DSQL a point2d value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doPoint2DGetYTransform(String point2DSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Provide the SQL to return the dimension of the Point2D
*
* <p>
* Point is a 0-dimensional objects for this purpose.
*
* @param point2DSQL a point2d value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doPoint2DMeasurableDimensionsTransform(String point2DSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Provide the SQL to derive the Polygon2D representing the Bounding Box of
* the Point2D.
*
* @param point2DSQL a point2d value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doPoint2DGetBoundingBoxTransform(String point2DSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Provide the SQL to derive the WKT version of the Point2D.
*
* @param point2DSQL a point2d value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doPoint2DAsTextTransform(String point2DSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Provide the SQL that correctly represents this Point2D in this database.
*
* @param point a point to be turned into an SQL point2d value.
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String transformPoint2DIntoDatabaseFormat(Point point) {
String wktValue = point.toText();
return "'" + wktValue + "'";
}
/**
* Provide the SQL that correctly represents these coordinates in this
* database.
*
* <p>
* The same as
* {@link #transformPoint2DIntoDatabaseFormat(com.vividsolutions.jts.geom.Point)}
* but for two coordinates as SQL.
*
* @param xValue a number value
* @param yValue a number value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String transformCoordinatesIntoDatabasePoint2DFormat(String xValue, String yValue) {
return "'POINT(" + xValue + " " + yValue + ")'";
}
/**
* From the database's representation of a Point2D create a JTS Point.
*
* <p>
* This is the inverse of {@link #transformPoint2DIntoDatabaseFormat(com.vividsolutions.jts.geom.Point)
* }.
*
* @param pointAsString a point2d value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a point created from the point2d value
* @throws com.vividsolutions.jts.io.ParseException if the database result is
* not a valid WKT
*/
public Point transformDatabasePoint2DValueToJTSPoint(String pointAsString) throws com.vividsolutions.jts.io.ParseException {
Point point = null;
WKTReader wktReader = new WKTReader();
Geometry geometry = wktReader.read(pointAsString);
if (geometry instanceof Point) {
point = (Point) geometry;
} else {
throw new IncorrectGeometryReturnedForDatatype(geometry, point);
}
return point;
}
/**
* From the database's representation of a Polygon2D create a JTS Polygon.
*
* <p>
* This is the inverse of
* {@link #transformPolygonIntoDatabasePolygon2DFormat(com.vividsolutions.jts.geom.Polygon)}.
*
* @param polygon2DSQL a polygon2d value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a polygon created from the polygon2d value
* @throws com.vividsolutions.jts.io.ParseException if the database result is
* not a valid WKT
*/
public Polygon transformDatabasePolygon2DToJTSPolygon(String polygon2DSQL) throws com.vividsolutions.jts.io.ParseException {
Polygon poly = null;
WKTReader wktReader = new WKTReader();
Geometry geometry = wktReader.read(polygon2DSQL);
if (geometry instanceof Polygon) {
poly = (Polygon) geometry;
} else if (geometry instanceof LineString) {
GeometryFactory geofactory = new GeometryFactory();
LineString lineString = (LineString) geometry;
poly = geofactory.createPolygon(lineString.getCoordinateSequence());
} else if (geometry instanceof Point) {
GeometryFactory geofactory = new GeometryFactory();
Point point = (Point) geometry;
poly = geofactory.createPolygon(new Coordinate[]{point.getCoordinate(), point.getCoordinate(),point.getCoordinate(),point.getCoordinate(),point.getCoordinate()});
} else {
throw new IncorrectGeometryReturnedForDatatype(geometry, poly);
}
return poly;
}
/**
* From the database's representation of a Lin2D create a JTS LineString.
*
* <p>
* This is the inverse of
* {@link #transformPolygonIntoDatabasePolygon2DFormat(com.vividsolutions.jts.geom.Polygon)}.
*
* @param lineStringAsSQL a line2d value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a linestring created from the line2d
* @throws com.vividsolutions.jts.io.ParseException if the database result is
* not a valid WKT
*/
public LineString transformDatabaseLine2DValueToJTSLineString(String lineStringAsSQL) throws com.vividsolutions.jts.io.ParseException {
LineString lineString = null;
WKTReader wktReader = new WKTReader();
Geometry geometry = wktReader.read(lineStringAsSQL);
if (geometry instanceof LineString) {
lineString = (LineString) geometry;
} else {
throw new IncorrectGeometryReturnedForDatatype(geometry, lineString);
}
return lineString;
}
/**
* Provide the SQL that correctly represents this LineString in this database.
*
* @param lineString a linestring to transform in to a Line2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String transformLineStringIntoDatabaseLine2DFormat(LineString lineString) {
String wktValue = lineString.toText();
return "'" + wktValue + "'";
}
/**
* Provide the SQL to derive the WKT version of the Line2D.
*
* @param line2DSQL a line2d value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doLine2DAsTextTransform(String line2DSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Transform the 2 Line2D SQL snippets into an EQUALS comparison of the 2
*
* @param line2DSQL the first line2d value to compare
* @param otherLine2DSQL the second line2d value to compare
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doLine2DEqualsTransform(String line2DSQL, String otherLine2DSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Transform the 2 Line2D SQL snippets into an NOT_EQUALS comparison of the 2
*
* @param line2DSQL the first line2d value to compare
* @param otherLine2DSQL the second line2d value to compare
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doLine2DNotEqualsTransform(String line2DSQL, String otherLine2DSQL) {
return "NOT (" + doLine2DEqualsTransform(line2DSQL, otherLine2DSQL) + ")";
}
/**
* Create the SQL required to get the dimension of this Line2D SQL.
*
* @param line2DSQL the line2d value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the dimension (probably 1)
*/
public String doLine2DMeasurableDimensionsTransform(String line2DSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Create the SQL to derive the bounding box of this Line2D SQL
*
* @param line2DSQL the line2d value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doLine2DGetBoundingBoxTransform(String line2DSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Create the SQL to transform a Point2DArray SQL into a Polygon2D
*
* @param pointSQL the point2d value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String transformPoint2DArrayToDatabasePolygon2DFormat(List<String> pointSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Generate the SQL that will return the largest X value within the Line2D
* expression.
*
* @param line2DSQL the line2d value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doLine2DGetMaxXTransform(String line2DSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Generate the SQL that will return the smallest X value within the Line2D
* expression.
*
* @param line2DSQL the line2d value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doLine2DGetMinXTransform(String line2DSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Generate the SQL that will return the largest Y value within the Line2D
* expression.
*
* @param line2DSQL the line2 value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doLine2DGetMaxYTransform(String line2DSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Generate the SQL that will return the smallest Y value within the Line2D
* expression.
*
* @param line2DSQL the line2d value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doLine2DGetMinYTransform(String line2DSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Generate the SQL that will return the largest X value within the Polygon2D
* expression.
*
* @param polygon2DSQL the polygon2d value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doPolygon2DGetMaxXTransform(String polygon2DSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Generate the SQL that will return the smallest X value within the Polygon2D
* expression.
*
* @param polygon2DSQL the polygon2d value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doPolygon2DGetMinXTransform(String polygon2DSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Generate the SQL that will return the largest X value within the Polygon2D
* expression.
*
* @param polygon2DSQL the polygon2d value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doPolygon2DGetMaxYTransform(String polygon2DSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Generate the SQL that will return the smallest Y value within the Polygon2D
* expression.
*
* @param polygon2DSQL the polygon2d value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doPolygon2DGetMinYTransform(String polygon2DSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Generate the SQL that will transform a WKT version of a Polygon2D into the
* database's version of a Polygon2D.
*
* @param polygon2D the polygon2d value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String transformPolygonIntoDatabasePolygon2DFormat(Polygon polygon2D) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Generate SQL to derive the distance between the two Polygon2D expressions.
*
* @param polygon2DSQL the first polygon2d value to compare
* @param otherPolygon2DSQL the second polygon2d value to compare
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL:
*/
public String doPoint2DDistanceBetweenTransform(String polygon2DSQL, String otherPolygon2DSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Generate the SQL to apply rounding to the Number expressions
*
* @param numberSQL the number value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doRoundTransform(String numberSQL) {
return "ROUND(" + numberSQL + ")";
}
/**
* Generate the SQL to apply rounding to the Number expressions with the
* specified number of decimal places.
*
* @param number the number value
* @param decimalPlaces the number value of the decimal places required.
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doRoundWithDecimalPlacesTransform(String number, String decimalPlaces) {
throw new UnsupportedOperationException();
}
/**
* Generate the SQL to use the SUBSTRING_BEFORE function with the 2 String
* expressions.
*
* @param fromThis the string value to be dissected
* @param beforeThis the string value that indicates the end of the required
* text. Not included in the returned value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doSubstringBeforeTransform(String fromThis, String beforeThis) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Generate the SQL to use the SUBSTRING_AFTER function with the 2 String
* expressions.
*
* @param fromThis the string value to be dissected
* @param afterThis the string value that indicates the beginning of the
* required text. Not included in the returned value.
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doSubstringAfterTransform(String fromThis, String afterThis) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Indicates that closing or canceling a statement will cause the connection
* to close as well.
*
* <p>
* Override this method and return FALSE if the database closes connections
* when closing statements
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return TRUE if closing a statement does NOT effect the connection,
* otherwise FALSE.
*/
public boolean willCloseConnectionOnStatementCancel() {
return false;
}
/**
* Indicates that the database driver does not provide the
* Statement.isClosed() method.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return TRUE by default.
*/
public boolean supportsStatementIsClosed() {
return true;
}
/**
* Generates the SQL to determine whether the first (polygon) argument
* contains the second point argument.
*
* @param polygon2DSQL the polygon2d to compare with
* @param point2DSQL the point2d value that might be inside the polygon2d
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doPolygon2DContainsPoint2DTransform(String polygon2DSQL, String point2DSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Generates the SQL to convert the polygon to the standard text version of a
* polygon.
*
* @param polygonSQL the polygon2d value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doPolygon2DAsTextTransform(String polygonSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Generates the SQL required to find whether the 2 lines cross at any point.
*
* @param firstLine the first line2d value to compare
* @param secondLine the second line2d value to compare
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return an SQL expression that will evaluate to TRUE FALSE or NULL,
* depending on whether the lines cross at any point.
*/
public String doLine2DIntersectsLine2DTransform(String firstLine, String secondLine) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Generate the SQL required to find the intersection point of the 2 line
* segment SQL expressions.
*
* @param firstLine the first line2d to compare
* @param secondLine the second line2d to compare
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return an SQL expression that will evaluate to the intersection point of
* the 2 line segments or NULL.
*/
public String doLine2DIntersectionPointWithLine2DTransform(String firstLine, String secondLine) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Generate the SQL required to find the complete set of all points of
* intersection between the tow 2 lines.
*
* @param firstLine the first line2d to compare
* @param secondLine the second line2d to compare
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return an SQL expression that will evaluate to the intersection point of
* the 2 line segments or NULL.
*/
public String doLine2DAllIntersectionPointsWithLine2DTransform(String firstLine, String secondLine) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Convert the String object returned by the database into a JTS LineSegment
* object.
*
* @param lineSegmentAsSQL the database linesegment2d value to create a
* {@link com.vividsolutions.jts.geom.LineSegment JTS LineSegment} with
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a JTS LineSegment derived from the database's response, may be
* null.
* @throws com.vividsolutions.jts.io.ParseException malformed WKT will throw
* an exception
*/
public LineSegment transformDatabaseLineSegment2DValueToJTSLineSegment(String lineSegmentAsSQL) throws com.vividsolutions.jts.io.ParseException {
LineString lineString = null;
WKTReader wktReader = new WKTReader();
Geometry geometry = wktReader.read(lineSegmentAsSQL);
if (geometry instanceof LineString) {
lineString = (LineString) geometry;
if (lineSegmentAsSQL == null) {
return null;
} else {
return new LineSegment(lineString.getCoordinateN(0), lineString.getCoordinateN(1));
}
} else {
throw new IncorrectGeometryReturnedForDatatype(geometry, lineString);
}
}
/**
* Convert the JTS LineSegment object into a SQL expression that the database
* will accept as a line segment.
*
* <p>
* By default, creates a WKT representation
*
* @param lineSegment the LineSegment to convert to database format.
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return an SQL expression that can be interpreted by the database as a line
* segment.
*/
public String transformLineSegmentIntoDatabaseLineSegment2DFormat(LineSegment lineSegment) {
LineString line = (new GeometryFactory()).createLineString(new Coordinate[]{lineSegment.getCoordinate(0), lineSegment.getCoordinate(1)});
String wktValue = line.toText();
return "'" + wktValue + "'";
}
/**
* Generates the database specific SQL for testing whether the 2 line segment
* expressions ever cross.
*
* @param firstSQL the first Line2D value to compare
* @param secondSQL the second Line2D value to compare
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return an SQL expression that will report whether the 2 line segments
* intersect.
* @see
* #doLineSegment2DIntersectionPointWithLineSegment2DTransform(java.lang.String,
* java.lang.String)
*/
public String doLineSegment2DIntersectsLineSegment2DTransform(String firstSQL, String secondSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Generate the SQL required to find the largest X value in the line segment
* SQL expression.
*
* @param lineSegment the LineSegment2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doLineSegment2DGetMaxXTransform(String lineSegment) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Generate the SQL required to find the smallest X value in the line segment
* SQL expression.
*
* @param lineSegment the LineSegment2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doLineSegment2DGetMinXTransform(String lineSegment) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Generate the SQL required to find the largest Y value in the line segment
* SQL expression.
*
* @param lineSegment the LineSegment2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doLineSegment2DGetMaxYTransform(String lineSegment) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Generate the SQL required to find the smallest Y value in the line segment
* SQL expression.
*
* @param lineSegment the LineSegment2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doLineSegment2DGetMinYTransform(String lineSegment) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Generate the SQL required to the rectangular boundary that fully encloses
* the line segment SQL expression.
*
* @param lineSegment the LineSegment2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doLineSegment2DGetBoundingBoxTransform(String lineSegment) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Generate the SQL required to find the dimension of the line segment SQL
* expression.
*
* @param lineSegment the LineSegment2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doLineSegment2DDimensionTransform(String lineSegment) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Generate the SQL required to find whether the 2 line segment SQL
* expressions are NOT equal.
*
* @param firstLineSegment the first LineSegment2D value
* @param secondLineSegment the second LineSegment2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doLineSegment2DNotEqualsTransform(String firstLineSegment, String secondLineSegment) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Generate the SQL required to find whether the 2 line segment SQL
* expressions are equal.
*
* @param firstLineSegment the first LineSegment2D value
* @param secondLineSegment the second LineSegment2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doLineSegment2DEqualsTransform(String firstLineSegment, String secondLineSegment) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Generate the SQL required to convert the line segment SQL expression into
* the WKT string format.
*
* @param lineSegment the LineSegment2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doLineSegment2DAsTextTransform(String lineSegment) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Generate the SQL required to find the intersection point of the 2 line
* segment SQL expressions.
*
* @param firstLineSegment the first LineSegment2D value
* @param secondLineSegment the second LineSegment2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return an SQL expression that will evaluate to the intersection point of
* the 2 line segments or NULL.
*/
public String doLineSegment2DIntersectionPointWithLineSegment2DTransform(String firstLineSegment, String secondLineSegment) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Generate the SQL required to return the starting point of the provided
* LineSegment2D expression.
*
* @param lineSegmentSQL the LineSegment2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doLineSegment2DStartPointTransform(String lineSegmentSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Generate the SQL required to return the starting point of the provided
* LineSegment2D expression.
*
* @param lineSegmentSQL the LineSegment2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doLineSegment2DEndPointTransform(String lineSegmentSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Provide the SQL that correctly represents this MultiPoint2D value in this
* database.
*
* @param points the MultiPoint2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String transformMultiPoint2DToDatabaseMultiPoint2DValue(MultiPoint points) {
String wktValue = points.toText();
return "'" + wktValue + "'";
}
/**
* Convert the database's string representation of a MultiPoint2D value into a
* MultiPoint..
*
* @param pointsAsString the MultiPoint2D value to create a
* {@link com.vividsolutions.jts.geom.MultiPoint JTS MultiPoint} with.
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the MultiPoint2D as a
* {@link com.vividsolutions.jts.geom.MultiPoint JTS MultiPoint} instance
* @throws com.vividsolutions.jts.io.ParseException malformed WKT values will
* throw an exception
*/
public MultiPoint transformDatabaseMultiPoint2DValueToJTSMultiPoint(String pointsAsString) throws com.vividsolutions.jts.io.ParseException {
MultiPoint mpoint = null;
WKTReader wktReader = new WKTReader();
Geometry geometry = wktReader.read(pointsAsString);
if (geometry instanceof MultiPoint) {
mpoint = (MultiPoint) geometry;
} else if (geometry instanceof Point) {
mpoint = (new GeometryFactory().createMultiPoint(new Point[]{((Point) geometry)}));
} else {
throw new IncorrectGeometryReturnedForDatatype(geometry, geometry);
}
return mpoint;
}
/**
* Provide the SQL to compare 2 MultiPoint2Ds using the equivalent of EQUALS.
*
* @param firstMultiPointValue the first MultiPoint2D value to compare
* @param secondMultiPointValue the second MultiPoint2D value to compare
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doMultiPoint2DEqualsTransform(String firstMultiPointValue, String secondMultiPointValue) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Provide the SQL to compare 2 MultiPoint2Ds using the equivalent of NOT
* EQUALS.
*
* @param first the first MultiPoint2D value to compare
* @param second the second MultiPoint2D value to compare
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doMultiPoint2DNotEqualsTransform(String first, String second) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Provide the SQL to get point at the supplied index within the MultiPoint2D
*
* @param first the first MultiPoint2D value to retrieve a point from.
* @param index the index at which the required point is at.
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doMultiPoint2DGetPointAtIndexTransform(String first, String index) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Provides the SQL the derive the number of points in the multipoint2d value.
*
* @param multiPoint2D the MultiPoint2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doMultiPoint2DGetNumberOfPointsTransform(String multiPoint2D) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Provides the SQL the derive the dimension (2 basically) of the MultiPoint2D
* value.
*
* @param multipoint2D the MultiPoint2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doMultiPoint2DMeasurableDimensionsTransform(String multipoint2D) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Provides the SQL the derive the bounding box containing all the points in
* the MultiPoint2D value.
*
* @param multiPoint2D the MultiPoint2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doMultiPoint2DGetBoundingBoxTransform(String multiPoint2D) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Provides the SQL the transform the MultiPoint2D value into a WKT value.
*
* @param multiPoint2D the MultiPoint2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doMultiPoint2DAsTextTransform(String multiPoint2D) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Provides the SQL the transform the MultiPoint2D value into a
* {@link Line2DResult} value.
*
* @param multiPoint2D the MultiPoint2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doMultiPoint2DToLine2DTransform(String multiPoint2D) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
// public String doMultiPoint2DToPolygon2DTransform(String first) {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
// }
/**
* Provides the SQL that will derive the smallest Y value of all the points in
* the MultiPoint2D value
*
* @param multiPoint2D the MultiPoint2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doMultiPoint2DGetMinYTransform(String multiPoint2D) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Provides the SQL that will derive the smallest X value of all the points in
* the MultiPoint2D value
*
* @param multiPoint2D the MultiPoint2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doMultiPoint2DGetMinXTransform(String multiPoint2D) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Provides the SQL that will derive the largest Y value of all the points in
* the MultiPoint2D value
*
* @param multiPoint2D the MultiPoint2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doMultiPoint2DGetMaxYTransform(String multiPoint2D) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Provides the SQL that will derive the largest X value of all the points in
* the MultiPoint2D value
*
* @param multiPoint2D the MultiPoint2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doMultiPoint2DGetMaxXTransform(String multiPoint2D) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Returns true if the database supports has built-in support for limiting
* number of rows returned by a query.
*
* @param options the query options used for this query.
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return TRUE if there is an SQL way of limiting rows numbers, otherwise
* FALSE
*/
public boolean supportsRowLimitsNatively(QueryOptions options) {
return true;
}
/**
* Return if, like Oracle, the database requires Spatial indexes to perform
* standard spatial operations.
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return FALSE by default
*/
public boolean requiresSpatial2DIndexes() {
return false;
}
/**
* Return the sequence of SQL operations required to create the necessary
* Spatial2D indexes.
*
* @param database the database for which we require spatial indexes.
* @param formatTableName the table for which the index should apply.
* @param formatColumnName the column which the index will index.
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return an ordered list of SQL.
*/
public List<String> getSpatial2DIndexSQL(DBDatabase database, String formatTableName, String formatColumnName) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Wrap query with any required syntax to provide paging functionality.
*
* <p>
* Required to support Oracle's ROWNUM-based paging "system".
*
* <p>
* By default the method just returns the sqlQuery.
*
* @param sqlQuery the SQL query to add paging functionality
* @param options the options that apply to the query.
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL
*/
public String doWrapQueryForPaging(String sqlQuery, QueryOptions options) {
return sqlQuery;
}
/**
* Return the number of spatial dimensions that this geometry is defined in.
*
* <p>
* Effectively indicates whether the geometry is 2D, 3D, etc.
*
* @param line2DSQL the Line2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the number of spatial dimensions that this geometry is defined in.
*/
public String doLine2DSpatialDimensionsTransform(String line2DSQL) {
return "2";
}
/**
* Return whether this geometry includes a magnitude (M) value along with X,
* Y, etc.
*
* @param line2DSQL the Line2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return TRUE or FALSE
*/
public String doLine2DHasMagnitudeTransform(String line2DSQL) {
return this.getFalseOperation();
}
/**
* Return the magnitude (M) value of this line.
*
* <p>
* Effectively indicates whether the geometry is 2D or 3D.
*
* @param line2DSQL the Line2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the value for the magnitude, or NULL if there is no magnitude.
*/
public String doLine2DGetMagnitudeTransform(String line2DSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Return the number of spatial dimensions that this geometry is defined in.
*
* <p>
* Effectively indicates whether the geometry is 2D, 3D, etc.
*
* @param point2DSQL the Point2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the number of spatial dimensions that this geometry is defined in.
*/
public String doPoint2DSpatialDimensionsTransform(String point2DSQL) {
return "2";
}
/**
* Return whether this geometry includes a magnitude (M) value along with X,
* Y, etc.
*
* @param point2DSQL the Point2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return TRUE or FALSE
*/
public String doPoint2DHasMagnitudeTransform(String point2DSQL) {
return this.getFalseOperation();
}
/**
* Return the magnitude (M) value of this line.
*
* <p>
* Effectively indicates whether the geometry is 2D or 3D.
*
* @param point2DSQL the Point2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the value for the magnitude, or NULL if there is no magnitude.
*/
public String doPoint2DGetMagnitudeTransform(String point2DSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Return the number of spatial dimensions that this geometry is defined in.
*
* <p>
* Effectively indicates whether the geometry is 2D, 3D, etc.
*
* @param multipoint2DSQL the MultiPoint2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the number of spatial dimensions that this geometry is defined in.
*/
public String doMultiPoint2DSpatialDimensionsTransform(String multipoint2DSQL) {
return "2";
}
/**
* Return whether this geometry includes a magnitude (M) value along with X,
* Y, etc.
*
* @param multipoint2DSQL the MultiPoint2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return TRUE or FALSE
*/
public String doMultiPoint2DHasMagnitudeTransform(String multipoint2DSQL) {
return this.getFalseOperation();
}
/**
* Return the magnitude (M) value of this line.
*
* <p>
* Effectively indicates whether the geometry is 2D or 3D.
*
* @param multipoint2DSQL the MultiPoint2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the value for the magnitude, or NULL if there is no magnitude.
*/
public String doMultiPoint2DGetMagnitudeTransform(String multipoint2DSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Return the number of spatial dimensions that this geometry is defined in.
*
* <p>
* Effectively indicates whether the geometry is 2D, 3D, etc.
*
* @param polygon2DSQL the Polygon2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the number of spatial dimensions that this geometry is defined in.
*/
public String doPolygon2DSpatialDimensionsTransform(String polygon2DSQL) {
return "2";
}
/**
* Return whether this geometry includes a magnitude (M) value along with X,
* Y, etc.
*
* @param polygon2DSQL the Polygon2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return TRUE or FALSE
*/
public String doPolygon2DHasMagnitudeTransform(String polygon2DSQL) {
return this.getFalseOperation();
}
/**
* Return the magnitude (M) value of this line.
*
* <p>
* Effectively indicates whether the geometry is 2D or 3D.
*
* @param polygon2DSQL the Polygon2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the value for the magnitude, or NULL if there is no magnitude.
*/
public String doPolygon2DGetMagnitudeTransform(String polygon2DSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Return the number of spatial dimensions that this geometry is defined in.
*
* <p>
* Effectively indicates whether the geometry is 2D, 3D, etc.
*
* @param lineSegment2DSQL the LineSegment2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the number of spatial dimensions that this geometry is defined in.
*/
public String doLineSegment2DSpatialDimensionsTransform(String lineSegment2DSQL) {
return "2";
}
/**
* Return whether this geometry includes a magnitude (M) value along with X,
* Y, etc.
*
* @param lineSegment2DSQL the LineSegment2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return TRUE or FALSE
*/
public String doLineSegment2DHasMagnitudeTransform(String lineSegment2DSQL) {
return this.getFalseOperation();
}
/**
* Return the magnitude (M) value of this line.
*
* <p>
* Effectively indicates whether the geometry is 2D or 3D.
*
* @param lineSegment2DSQL the LineSegment2D value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the value for the magnitude, or NULL if there is no magnitude.
*/
public String doLineSegment2DGetMagnitudeTransform(String lineSegment2DSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Override this method to provide the SQL that will create a database
* Polygon2D value from the list of presumed coordinates.
*
* <p>
* Coordinates are a series of number values that are presumed to be pairs of
* X and Y values. That is to say the list is a list number values with no
* formatting other than that required to express the values as numbers.
*
* @param coordinateSQL lots of numbers
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a polygon2d value
*/
public String transformCoordinateArrayToDatabasePolygon2DFormat(List<String> coordinateSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Override this method to provide a specific transform that will derive the
* last day of the month from the date value provided.
*
* <p>
* If no override is provided for this method a default implementation will be
* used instead.
*
* @param dateSQL the date value
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the last day of the month that the date is in.
*/
public String doEndOfMonthTransform(String dateSQL) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Override this method to implement changing a date to another time zone.
*
* <p>
* The method should roll the time forward or backward to the correct time for
* the time zone. That is if the date is 12/Aug/2015 10:13:34 GMT+1200 and the
* new time zone is GMT+1000, then the new date should be 12/Aug/2015 8:13:34
* GMT+1000.
*
* <p>
* When implementing this method be aware that time zones are very complex,
* and you will need to deal with "GMT+1345", "PST", "Pacific/Auckland", and
* lots of other variants.
*
* @param dateSQL the date to be move to another time.
* @param timeZone the required time zone
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return SQL representing the date value in the requested time zone.
*/
public String doDateAtTimeZoneTransform(String dateSQL, TimeZone timeZone) throws UnsupportedOperationException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Returns the {@link QueryableDatatype} class to be used with the named
* database specific datatype.
*
* <p>
* This method is called during {@link DBTableClassGenerator} to resolve data
* types that JDBC doesn't recognize into a QDT. In particular anything that
* JDBC reports as {@link java.sql.Types#OTHER} will be resolved using this
* method.
*
* <p>
* The default method returns NULL which causes the generator to use a
* DBJavaObject.
*
* @param typeName
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the class of the QDT that can be used with this columns of this
* type name.
*/
public Class<? extends QueryableDatatype> getQueryableDatatypeClassForSQLDatatype(String typeName) {
if (typeName.toUpperCase().equals("POLYGON")) {
return DBPolygon2D.class;
} else if (typeName.toUpperCase().equals("LINESTRING")) {
return DBLine2D.class;
} else if (typeName.toUpperCase().equals("POINT")) {
return DBPoint2D.class;
} else if (typeName.toUpperCase().equals("MULTIPOINT")) {
return DBMultiPoint2D.class; // obviously this is not going to work in all cases
} else {
return null;
}
}
/**
* Supplies the beginning of the HAVING clause.
*
* <p>
* Default implementation returns "HAVING ".
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return "HAVING "
*/
public String getHavingClauseStart() {
return "HAVING ";
}
/**
* Adapts the query to work for a database that does not support full outer
* join queries.
*
* <p>
* Full outer join queries in this sense use a FULL OUTER join for ALL joins
* in the query.
*
* <p>
* The standard implementation replaces the query with a LEFT OUTER join query
* UNIONed with a RIGHT OUTER join query.
*
* @param querySQL
* @param options
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return a fake full outer join query for databases that don't support FULL
* OUTER joins
*/
public String doWrapQueryToFakeFullOuterJoin(String querySQL, QueryOptions options) {
return "" + querySQL.replaceAll(" FULL OUTER ", " LEFT OUTER ").replaceFirst("; *$", "")
+ " UNION DISTINCT "
+ querySQL.replaceAll(" FULL OUTER ", " RIGHT OUTER ");
}
/**
* The value used for TRUE boolean values.
*
* <p>
* The default method returns " TRUE ".
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return " TRUE "
*/
public String getTrueValue() {
return " TRUE ";
}
/**
* The value used for FALSE boolean values.
*
* <p>
* The default method returns " FALSE ".
*
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return " FALSE "
*/
public String getFalseValue() {
return " FALSE ";
}
/**
* Transforms the boolean statement to a value that can be compared by this
* database.
*
* <p>
* If the database supports comparing booleans (see {@link #supportsComparingBooleanResults()
* }) just return the input.
*
* @param booleanStatement
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the statement transformed so that the value can be compared using
* the standard operators, by default the method returns the input unchanged.
*/
public String doBooleanStatementToBooleanComparisonValueTransform(String booleanStatement) {
if (this.supportsComparingBooleanResults()) {
return booleanStatement;
} else {
return " CASE WHEN " + booleanStatement + " THEN " + getTrueValue() + " WHEN NOT " + booleanStatement + " THEN " + getFalseValue() + " ELSE -1 END ";
}
}
/**
* Transforms the boolean value (as an SQL snippet) to a value that can be
* compared by this database.
*
* <p>
* If the database supports comparing booleans (see {@link #supportsComparingBooleanResults()
* }) just return the input.
*
* @param booleanValue
* <p style="color: #F90;">Support DBvolution at
* <a href="http://patreon.com/dbvolution" target=new>Patreon</a></p>
*
* @return the statement transformed so that the value can be compared using
* the standard operators, by default the method returns the input unchanged.
*/
public String doBooleanValueToBooleanComparisonValueTransform(String booleanValue) {
if (this.supportsComparingBooleanResults()) {
return booleanValue;
} else {
return " CASE WHEN " + booleanValue + " IS NULL THEN -1 ELSE " + booleanValue + " END ";
}
}
}
|
gregorydgraham/DBvolution
|
src/main/java/nz/co/gregs/dbvolution/databases/definitions/DBDefinition.java
|
Java
|
apache-2.0
| 191,012
|
# -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import warnings
from typing import Callable, Dict, Optional, Sequence, Tuple, Union
from google.api_core import grpc_helpers
from google.api_core import gapic_v1
import google.auth # type: ignore
from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
import grpc # type: ignore
from google.cloud.kms_v1.types import resources
from google.cloud.kms_v1.types import service
from google.iam.v1 import iam_policy_pb2 # type: ignore
from google.iam.v1 import policy_pb2 # type: ignore
from .base import KeyManagementServiceTransport, DEFAULT_CLIENT_INFO
class KeyManagementServiceGrpcTransport(KeyManagementServiceTransport):
"""gRPC backend transport for KeyManagementService.
Google Cloud Key Management Service
Manages cryptographic keys and operations using those keys.
Implements a REST model with the following objects:
- [KeyRing][google.cloud.kms.v1.KeyRing]
- [CryptoKey][google.cloud.kms.v1.CryptoKey]
- [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]
- [ImportJob][google.cloud.kms.v1.ImportJob]
If you are using manual gRPC libraries, see `Using gRPC with Cloud
KMS <https://cloud.google.com/kms/docs/grpc>`__.
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
It sends protocol buffers over the wire using gRPC (which is built on
top of HTTP/2); the ``grpcio`` package must be installed.
"""
_stubs: Dict[str, Callable]
def __init__(
self,
*,
host: str = "cloudkms.googleapis.com",
credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Sequence[str] = None,
channel: grpc.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None,
quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
always_use_jwt_access: Optional[bool] = False,
) -> None:
"""Instantiate the transport.
Args:
host (Optional[str]):
The hostname to connect to.
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
This argument is ignored if ``channel`` is provided.
credentials_file (Optional[str]): A file with credentials that can
be loaded with :func:`google.auth.load_credentials_from_file`.
This argument is ignored if ``channel`` is provided.
scopes (Optional(Sequence[str])): A list of scopes. This argument is
ignored if ``channel`` is provided.
channel (Optional[grpc.Channel]): A ``Channel`` instance through
which to make calls.
api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
If provided, it overrides the ``host`` argument and tries to create
a mutual TLS channel with client SSL credentials from
``client_cert_source`` or application default SSL credentials.
client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
Deprecated. A callback to provide client SSL certificate bytes and
private key bytes, both in PEM format. It is ignored if
``api_mtls_endpoint`` is None.
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
for the grpc channel. It is ignored if ``channel`` is provided.
client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
A callback to provide client certificate bytes and private key bytes,
both in PEM format. It is used to configure a mutual TLS channel. It is
ignored if ``channel`` or ``ssl_channel_credentials`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
The client info used to send a user-agent string along with
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
always_use_jwt_access (Optional[bool]): Whether self signed JWT should
be used for service account credentials.
Raises:
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
creation failed for any reason.
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
self._grpc_channel = None
self._ssl_channel_credentials = ssl_channel_credentials
self._stubs: Dict[str, Callable] = {}
if api_mtls_endpoint:
warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
if client_cert_source:
warnings.warn("client_cert_source is deprecated", DeprecationWarning)
if channel:
# Ignore credentials if a channel was passed.
credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
else:
if api_mtls_endpoint:
host = api_mtls_endpoint
# Create SSL credentials with client_cert_source or application
# default SSL credentials.
if client_cert_source:
cert, key = client_cert_source()
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
certificate_chain=cert, private_key=key
)
else:
self._ssl_channel_credentials = SslCredentials().ssl_credentials
else:
if client_cert_source_for_mtls and not ssl_channel_credentials:
cert, key = client_cert_source_for_mtls()
self._ssl_channel_credentials = grpc.ssl_channel_credentials(
certificate_chain=cert, private_key=key
)
# The base transport sets the host, credentials and scopes
super().__init__(
host=host,
credentials=credentials,
credentials_file=credentials_file,
scopes=scopes,
quota_project_id=quota_project_id,
client_info=client_info,
always_use_jwt_access=always_use_jwt_access,
)
if not self._grpc_channel:
self._grpc_channel = type(self).create_channel(
self._host,
# use the credentials which are saved
credentials=self._credentials,
# Set ``credentials_file`` to ``None`` here as
# the credentials that we saved earlier should be used.
credentials_file=None,
scopes=self._scopes,
ssl_credentials=self._ssl_channel_credentials,
quota_project_id=quota_project_id,
options=[
("grpc.max_send_message_length", -1),
("grpc.max_receive_message_length", -1),
],
)
# Wrap messages. This must be done after self._grpc_channel exists
self._prep_wrapped_messages(client_info)
@classmethod
def create_channel(
cls,
host: str = "cloudkms.googleapis.com",
credentials: ga_credentials.Credentials = None,
credentials_file: str = None,
scopes: Optional[Sequence[str]] = None,
quota_project_id: Optional[str] = None,
**kwargs,
) -> grpc.Channel:
"""Create and return a gRPC channel object.
Args:
host (Optional[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
none are specified, the client will attempt to ascertain
the credentials from the environment.
credentials_file (Optional[str]): A file with credentials that can
be loaded with :func:`google.auth.load_credentials_from_file`.
This argument is mutually exclusive with credentials.
scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
service. These are only used when credentials are not specified and
are passed to :func:`google.auth.default`.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
kwargs (Optional[dict]): Keyword arguments, which are passed to the
channel creation.
Returns:
grpc.Channel: A gRPC channel object.
Raises:
google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
and ``credentials_file`` are passed.
"""
return grpc_helpers.create_channel(
host,
credentials=credentials,
credentials_file=credentials_file,
quota_project_id=quota_project_id,
default_scopes=cls.AUTH_SCOPES,
scopes=scopes,
default_host=cls.DEFAULT_HOST,
**kwargs,
)
@property
def grpc_channel(self) -> grpc.Channel:
"""Return the channel designed to connect to this service.
"""
return self._grpc_channel
@property
def list_key_rings(
self,
) -> Callable[[service.ListKeyRingsRequest], service.ListKeyRingsResponse]:
r"""Return a callable for the list key rings method over gRPC.
Lists [KeyRings][google.cloud.kms.v1.KeyRing].
Returns:
Callable[[~.ListKeyRingsRequest],
~.ListKeyRingsResponse]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "list_key_rings" not in self._stubs:
self._stubs["list_key_rings"] = self.grpc_channel.unary_unary(
"/google.cloud.kms.v1.KeyManagementService/ListKeyRings",
request_serializer=service.ListKeyRingsRequest.serialize,
response_deserializer=service.ListKeyRingsResponse.deserialize,
)
return self._stubs["list_key_rings"]
@property
def list_crypto_keys(
self,
) -> Callable[[service.ListCryptoKeysRequest], service.ListCryptoKeysResponse]:
r"""Return a callable for the list crypto keys method over gRPC.
Lists [CryptoKeys][google.cloud.kms.v1.CryptoKey].
Returns:
Callable[[~.ListCryptoKeysRequest],
~.ListCryptoKeysResponse]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "list_crypto_keys" not in self._stubs:
self._stubs["list_crypto_keys"] = self.grpc_channel.unary_unary(
"/google.cloud.kms.v1.KeyManagementService/ListCryptoKeys",
request_serializer=service.ListCryptoKeysRequest.serialize,
response_deserializer=service.ListCryptoKeysResponse.deserialize,
)
return self._stubs["list_crypto_keys"]
@property
def list_crypto_key_versions(
self,
) -> Callable[
[service.ListCryptoKeyVersionsRequest], service.ListCryptoKeyVersionsResponse
]:
r"""Return a callable for the list crypto key versions method over gRPC.
Lists [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion].
Returns:
Callable[[~.ListCryptoKeyVersionsRequest],
~.ListCryptoKeyVersionsResponse]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "list_crypto_key_versions" not in self._stubs:
self._stubs["list_crypto_key_versions"] = self.grpc_channel.unary_unary(
"/google.cloud.kms.v1.KeyManagementService/ListCryptoKeyVersions",
request_serializer=service.ListCryptoKeyVersionsRequest.serialize,
response_deserializer=service.ListCryptoKeyVersionsResponse.deserialize,
)
return self._stubs["list_crypto_key_versions"]
@property
def list_import_jobs(
self,
) -> Callable[[service.ListImportJobsRequest], service.ListImportJobsResponse]:
r"""Return a callable for the list import jobs method over gRPC.
Lists [ImportJobs][google.cloud.kms.v1.ImportJob].
Returns:
Callable[[~.ListImportJobsRequest],
~.ListImportJobsResponse]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "list_import_jobs" not in self._stubs:
self._stubs["list_import_jobs"] = self.grpc_channel.unary_unary(
"/google.cloud.kms.v1.KeyManagementService/ListImportJobs",
request_serializer=service.ListImportJobsRequest.serialize,
response_deserializer=service.ListImportJobsResponse.deserialize,
)
return self._stubs["list_import_jobs"]
@property
def get_key_ring(self) -> Callable[[service.GetKeyRingRequest], resources.KeyRing]:
r"""Return a callable for the get key ring method over gRPC.
Returns metadata for a given
[KeyRing][google.cloud.kms.v1.KeyRing].
Returns:
Callable[[~.GetKeyRingRequest],
~.KeyRing]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "get_key_ring" not in self._stubs:
self._stubs["get_key_ring"] = self.grpc_channel.unary_unary(
"/google.cloud.kms.v1.KeyManagementService/GetKeyRing",
request_serializer=service.GetKeyRingRequest.serialize,
response_deserializer=resources.KeyRing.deserialize,
)
return self._stubs["get_key_ring"]
@property
def get_crypto_key(
self,
) -> Callable[[service.GetCryptoKeyRequest], resources.CryptoKey]:
r"""Return a callable for the get crypto key method over gRPC.
Returns metadata for a given
[CryptoKey][google.cloud.kms.v1.CryptoKey], as well as its
[primary][google.cloud.kms.v1.CryptoKey.primary]
[CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion].
Returns:
Callable[[~.GetCryptoKeyRequest],
~.CryptoKey]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "get_crypto_key" not in self._stubs:
self._stubs["get_crypto_key"] = self.grpc_channel.unary_unary(
"/google.cloud.kms.v1.KeyManagementService/GetCryptoKey",
request_serializer=service.GetCryptoKeyRequest.serialize,
response_deserializer=resources.CryptoKey.deserialize,
)
return self._stubs["get_crypto_key"]
@property
def get_crypto_key_version(
self,
) -> Callable[[service.GetCryptoKeyVersionRequest], resources.CryptoKeyVersion]:
r"""Return a callable for the get crypto key version method over gRPC.
Returns metadata for a given
[CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion].
Returns:
Callable[[~.GetCryptoKeyVersionRequest],
~.CryptoKeyVersion]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "get_crypto_key_version" not in self._stubs:
self._stubs["get_crypto_key_version"] = self.grpc_channel.unary_unary(
"/google.cloud.kms.v1.KeyManagementService/GetCryptoKeyVersion",
request_serializer=service.GetCryptoKeyVersionRequest.serialize,
response_deserializer=resources.CryptoKeyVersion.deserialize,
)
return self._stubs["get_crypto_key_version"]
@property
def get_public_key(
self,
) -> Callable[[service.GetPublicKeyRequest], resources.PublicKey]:
r"""Return a callable for the get public key method over gRPC.
Returns the public key for the given
[CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. The
[CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must
be
[ASYMMETRIC_SIGN][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN]
or
[ASYMMETRIC_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_DECRYPT].
Returns:
Callable[[~.GetPublicKeyRequest],
~.PublicKey]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "get_public_key" not in self._stubs:
self._stubs["get_public_key"] = self.grpc_channel.unary_unary(
"/google.cloud.kms.v1.KeyManagementService/GetPublicKey",
request_serializer=service.GetPublicKeyRequest.serialize,
response_deserializer=resources.PublicKey.deserialize,
)
return self._stubs["get_public_key"]
@property
def get_import_job(
self,
) -> Callable[[service.GetImportJobRequest], resources.ImportJob]:
r"""Return a callable for the get import job method over gRPC.
Returns metadata for a given
[ImportJob][google.cloud.kms.v1.ImportJob].
Returns:
Callable[[~.GetImportJobRequest],
~.ImportJob]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "get_import_job" not in self._stubs:
self._stubs["get_import_job"] = self.grpc_channel.unary_unary(
"/google.cloud.kms.v1.KeyManagementService/GetImportJob",
request_serializer=service.GetImportJobRequest.serialize,
response_deserializer=resources.ImportJob.deserialize,
)
return self._stubs["get_import_job"]
@property
def create_key_ring(
self,
) -> Callable[[service.CreateKeyRingRequest], resources.KeyRing]:
r"""Return a callable for the create key ring method over gRPC.
Create a new [KeyRing][google.cloud.kms.v1.KeyRing] in a given
Project and Location.
Returns:
Callable[[~.CreateKeyRingRequest],
~.KeyRing]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "create_key_ring" not in self._stubs:
self._stubs["create_key_ring"] = self.grpc_channel.unary_unary(
"/google.cloud.kms.v1.KeyManagementService/CreateKeyRing",
request_serializer=service.CreateKeyRingRequest.serialize,
response_deserializer=resources.KeyRing.deserialize,
)
return self._stubs["create_key_ring"]
@property
def create_crypto_key(
self,
) -> Callable[[service.CreateCryptoKeyRequest], resources.CryptoKey]:
r"""Return a callable for the create crypto key method over gRPC.
Create a new [CryptoKey][google.cloud.kms.v1.CryptoKey] within a
[KeyRing][google.cloud.kms.v1.KeyRing].
[CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] and
[CryptoKey.version_template.algorithm][google.cloud.kms.v1.CryptoKeyVersionTemplate.algorithm]
are required.
Returns:
Callable[[~.CreateCryptoKeyRequest],
~.CryptoKey]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "create_crypto_key" not in self._stubs:
self._stubs["create_crypto_key"] = self.grpc_channel.unary_unary(
"/google.cloud.kms.v1.KeyManagementService/CreateCryptoKey",
request_serializer=service.CreateCryptoKeyRequest.serialize,
response_deserializer=resources.CryptoKey.deserialize,
)
return self._stubs["create_crypto_key"]
@property
def create_crypto_key_version(
self,
) -> Callable[[service.CreateCryptoKeyVersionRequest], resources.CryptoKeyVersion]:
r"""Return a callable for the create crypto key version method over gRPC.
Create a new
[CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in a
[CryptoKey][google.cloud.kms.v1.CryptoKey].
The server will assign the next sequential id. If unset,
[state][google.cloud.kms.v1.CryptoKeyVersion.state] will be set
to
[ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED].
Returns:
Callable[[~.CreateCryptoKeyVersionRequest],
~.CryptoKeyVersion]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "create_crypto_key_version" not in self._stubs:
self._stubs["create_crypto_key_version"] = self.grpc_channel.unary_unary(
"/google.cloud.kms.v1.KeyManagementService/CreateCryptoKeyVersion",
request_serializer=service.CreateCryptoKeyVersionRequest.serialize,
response_deserializer=resources.CryptoKeyVersion.deserialize,
)
return self._stubs["create_crypto_key_version"]
@property
def import_crypto_key_version(
self,
) -> Callable[[service.ImportCryptoKeyVersionRequest], resources.CryptoKeyVersion]:
r"""Return a callable for the import crypto key version method over gRPC.
Import wrapped key material into a
[CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion].
All requests must specify a
[CryptoKey][google.cloud.kms.v1.CryptoKey]. If a
[CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] is
additionally specified in the request, key material will be
reimported into that version. Otherwise, a new version will be
created, and will be assigned the next sequential id within the
[CryptoKey][google.cloud.kms.v1.CryptoKey].
Returns:
Callable[[~.ImportCryptoKeyVersionRequest],
~.CryptoKeyVersion]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "import_crypto_key_version" not in self._stubs:
self._stubs["import_crypto_key_version"] = self.grpc_channel.unary_unary(
"/google.cloud.kms.v1.KeyManagementService/ImportCryptoKeyVersion",
request_serializer=service.ImportCryptoKeyVersionRequest.serialize,
response_deserializer=resources.CryptoKeyVersion.deserialize,
)
return self._stubs["import_crypto_key_version"]
@property
def create_import_job(
self,
) -> Callable[[service.CreateImportJobRequest], resources.ImportJob]:
r"""Return a callable for the create import job method over gRPC.
Create a new [ImportJob][google.cloud.kms.v1.ImportJob] within a
[KeyRing][google.cloud.kms.v1.KeyRing].
[ImportJob.import_method][google.cloud.kms.v1.ImportJob.import_method]
is required.
Returns:
Callable[[~.CreateImportJobRequest],
~.ImportJob]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "create_import_job" not in self._stubs:
self._stubs["create_import_job"] = self.grpc_channel.unary_unary(
"/google.cloud.kms.v1.KeyManagementService/CreateImportJob",
request_serializer=service.CreateImportJobRequest.serialize,
response_deserializer=resources.ImportJob.deserialize,
)
return self._stubs["create_import_job"]
@property
def update_crypto_key(
self,
) -> Callable[[service.UpdateCryptoKeyRequest], resources.CryptoKey]:
r"""Return a callable for the update crypto key method over gRPC.
Update a [CryptoKey][google.cloud.kms.v1.CryptoKey].
Returns:
Callable[[~.UpdateCryptoKeyRequest],
~.CryptoKey]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "update_crypto_key" not in self._stubs:
self._stubs["update_crypto_key"] = self.grpc_channel.unary_unary(
"/google.cloud.kms.v1.KeyManagementService/UpdateCryptoKey",
request_serializer=service.UpdateCryptoKeyRequest.serialize,
response_deserializer=resources.CryptoKey.deserialize,
)
return self._stubs["update_crypto_key"]
@property
def update_crypto_key_version(
self,
) -> Callable[[service.UpdateCryptoKeyVersionRequest], resources.CryptoKeyVersion]:
r"""Return a callable for the update crypto key version method over gRPC.
Update a
[CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]'s
metadata.
[state][google.cloud.kms.v1.CryptoKeyVersion.state] may be
changed between
[ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED]
and
[DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED]
using this method. See
[DestroyCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.DestroyCryptoKeyVersion]
and
[RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion]
to move between other states.
Returns:
Callable[[~.UpdateCryptoKeyVersionRequest],
~.CryptoKeyVersion]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "update_crypto_key_version" not in self._stubs:
self._stubs["update_crypto_key_version"] = self.grpc_channel.unary_unary(
"/google.cloud.kms.v1.KeyManagementService/UpdateCryptoKeyVersion",
request_serializer=service.UpdateCryptoKeyVersionRequest.serialize,
response_deserializer=resources.CryptoKeyVersion.deserialize,
)
return self._stubs["update_crypto_key_version"]
@property
def update_crypto_key_primary_version(
self,
) -> Callable[[service.UpdateCryptoKeyPrimaryVersionRequest], resources.CryptoKey]:
r"""Return a callable for the update crypto key primary
version method over gRPC.
Update the version of a
[CryptoKey][google.cloud.kms.v1.CryptoKey] that will be used in
[Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt].
Returns an error if called on a key whose purpose is not
[ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT].
Returns:
Callable[[~.UpdateCryptoKeyPrimaryVersionRequest],
~.CryptoKey]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "update_crypto_key_primary_version" not in self._stubs:
self._stubs[
"update_crypto_key_primary_version"
] = self.grpc_channel.unary_unary(
"/google.cloud.kms.v1.KeyManagementService/UpdateCryptoKeyPrimaryVersion",
request_serializer=service.UpdateCryptoKeyPrimaryVersionRequest.serialize,
response_deserializer=resources.CryptoKey.deserialize,
)
return self._stubs["update_crypto_key_primary_version"]
@property
def destroy_crypto_key_version(
self,
) -> Callable[[service.DestroyCryptoKeyVersionRequest], resources.CryptoKeyVersion]:
r"""Return a callable for the destroy crypto key version method over gRPC.
Schedule a
[CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] for
destruction.
Upon calling this method,
[CryptoKeyVersion.state][google.cloud.kms.v1.CryptoKeyVersion.state]
will be set to
[DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED],
and
[destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time]
will be set to the time
[destroy_scheduled_duration][google.cloud.kms.v1.CryptoKey.destroy_scheduled_duration]
in the future. At that time, the
[state][google.cloud.kms.v1.CryptoKeyVersion.state] will
automatically change to
[DESTROYED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED],
and the key material will be irrevocably destroyed.
Before the
[destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time]
is reached,
[RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion]
may be called to reverse the process.
Returns:
Callable[[~.DestroyCryptoKeyVersionRequest],
~.CryptoKeyVersion]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "destroy_crypto_key_version" not in self._stubs:
self._stubs["destroy_crypto_key_version"] = self.grpc_channel.unary_unary(
"/google.cloud.kms.v1.KeyManagementService/DestroyCryptoKeyVersion",
request_serializer=service.DestroyCryptoKeyVersionRequest.serialize,
response_deserializer=resources.CryptoKeyVersion.deserialize,
)
return self._stubs["destroy_crypto_key_version"]
@property
def restore_crypto_key_version(
self,
) -> Callable[[service.RestoreCryptoKeyVersionRequest], resources.CryptoKeyVersion]:
r"""Return a callable for the restore crypto key version method over gRPC.
Restore a
[CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] in the
[DESTROY_SCHEDULED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED]
state.
Upon restoration of the CryptoKeyVersion,
[state][google.cloud.kms.v1.CryptoKeyVersion.state] will be set
to
[DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED],
and
[destroy_time][google.cloud.kms.v1.CryptoKeyVersion.destroy_time]
will be cleared.
Returns:
Callable[[~.RestoreCryptoKeyVersionRequest],
~.CryptoKeyVersion]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "restore_crypto_key_version" not in self._stubs:
self._stubs["restore_crypto_key_version"] = self.grpc_channel.unary_unary(
"/google.cloud.kms.v1.KeyManagementService/RestoreCryptoKeyVersion",
request_serializer=service.RestoreCryptoKeyVersionRequest.serialize,
response_deserializer=resources.CryptoKeyVersion.deserialize,
)
return self._stubs["restore_crypto_key_version"]
@property
def encrypt(self) -> Callable[[service.EncryptRequest], service.EncryptResponse]:
r"""Return a callable for the encrypt method over gRPC.
Encrypts data, so that it can only be recovered by a call to
[Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. The
[CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must
be
[ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT].
Returns:
Callable[[~.EncryptRequest],
~.EncryptResponse]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "encrypt" not in self._stubs:
self._stubs["encrypt"] = self.grpc_channel.unary_unary(
"/google.cloud.kms.v1.KeyManagementService/Encrypt",
request_serializer=service.EncryptRequest.serialize,
response_deserializer=service.EncryptResponse.deserialize,
)
return self._stubs["encrypt"]
@property
def decrypt(self) -> Callable[[service.DecryptRequest], service.DecryptResponse]:
r"""Return a callable for the decrypt method over gRPC.
Decrypts data that was protected by
[Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt]. The
[CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] must
be
[ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT].
Returns:
Callable[[~.DecryptRequest],
~.DecryptResponse]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "decrypt" not in self._stubs:
self._stubs["decrypt"] = self.grpc_channel.unary_unary(
"/google.cloud.kms.v1.KeyManagementService/Decrypt",
request_serializer=service.DecryptRequest.serialize,
response_deserializer=service.DecryptResponse.deserialize,
)
return self._stubs["decrypt"]
@property
def asymmetric_sign(
self,
) -> Callable[[service.AsymmetricSignRequest], service.AsymmetricSignResponse]:
r"""Return a callable for the asymmetric sign method over gRPC.
Signs data using a
[CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with
[CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose]
ASYMMETRIC_SIGN, producing a signature that can be verified with
the public key retrieved from
[GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey].
Returns:
Callable[[~.AsymmetricSignRequest],
~.AsymmetricSignResponse]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "asymmetric_sign" not in self._stubs:
self._stubs["asymmetric_sign"] = self.grpc_channel.unary_unary(
"/google.cloud.kms.v1.KeyManagementService/AsymmetricSign",
request_serializer=service.AsymmetricSignRequest.serialize,
response_deserializer=service.AsymmetricSignResponse.deserialize,
)
return self._stubs["asymmetric_sign"]
@property
def asymmetric_decrypt(
self,
) -> Callable[
[service.AsymmetricDecryptRequest], service.AsymmetricDecryptResponse
]:
r"""Return a callable for the asymmetric decrypt method over gRPC.
Decrypts data that was encrypted with a public key retrieved
from
[GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]
corresponding to a
[CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with
[CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose]
ASYMMETRIC_DECRYPT.
Returns:
Callable[[~.AsymmetricDecryptRequest],
~.AsymmetricDecryptResponse]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "asymmetric_decrypt" not in self._stubs:
self._stubs["asymmetric_decrypt"] = self.grpc_channel.unary_unary(
"/google.cloud.kms.v1.KeyManagementService/AsymmetricDecrypt",
request_serializer=service.AsymmetricDecryptRequest.serialize,
response_deserializer=service.AsymmetricDecryptResponse.deserialize,
)
return self._stubs["asymmetric_decrypt"]
@property
def mac_sign(self) -> Callable[[service.MacSignRequest], service.MacSignResponse]:
r"""Return a callable for the mac sign method over gRPC.
Signs data using a
[CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with
[CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] MAC,
producing a tag that can be verified by another source with the
same key.
Returns:
Callable[[~.MacSignRequest],
~.MacSignResponse]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "mac_sign" not in self._stubs:
self._stubs["mac_sign"] = self.grpc_channel.unary_unary(
"/google.cloud.kms.v1.KeyManagementService/MacSign",
request_serializer=service.MacSignRequest.serialize,
response_deserializer=service.MacSignResponse.deserialize,
)
return self._stubs["mac_sign"]
@property
def mac_verify(
self,
) -> Callable[[service.MacVerifyRequest], service.MacVerifyResponse]:
r"""Return a callable for the mac verify method over gRPC.
Verifies MAC tag using a
[CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with
[CryptoKey.purpose][google.cloud.kms.v1.CryptoKey.purpose] MAC,
and returns a response that indicates whether or not the
verification was successful.
Returns:
Callable[[~.MacVerifyRequest],
~.MacVerifyResponse]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "mac_verify" not in self._stubs:
self._stubs["mac_verify"] = self.grpc_channel.unary_unary(
"/google.cloud.kms.v1.KeyManagementService/MacVerify",
request_serializer=service.MacVerifyRequest.serialize,
response_deserializer=service.MacVerifyResponse.deserialize,
)
return self._stubs["mac_verify"]
@property
def generate_random_bytes(
self,
) -> Callable[
[service.GenerateRandomBytesRequest], service.GenerateRandomBytesResponse
]:
r"""Return a callable for the generate random bytes method over gRPC.
Generate random bytes using the Cloud KMS randomness
source in the provided location.
Returns:
Callable[[~.GenerateRandomBytesRequest],
~.GenerateRandomBytesResponse]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "generate_random_bytes" not in self._stubs:
self._stubs["generate_random_bytes"] = self.grpc_channel.unary_unary(
"/google.cloud.kms.v1.KeyManagementService/GenerateRandomBytes",
request_serializer=service.GenerateRandomBytesRequest.serialize,
response_deserializer=service.GenerateRandomBytesResponse.deserialize,
)
return self._stubs["generate_random_bytes"]
@property
def set_iam_policy(
self,
) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]:
r"""Return a callable for the set iam policy method over gRPC.
Sets the IAM access control policy on the specified
function. Replaces any existing policy.
Returns:
Callable[[~.SetIamPolicyRequest],
~.Policy]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "set_iam_policy" not in self._stubs:
self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary(
"/google.iam.v1.IAMPolicy/SetIamPolicy",
request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString,
response_deserializer=policy_pb2.Policy.FromString,
)
return self._stubs["set_iam_policy"]
@property
def get_iam_policy(
self,
) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]:
r"""Return a callable for the get iam policy method over gRPC.
Gets the IAM access control policy for a function.
Returns an empty policy if the function exists and does
not have a policy set.
Returns:
Callable[[~.GetIamPolicyRequest],
~.Policy]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "get_iam_policy" not in self._stubs:
self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary(
"/google.iam.v1.IAMPolicy/GetIamPolicy",
request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString,
response_deserializer=policy_pb2.Policy.FromString,
)
return self._stubs["get_iam_policy"]
@property
def test_iam_permissions(
self,
) -> Callable[
[iam_policy_pb2.TestIamPermissionsRequest],
iam_policy_pb2.TestIamPermissionsResponse,
]:
r"""Return a callable for the test iam permissions method over gRPC.
Tests the specified permissions against the IAM access control
policy for a function. If the function does not exist, this will
return an empty set of permissions, not a NOT_FOUND error.
Returns:
Callable[[~.TestIamPermissionsRequest],
~.TestIamPermissionsResponse]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "test_iam_permissions" not in self._stubs:
self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary(
"/google.iam.v1.IAMPolicy/TestIamPermissions",
request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString,
response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString,
)
return self._stubs["test_iam_permissions"]
def close(self):
self.grpc_channel.close()
__all__ = ("KeyManagementServiceGrpcTransport",)
|
googleapis/python-kms
|
google/cloud/kms_v1/services/key_management_service/transports/grpc.py
|
Python
|
apache-2.0
| 50,118
|
---
title: "Quickstart"
nav-title: '<i class="fa fa-power-off title appetizer" aria-hidden="true"></i> Quickstart'
nav-parent_id: root
nav-pos: 2
---
<!--
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.
-->
* This will be replaced by the TOC
{:toc}
Get a Flink example program up and running in a few simple steps.
## Setup: Download and Start Flink
Flink runs on __Linux, Mac OS X, and Windows__. To be able to run Flink, the only requirement is to have a working __Java 7.x__ (or higher) installation. Windows users, please take a look at the [Flink on Windows]({{ site.baseurl }}/start/flink_on_windows.html) guide which describes how to run Flink on Windows for local setups.
You can check the correct installation of Java by issuing the following command:
~~~bash
java -version
~~~
If you have Java 8, the output will look something like this:
~~~bash
java version "1.8.0_111"
Java(TM) SE Runtime Environment (build 1.8.0_111-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.111-b14, mixed mode)
~~~
{% if site.is_stable %}
<div class="codetabs" markdown="1">
<div data-lang="Download and Unpack" markdown="1">
1. Download a binary from the [downloads page](http://flink.apache.org/downloads.html). You can pick
any Hadoop/Scala combination you like. If you plan to just use the local file system, any Hadoop
version will work fine.
2. Go to the download directory.
3. Unpack the downloaded archive.
~~~bash
$ cd ~/Downloads # Go to download directory
$ tar xzf flink-*.tgz # Unpack the downloaded archive
$ cd flink-{{site.version}}
~~~
</div>
<div data-lang="MacOS X" markdown="1">
For MacOS X users, Flink can be installed through [Homebrew](https://brew.sh/).
~~~bash
$ brew install apache-flink
...
$ flink --version
Version: 1.2.0, Commit ID: 1c659cf
~~~
</div>
</div>
{% else %}
### Download and Compile
Clone the source code from one of our [repositories](http://flink.apache.org/community.html#source-code), e.g.:
~~~bash
$ git clone https://github.com/apache/flink.git
$ cd flink
$ mvn clean package -DskipTests # this will take up to 10 minutes
$ cd build-target # this is where Flink is installed to
~~~
{% endif %}
### Start a Local Flink Cluster
~~~bash
$ ./bin/start-local.sh # Start Flink
~~~
Check the __JobManager's web frontend__ at [http://localhost:8081](http://localhost:8081) and make sure everything is up and running. The web frontend should report a single available TaskManager instance.
<a href="{{ site.baseurl }}/page/img/quickstart-setup/jobmanager-1.png" ><img class="img-responsive" src="{{ site.baseurl }}/page/img/quickstart-setup/jobmanager-1.png" alt="JobManager: Overview"/></a>
You can also verify that the system is running by checking the log files in the `logs` directory:
~~~bash
$ tail log/flink-*-jobmanager-*.log
INFO ... - Starting JobManager
INFO ... - Starting JobManager web frontend
INFO ... - Web frontend listening at 127.0.0.1:8081
INFO ... - Registered TaskManager at 127.0.0.1 (akka://flink/user/taskmanager)
~~~
## Read the Code
You can find the complete source code for this SocketWindowWordCount example in [scala](https://github.com/apache/flink/blob/master/flink-examples/flink-examples-streaming/src/main/scala/org/apache/flink/streaming/scala/examples/socket/SocketWindowWordCount.scala) and [java](https://github.com/apache/flink/blob/master/flink-examples/flink-examples-streaming/src/main/java/org/apache/flink/streaming/examples/socket/SocketWindowWordCount.java) on GitHub.
<div class="codetabs" markdown="1">
<div data-lang="scala" markdown="1">
{% highlight scala %}
object SocketWindowWordCount {
def main(args: Array[String]) : Unit = {
// the port to connect to
val port: Int = try {
ParameterTool.fromArgs(args).getInt("port")
} catch {
case e: Exception => {
System.err.println("No port specified. Please run 'SocketWindowWordCount --port <port>'")
return
}
}
// get the execution environment
val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment
// get input data by connecting to the socket
val text = env.socketTextStream("localhost", port, '\n')
// parse the data, group it, window it, and aggregate the counts
val windowCounts = text
.flatMap { w => w.split("\\s") }
.map { w => WordWithCount(w, 1) }
.keyBy("word")
.timeWindow(Time.seconds(5), Time.seconds(1))
.sum("count")
// print the results with a single thread, rather than in parallel
windowCounts.print().setParallelism(1)
env.execute("Socket Window WordCount")
}
// Data type for words with count
case class WordWithCount(word: String, count: Long)
}
{% endhighlight %}
</div>
<div data-lang="java" markdown="1">
{% highlight java %}
public class SocketWindowWordCount {
public static void main(String[] args) throws Exception {
// the port to connect to
final int port;
try {
final ParameterTool params = ParameterTool.fromArgs(args);
port = params.getInt("port");
} catch (Exception e) {
System.err.println("No port specified. Please run 'SocketWindowWordCount --port <port>'");
return;
}
// get the execution environment
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// get input data by connecting to the socket
DataStream<String> text = env.socketTextStream("localhost", port, "\n");
// parse the data, group it, window it, and aggregate the counts
DataStream<WordWithCount> windowCounts = text
.flatMap(new FlatMapFunction<String, WordWithCount>() {
@Override
public void flatMap(String value, Collector<WordWithCount> out) {
for (String word : value.split("\\s")) {
out.collect(new WordWithCount(word, 1L));
}
}
})
.keyBy("word")
.timeWindow(Time.seconds(5), Time.seconds(1))
.reduce(new ReduceFunction<WordWithCount>() {
@Override
public WordWithCount reduce(WordWithCount a, WordWithCount b) {
return new WordWithCount(a.word, a.count + b.count);
}
});
// print the results with a single thread, rather than in parallel
windowCounts.print().setParallelism(1);
env.execute("Socket Window WordCount");
}
// Data type for words with count
public static class WordWithCount {
public String word;
public long count;
public WordWithCount() {}
public WordWithCount(String word, long count) {
this.word = word;
this.count = count;
}
@Override
public String toString() {
return word + " : " + count;
}
}
}
{% endhighlight %}
</div>
</div>
## Run the Example
Now, we are going to run this Flink application. It will read text from
a socket and once every 5 seconds print the number of occurrences of
each distinct word during the previous 5 seconds, i.e. a tumbling
window of processing time, as long as words are floating in.
* First of all, we use **netcat** to start local server via
~~~bash
$ nc -l 9000
~~~
* Submit the Flink program:
~~~bash
$ ./bin/flink run examples/streaming/SocketWindowWordCount.jar --port 9000
Cluster configuration: Standalone cluster with JobManager at /127.0.0.1:6123
Using address 127.0.0.1:6123 to connect to JobManager.
JobManager web interface address http://127.0.0.1:8081
Starting execution of program
Submitting job with JobID: 574a10c8debda3dccd0c78a3bde55e1b. Waiting for job completion.
Connected to JobManager at Actor[akka.tcp://flink@127.0.0.1:6123/user/jobmanager#297388688]
11/04/2016 14:04:50 Job execution switched to status RUNNING.
11/04/2016 14:04:50 Source: Socket Stream -> Flat Map(1/1) switched to SCHEDULED
11/04/2016 14:04:50 Source: Socket Stream -> Flat Map(1/1) switched to DEPLOYING
11/04/2016 14:04:50 Fast TumblingProcessingTimeWindows(5000) of WindowedStream.main(SocketWindowWordCount.java:79) -> Sink: Unnamed(1/1) switched to SCHEDULED
11/04/2016 14:04:51 Fast TumblingProcessingTimeWindows(5000) of WindowedStream.main(SocketWindowWordCount.java:79) -> Sink: Unnamed(1/1) switched to DEPLOYING
11/04/2016 14:04:51 Fast TumblingProcessingTimeWindows(5000) of WindowedStream.main(SocketWindowWordCount.java:79) -> Sink: Unnamed(1/1) switched to RUNNING
11/04/2016 14:04:51 Source: Socket Stream -> Flat Map(1/1) switched to RUNNING
~~~
The program connects to the socket and waits for input. You can check the web interface to verify that the job is running as expected:
<div class="row">
<div class="col-sm-6">
<a href="{{ site.baseurl }}/page/img/quickstart-setup/jobmanager-2.png" ><img class="img-responsive" src="{{ site.baseurl }}/page/img/quickstart-setup/jobmanager-2.png" alt="JobManager: Overview (cont'd)"/></a>
</div>
<div class="col-sm-6">
<a href="{{ site.baseurl }}/page/img/quickstart-setup/jobmanager-3.png" ><img class="img-responsive" src="{{ site.baseurl }}/page/img/quickstart-setup/jobmanager-3.png" alt="JobManager: Running Jobs"/></a>
</div>
</div>
* Words are counted in time windows of 5 seconds (processing time, tumbling
windows) and are printed to `stdout`. Monitor the TaskManager's output file
and write some text in `nc` (input is sent to Flink line by line after
hitting <RETURN>):
~~~bash
$ nc -l 9000
lorem ipsum
ipsum ipsum ipsum
bye
~~~
The `.out` file will print the counts at the end of each time window as long
as words are floating in, e.g.:
~~~bash
$ tail -f log/flink-*-taskmanager-*.out
lorem : 1
bye : 1
ipsum : 4
~~~~
To **stop** Flink when you're done type:
~~~bash
$ ./bin/stop-local.sh
~~~
## Next Steps
Check out some more [examples]({{ site.baseurl }}/examples) to get a better feel for Flink's programming APIs. When you are done with that, go ahead and read the [streaming guide]({{ site.baseurl }}/dev/datastream_api.html).
|
PangZhi/flink
|
docs/quickstart/setup_quickstart.md
|
Markdown
|
apache-2.0
| 11,092
|
export default function reducer(google = {}, action) {
switch (action.type) {
case 'GOOGLE_SET':
return { ...google, ...action.data };
default:
return google;
}
}
|
jaedb/Iris
|
src/js/services/google/reducer.js
|
JavaScript
|
apache-2.0
| 195
|
// Copyright 2022 The Google Research 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.
#include "sparse/ops/cc/common.h"
#include "sparse/ops/cc/sparse_softmax_launcher.h"
#include "tensorflow/core/framework/op_kernel.h"
namespace sgk {
using ::tensorflow::Tensor;
using ::tensorflow::TensorShapeUtils;
using ::tensorflow::errors::InvalidArgument;
template <typename Device, typename T>
class SparseSoftmaxOp : public tensorflow::OpKernel {
public:
explicit SparseSoftmaxOp(tensorflow::OpKernelConstruction* context)
: OpKernel(context) {}
void Compute(tensorflow::OpKernelContext* context) override {
// Collect the input & output tensors.
const Tensor& values = context->input(0);
const Tensor& row_indices = context->input(1);
const Tensor& row_offsets = context->input(2);
const Tensor& column_indices = context->input(3);
// Validate the input shapes.
OP_REQUIRES(context, TensorShapeUtils::IsVector(row_indices.shape()),
InvalidArgument("Expected 1-dimension row_indices tensor."));
OP_REQUIRES(context, TensorShapeUtils::IsVector(row_offsets.shape()),
InvalidArgument("Expected 1-dimension row_offsets tensor."));
OP_REQUIRES(context, TensorShapeUtils::IsVector(column_indices.shape()),
InvalidArgument("Expected 1-dimension column_indices tensor."));
OP_REQUIRES(context, row_indices.dim_size(0) + 1 == row_offsets.dim_size(0),
InvalidArgument("Expected 1 more row index than offset."));
OP_REQUIRES(
context,
TensorShapeUtils::IsVector(values.shape()) || values.dims() == 2,
InvalidArgument("Expected 1-dim or 2-dim values tensor."));
// Get the problem shape.
//
// NOTE: The kernel doesn't actually need the n argument. Pass garbage,
// since we can't pull it off the sparse matrix representation.
int m = row_indices.dim_size(0);
int n = -1;
int nonzeros = column_indices.dim_size(0);
int dim_offset = values.dims() - 1;
int replication = dim_offset == 1 ? values.dim_size(0) : 1;
// Validate the sparse matrix shape.
OP_REQUIRES(context, values.dim_size(dim_offset) == nonzeros,
InvalidArgument("Num values must equal num col indices."));
// Allocate the output tensor.
Tensor* output_values = nullptr;
OP_REQUIRES_OK(context,
context->allocate_output(0, values.shape(), &output_values));
// Launch the kernel for each step of computation.
//
// TODO(tgale): This could be accelerated by supported replicated/batched
// execution in the kernel. Running the kernel is a loop like this could
// incur significant overhead from kernel launch latency if the computation
// is cheap.
for (int idx = 0; idx < replication; ++idx) {
LaunchSparseSoftmax(context->eigen_device<Device>(), m, n, nonzeros,
values.flat<float>().data() + nonzeros * idx,
AsInt32<1>(row_indices), AsInt32<1>(row_offsets),
AsInt32<1>(column_indices),
output_values->flat<float>().data() + nonzeros * idx);
}
}
};
#ifdef GOOGLE_CUDA
REGISTER_KERNEL_BUILDER(Name("CsrSoftmax").Device(tensorflow::DEVICE_GPU),
SparseSoftmaxOp<Eigen::GpuDevice, float>);
#endif // GOOGLE_CUDA
} // namespace sgk
|
google-research/google-research
|
sgk/sparse/ops/cc/sparse_softmax_op.cc
|
C++
|
apache-2.0
| 3,905
|
//
// UIViewController+Common.h
// HappyWeekDayer
//
// Created by scjy on 16/1/6.
// Copyright © 2016年 李志鹏. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIViewController (Common)
- (void)showBackButtonWithImage:(NSString *)imageName;
- (void)showRightButtonWithTitle:(NSString *)Title;
@end
|
BurapaLi/HaoppyWeekDayer
|
HappyWeekDayer/Library/UIViewController+Common.h
|
C
|
apache-2.0
| 321
|
// +build linux
package sh_test
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"os/exec"
"strings"
"testing"
)
var (
enableUserNS bool
)
func init() {
const usernsOk = "1"
const kernelcfg = "CONFIG_USER_NS"
logUsernsDetection := func(err error) {
if enableUserNS {
fmt.Printf("Linux user namespaces enabled!")
return
}
fmt.Printf("Warning: Impossible to know if kernel support USER namespace.\n")
fmt.Printf("Warning: USER namespace tests will not run.\n")
if err != nil {
fmt.Printf("ERROR: %s\n", err)
}
}
usernsCfg := "/proc/sys/kernel/unprivileged_userns_clone"
val, permerr := ioutil.ReadFile(usernsCfg)
// Travis build doesn't support /proc/config.gz but kernel has userns
if os.Getenv("TRAVIS_BUILD") == "1" {
enableUserNS = permerr == nil && string(val) == usernsOk
logUsernsDetection(permerr)
return
}
if permerr == nil {
enableUserNS = string(val) == usernsOk
logUsernsDetection(permerr)
return
}
// old kernels dont have sysctl configurations
// than just checking the /proc/config suffices
usernsCmd := exec.Command("zgrep", kernelcfg, "/proc/config.gz")
content, err := usernsCmd.CombinedOutput()
if err != nil {
enableUserNS = false
logUsernsDetection(fmt.Errorf("Failed to get kernel config: %s", err))
return
}
cfgVal := strings.Trim(string(content), "\n\t ")
enableUserNS = cfgVal == kernelcfg+"=y"
logUsernsDetection(fmt.Errorf("%s not enabled in kernel config", kernelcfg))
}
func TestExecuteRforkUserNS(t *testing.T) {
if !enableUserNS {
t.Skip("User namespace not enabled")
return
}
f, teardown := setup(t)
defer teardown()
err := f.shell.Exec("rfork test", `
rfork u {
id -u
}
`)
if err != nil {
t.Error(err)
return
}
if string(f.shellOut.Bytes()) != "0\n" {
t.Errorf("User namespace not supported in your kernel: %s", string(f.shellOut.Bytes()))
return
}
}
func TestExecuteRforkEnvVars(t *testing.T) {
if !enableUserNS {
t.Skip("User namespace not enabled")
return
}
f, teardown := setup(t)
defer teardown()
sh := f.shell
err := sh.Exec("test env", `var abra = "cadabra"
setenv abra
rfork up {
echo $abra
}`)
if err != nil {
t.Error(err)
return
}
}
func TestExecuteRforkUserNSNested(t *testing.T) {
if !enableUserNS {
t.Skip("User namespace not enabled")
return
}
var out bytes.Buffer
f, teardown := setup(t)
defer teardown()
sh := f.shell
sh.SetStdout(&out)
err := sh.Exec("rfork userns nested", `
rfork u {
id -u
rfork u {
id -u
}
}
`)
if err != nil {
t.Error(err)
return
}
if string(out.Bytes()) != "0\n0\n" {
t.Errorf("User namespace not supported in your kernel")
return
}
}
|
NeowayLabs/nash
|
internal/sh/shell_linux_test.go
|
GO
|
apache-2.0
| 2,766
|
package com.example.administrator.c3_28_edittext;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showEditText();
showAutoCompleteTextView();
}
public void showAutoCompleteTextView(){
AutoCompleteTextView autoCompleteTextView =(AutoCompleteTextView)findViewById(R.id.autoCompleteTextView);
//1.data Source
String[] names={"vero","vnix","Duff","Alicc","ball","gogong","uzi","weixiao","CJJ","err","GodV"};
//2.adapter
ArrayAdapter<String> adapter=new ArrayAdapter<>(this,android.R.layout.simple_dropdown_item_1line,names);
//3.bind
autoCompleteTextView.setAdapter(adapter);
}
public void showEditText(){
EditText editText=(EditText)findViewById(R.id.editText);
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {//press Enter key
Toast.makeText(MainActivity.this,"actID:"+actionId,Toast.LENGTH_SHORT).show();
return false;
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
wapalxj/Android_C2_UI
|
C2_UI/c3_28_edittext/src/main/java/com/example/administrator/c3_28_edittext/MainActivity.java
|
Java
|
apache-2.0
| 2,421
|
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.cxf;
public class CXFWsdlOnlyMessageModeNoSpringTest extends CXFWsdlOnlyPayloadModeNoSpringTest {
@Override
protected String getDataFormat() {
return "MESSAGE";
}
}
|
kingargyle/turmeric-bot
|
components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CXFWsdlOnlyMessageModeNoSpringTest.java
|
Java
|
apache-2.0
| 1,028
|
/*
* CommentAccess.java 2011.01.01
*
* Copyright (c) 2010, MEI By Seok Kyun. Choi. (최석균)
* http://syaku.tistory.com
*
* GNU Lesser General Public License
* http://www.gnu.org/licenses/lgpl.html
*/
package com.syaku.modules.comment;
import java.util.*;
import org.apache.log4j.Logger;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.syaku.core.common.*;
public class CommentAccess {
private Logger log = Logger.getLogger( this.getClass() );
public static final SqlMapClient sqlMap = MyBatis.getInstance();
public List sqlCommentList(Map map) throws Exception { return sqlMap.queryForList("modules.comment.select-comment-list",map); }
public List sqlCommentMapList(Map map) throws Exception { return sqlMap.queryForList("modules.comment.select-map-comment",map); }
public Object sqlCommentObject(Map map) throws Exception { return sqlMap.queryForObject("modules.comment.select-comment-one",map); }
public Long sqlCommentCount(Map map) throws Exception { return (Long) sqlMap.queryForObject("modules.comment.select-comment-count",map); }
public String sqlCommentInsert(Object object) throws Exception { return (String) sqlMap.insert("modules.comment.insert-comment",object); }
public void sqlCommentUpdate(Object object) throws Exception { sqlMap.update("modules.comment.update-comment",object); }
public void sqlCommentDelete(Map map) throws Exception { sqlMap.delete("modules.comment.delete-comment",map); }
public void sqlCommentIsDelete(Map map) throws Exception { sqlMap.update("modules.comment.update-comment-del",map); }
public void sqlCommentReplyGroupDelete(Map map) throws Exception { sqlMap.delete("modules.comment.delete-comment-replygroup",map); }
public void sqlCommentModuleDelete(Map map) throws Exception { sqlMap.delete("modules.comment.delete-comment-module",map); }
public void sqlCommentTargetDelete(Map map) throws Exception { sqlMap.delete("modules.comment.delete-comment-target",map); }
public void sqlCommentReplySeqUpdate(Object object) throws Exception { sqlMap.update("modules.comment.update-comment-reply-seq",object); }
public void sqlCommentReplyDelete(Map map) throws Exception { sqlMap.delete("modules.comment.delete-comment-reply",map); }
public Long sqlCommentCounterCount(Map map) throws Exception { return (Long) sqlMap.queryForObject("modules.comment.select-comment-counter-count",map); }
public Long sqlCommentCounterCountObject(Map map) throws Exception { return (Long) sqlMap.queryForObject("modules.comment.select-comment-counter-count-one",map); }
public void sqlCommentCounterInsert(Object object) throws Exception { sqlMap.insert("modules.comment.insert-comment-counter",object); }
public void sqlCommentCounterUpdate(Object object) throws Exception { sqlMap.update("modules.comment.update-comment-counter",object); }
public void sqlCommentCounterDelete(Map map) throws Exception { sqlMap.delete("modules.comment.delete-comment-counter",map); }
public void sqlCommentCounterModuleDelete(Map map) throws Exception { sqlMap.delete("modules.comment.delete-comment-counter-module",map); }
public List sqlCommentSnsList(Map map) throws Exception { return sqlMap.queryForList("modules.comment.select-commentsns-list",map); }
public void sqlCommentSnsInsert(Object object) throws Exception { sqlMap.insert("modules.comment.insert-commentsns",object); }
public void sqlCommentSnsDelete(Map map) throws Exception { sqlMap.delete("modules.comment.delete-commentsns",map); }
public List sqlCommentAdminList(Map map) throws Exception { return sqlMap.queryForList("modules.comment.select-comment-admin-list",map); }
public Long sqlCommentAdminCount(Map map) throws Exception { return (Long) sqlMap.queryForObject("modules.comment.select-comment-admin-count",map); }
public void sqlCommentCreate(Map map) throws Exception { sqlMap.insert("modules.comment.create-comment",map); }
public void sqlCommentCreateCounter(Map map) throws Exception { sqlMap.insert("modules.comment.create-comment-counter",map); }
public void sqlCommentCreateSns(Map map) throws Exception { sqlMap.insert("modules.comment.create-comment-sns",map); }
}
|
syakuis/java-mei
|
WEB-INF/src/com/syaku/modules/comment/CommentAccess.java
|
Java
|
apache-2.0
| 4,153
|
package dk.teachus.frontend.components.list;
import java.io.Serializable;
import java.util.Comparator;
/**
* Case insensitive string comparator
*/
public class StringComparator implements Comparator<String>, Serializable {
private static final long serialVersionUID = 1L;
public int compare(String o1, String o2) {
int compare = 0;
if (o1 != null && o2 != null) {
compare = o1.toLowerCase().compareTo(o2.toLowerCase());
} else if (o1 != null) {
compare = -1;
} else if (o2 != null) {
compare = 1;
}
return compare;
}
}
|
teachus/teachus
|
teachus-frontend/src/main/java/dk/teachus/frontend/components/list/StringComparator.java
|
Java
|
apache-2.0
| 554
|
#!/bin/bash
# Copyright 2014 The Kubernetes Authors All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
set -o errexit
set -o nounset
set -o pipefail
# Caller should set in the ev:
# MASTER_IP - this may be an ip or things like "_use_gce_external_ip_"
# DNS_DOMAIN - which will be passed to minions in --cluster_domain
# SERVICE_CLUSTER_IP_RANGE - where all service IPs are allocated
# MASTER_NAME - I'm not sure what it is...
# Also the following will be respected
# CERT_DIR - where to place the finished certs
# CERT_GROUP - who the group owner of the cert files should be
service_range="${SERVICE_CLUSTER_IP_RANGE:="10.0.0.0/16"}"
dns_domain="${DNS_DOMAIN:="cluster.local"}"
cert_dir="${CERT_DIR:-"/tmp/certs"}"
cert_group="${CERT_GROUP:="kube"}"
masters="${MASTERS}"
# The following certificate pairs are created:
#
# - ca (the cluster's certificate authority)
# - server
# - kubelet
# - kubecfg (for kubectl)
tmpdir=$(mktemp -d -t kubernetes_cacert.XXXXXX)
trap 'rm -rf "${tmpdir}"' EXIT
cd "${tmpdir}"
# Calculate the first ip address in the service range
octects=($(echo "${service_range}" | sed -e 's|/.*||' -e 's/\./ /g'))
((octects[3]+=1))
service_ip=$(echo "${octects[*]}" | sed 's/ /./g')
# Determine appropriete subject alt names
sans="IP:${service_ip},IP:127.0.0.1,DNS:localhost,DNS:kubernetes,DNS:kubernetes.default,DNS:kubernetes.default.svc,DNS:kubernetes.default.svc.${dns_domain}"
hosts=$(for host in ${masters}; do echo DNS:${host}; done|tr [[:space:]] ,)
sans="$sans,${hosts%?}"
curl -L -O https://github.com/OpenVPN/easy-rsa/releases/download/3.0.0/EasyRSA-3.0.0.tgz > /dev/null 2>&1
tar xzf EasyRSA-3.0.0.tgz > /dev/null
cd EasyRSA-3.0.0
(./easyrsa init-pki > /dev/null 2>&1
./easyrsa --batch "--req-cn=kubernetes@$(date +%s)" build-ca nopass > /dev/null 2>&1
./easyrsa --subject-alt-name="${sans}" build-server-full server nopass > /dev/null 2>&1
./easyrsa build-client-full kubelet nopass > /dev/null 2>&1
./easyrsa build-client-full kubecfg nopass > /dev/null 2>&1) || {
# If there was an error in the subshell, just die.
# TODO(roberthbailey): add better error handling here
echo "=== Failed to generate certificates: Aborting ==="
exit 2
}
mkdir -p "$cert_dir"
cp -p pki/ca.crt "${cert_dir}/ca.crt"
cp -p pki/issued/server.crt "${cert_dir}/server.crt"
cp -p pki/private/server.key "${cert_dir}/server.key"
cp -p pki/issued/kubecfg.crt "${cert_dir}/kubecfg.crt"
cp -p pki/private/kubecfg.key "${cert_dir}/kubecfg.key"
cp -p pki/issued/kubelet.crt "${cert_dir}/kubelet.crt"
cp -p pki/private/kubelet.key "${cert_dir}/kubelet.key"
CERTS=("ca.crt" "server.key" "server.crt" "kubelet.key" "kubelet.crt" "kubecfg.key" "kubecfg.crt")
for cert in "${CERTS[@]}"; do
# chgrp "${cert_group}" "${cert_dir}/${cert}"
chmod 666 "${cert_dir}/${cert}"
done
|
phnmnl/mantl
|
roles/kubernetes/files/make-ca-cert.sh
|
Shell
|
apache-2.0
| 3,315
|
using System;
using System.IO;
using System.Text;
using Serilog.Events;
using Serilog.Formatting;
namespace Serilog.Sinks.RollingFileAlternate.Sinks.HourlyRolling
{
internal class HourlyFileSink : IDisposable
{
private static readonly string ThisObjectName = typeof(HourlyFileSink).Name;
private readonly ITextFormatter formatter;
private readonly HourlyLogFileDescription hourlyLogFileDescription;
private readonly StreamWriter output;
private readonly object syncRoot = new object();
private bool disposed;
private bool exceptionAlreadyThrown;
internal HourlyFileSink(
ITextFormatter formatter,
string logRootDirectory,
HourlyLogFileDescription hourlyLogFileDescription,
Encoding encoding = null)
{
this.formatter = formatter;
this.hourlyLogFileDescription = hourlyLogFileDescription;
string logDir = Path.Combine(logRootDirectory, DateTime.UtcNow.ToString("yyyy-MM-dd"));
this.output = this.OpenFileForWriting(logDir, hourlyLogFileDescription, encoding ?? Encoding.UTF8);
}
internal HourlyLogFileDescription LogFileDescription
{
get
{
return this.hourlyLogFileDescription;
}
}
public void Dispose()
{
if (!this.disposed)
{
this.output.Flush();
this.output.Dispose();
this.disposed = true;
}
}
internal void Emit(LogEvent logEvent)
{
if (logEvent == null) throw new ArgumentNullException("logEvent");
lock (this.syncRoot)
{
if (this.disposed)
{
throw new ObjectDisposedException(ThisObjectName, "Cannot write to disposed file");
}
if (this.output == null)
{
return;
}
this.formatter.Format(logEvent, this.output);
this.output.Flush();
}
}
private StreamWriter OpenFileForWriting(
string folderPath,
HourlyLogFileDescription logFileDescription,
Encoding encoding)
{
EnsureDirectoryCreated(folderPath);
try
{
var fullPath = Path.Combine(folderPath, logFileDescription.FileName);
var stream = File.Open(fullPath, FileMode.Append, FileAccess.Write, FileShare.Read);
return new StreamWriter(stream, encoding ?? Encoding.UTF8);
}
catch (IOException ex)
{
// Unfortuantely the exception doesn't have a code to check so need to check the message instead
if (!ex.Message.StartsWith("The process cannot access the file"))
{
throw;
}
}
catch (UnauthorizedAccessException)
{
if (exceptionAlreadyThrown)
{
throw;
}
exceptionAlreadyThrown = true;
}
return OpenFileForWriting(folderPath, logFileDescription.Next(), encoding);
}
private static void EnsureDirectoryCreated(string path)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
}
}
|
BedeGaming/sinks-rollingfile
|
src/Serilog.Sinks.RollingFileAlternate/Sinks/HourlyRolling/HourlyFileSink.cs
|
C#
|
apache-2.0
| 3,562
|
package com.xoozi.apiguides.gl.programs;
import android.content.Context;
import static android.opengl.GLES30.glGetAttribLocation;
import static android.opengl.GLES30.glGetUniformLocation;
import static android.opengl.GLES30.glUniformMatrix4fv;
import static android.opengl.GLES30.glUniform4f;
import com.xoozi.apiguides.R;
/**
* 射线着色程序
*/
public class RayShaderProgram extends ShaderProgram {
private final int _uMatrixLocation;
private final int _uColorLocation;
private final int _aPositionLocation;
public RayShaderProgram(Context context){
super(context, R.raw.ray_vertex_shader, R.raw.ray_fragment_shader);
_uMatrixLocation = glGetUniformLocation(_program, U_MATRIX);
_uColorLocation = glGetUniformLocation(_program, U_COLOR);
_aPositionLocation = glGetAttribLocation(_program, A_POSITION);
}
/**
* 设置必要的Uniform
*/
public void setUniforms(float []matrix, float a, float r, float g, float b){
glUniformMatrix4fv(_uMatrixLocation, 1, false, matrix, 0);
glUniform4f(_uColorLocation, r, g, b, a);
}
public int getPositionAttributeLocation(){
return _aPositionLocation;
}
}
|
Xoozi/ApiGuides
|
src/com/xoozi/apiguides/gl/programs/RayShaderProgram.java
|
Java
|
apache-2.0
| 1,247
|
<a href='https://github.com/angular/angular.js/edit/v1.4.x/src/ng/http.js?message=docs($httpParamSerializer)%3A%20describe%20your%20change...#L27' class='improve-docs btn btn-primary'><i class="glyphicon glyphicon-edit"> </i>Improve this Doc</a>
<a href='https://github.com/angular/angular.js/tree/v1.4.8/src/ng/http.js#L27' class='view-source pull-right btn btn-primary'>
<i class="glyphicon glyphicon-zoom-in"> </i>View Source
</a>
<header class="api-profile-header">
<h1 class="api-profile-header-heading">$httpParamSerializer</h1>
<ol class="api-profile-header-structure naked-list step-list">
<li>
- service in module <a href="api/ng">ng</a>
</li>
</ol>
</header>
<div class="api-profile-description">
<p>Default <a href="api/ng/service/$http"><code>$http</code></a> params serializer that converts objects to strings
according to the following rules:</p>
<ul>
<li><code>{'foo': 'bar'}</code> results in <code>foo=bar</code></li>
<li><code>{'foo': Date.now()}</code> results in <code>foo=2015-04-01T09%3A50%3A49.262Z</code> (<code>toISOString()</code> and encoded representation of a Date object)</li>
<li><code>{'foo': ['bar', 'baz']}</code> results in <code>foo=bar&foo=baz</code> (repeated key for each array element)</li>
<li><code>{'foo': {'bar':'baz'}}</code> results in <code>foo=%7B%22bar%22%3A%22baz%22%7D"</code> (stringified and encoded representation of an object)</li>
</ul>
<p>Note that serializer will sort the request parameters alphabetically.</p>
</div>
<div>
</div>
|
LADOSSIFPB/nutrif
|
nutrif-web/lib/angular/docs/partials/api/ng/service/$httpParamSerializer.html
|
HTML
|
apache-2.0
| 1,714
|
#!/usr/bin/python
######################################################################
#
# File: kafka_to_mysql.py
#
# Copyright 2015 TiVo Inc. All Rights Reserved.
#
######################################################################
"""
Usage: kafka_to_mysql.py <kafka_topic> <kafka_broker> <mysql-ip> <mysql-port> <mysql-user> <mysql-password> <mysql_table>
"""
import json
import MySQLdb
from kafka import KafkaClient, KafkaConsumer
import sys
def usage():
print __doc__
sys.exit(1)
def main():
# R0915: "too many statements in function (>50)"
# pylint: disable=R0915
if len(sys.argv) != 8:
print "Wrong number of arguments"
usage()
(kafka_topic, kafka_broker, mysql_host, mysql_port, mysql_user, mysql_password, mysql_table) = sys.argv[1:8]
sql_db = MySQLdb.connect(
host = mysql_host,
port = int(mysql_port),
user = mysql_user,
passwd = mysql_password)
query = sql_db.cursor()
client = KafkaClient(kafka_broker)
consumer = KafkaConsumer(kafka_topic, metadata_broker_list = [kafka_broker],
auto_commit_enable = False,
auto_offset_reset='smallest')
last_offsets = {}
partition_ids = client.get_partition_ids_for_topic(kafka_topic)
for partition in partition_ids:
offsets = consumer.get_partition_offsets(kafka_topic, partition, -1, 1)
print offsets
# Don't really understand this format, so put in asserts
# (Pdb) consumer.get_partition_offsets("topicname", 0, -1, 1)
# (15471)
assert len(offsets) == 1
assert offsets[0] > 0
next_offset = offsets[0]
last_offset = next_offset - 1
last_offsets[partition] = last_offset
finished_partitions = set()
print last_offsets
count = 0
# mapping from primary key tuples, to row data
insert_batch = {}
insert_sql = None
for m in consumer:
if m.partition in finished_partitions:
continue
count += 1
payload = m.value
(first_line, rest) = payload.split("\r\n", 1)
(_notused, header_len, _body_len) = first_line.split(" ")
header_len = int(header_len)
body = rest[header_len:]
primary_key_str = m.key
# import pdb; pdb.set_trace()
primary_keys = json.loads(primary_key_str)
primary_tuples = sorted(primary_keys.items())
sorted_primary_key_names = [ k for (k,v) in primary_tuples ]
sorted_primary_key_values = [ int(v) for (k,v) in primary_tuples ]
if len(body) > 0:
# This is a write
data = json.loads(body)
# date fields have to be turned from a number back into a datetime object
date_fields = ['createDate', 'updateDate']
for d in date_fields:
if d not in data:
continue
val = data[d]
if val is None:
continue
if val == -62170156800000:
# this is hacky and a sign that i'm doing something wrong, I think.
val = "0000-00-00 00:00:00"
else:
val = val/1000
import datetime;
val = datetime.datetime.utcfromtimestamp(val)
data[d] = val
keys = [ k for (k, v) in sorted(data.items()) ]
values = [ v for (k, v) in sorted(data.items()) ]
keys_wo_primary = [ k for (k, v) in sorted(data.items()) ]
for p in sorted_primary_key_names:
keys_wo_primary.remove(p)
# e.g.
# insert into dbname.tablename (col1, col2) values (%s, %s) on duplicate key update col2 = values(col2)
# assuming that col1 is the primary key
insert_sql = """insert into %s """ % mysql_table
insert_sql += """ (%s) """ % (", ".join(keys))
insert_sql += " values (%s) " % (", ".join(["%s"] * len(values) ))
insert_sql += "on duplicate key update "
insert_sql += ", ".join(["%s = values(%s)" % (k, k) for k in keys_wo_primary ])
insert_batch[tuple(primary_tuples)] = tuple(values)
if len(insert_batch) > 5000:
query.executemany(insert_sql, insert_batch.values())
sql_db.commit()
insert_batch = {}
else:
# This is a delete
if len(insert_batch) > 0 and insert_sql is not None:
# flush all writes before processing any deletes
query.executemany(insert_sql, insert_batch.values())
sql_db.commit()
insert_batch = {}
# get the primary keys, and delete the row
where_clause = ' and '.join([ "%s = %%s" % k for k in sorted_primary_key_names ])
# e.g.
# delete from dbname.tablename where field1 = %s and field2 = %s
delete_sql = """delete from %s where %s""" % (mysql_table, where_clause)
values = tuple(sorted_primary_key_values)
query.execute(delete_sql, values)
sql_db.commit()
# how do I know when to stop?
print "Partition %d Offset %d of %d" % (m.partition, m.offset, last_offsets.get(m.partition))
if m.offset >= last_offsets.get(m.partition):
finished_partitions.add(m.partition)
if len(finished_partitions) == len(last_offsets):
# All partitions are done.
break
if len(insert_batch) > 0:
# flush any remaining writes
query.executemany(insert_sql, insert_batch.values())
sql_db.commit()
insert_batch = {}
print "Imported %d messages into mysql" % count
if __name__ == "__main__":
main()
|
TiVo/wombat
|
correctness/kafka_to_mysql.py
|
Python
|
apache-2.0
| 5,895
|
package com.yjl.spring.dao;
import com.yjl.spring.model.User;
/**
* Created by YangJunLin on 2015/4/18.
*/
public interface UserDao {
public User getUser(int userId);
}
|
yangjunlin-const/WhileTrueCoding
|
Spring/src/main/java/com/yjl/spring/dao/UserDao.java
|
Java
|
apache-2.0
| 177
|
package org.approvaltests.reporters.macosx;
import org.approvaltests.reporters.DiffPrograms.Mac;
import org.approvaltests.reporters.GenericDiffReporter;
public class KaleidoscopeDiffReporter extends GenericDiffReporter
{
public static final KaleidoscopeDiffReporter INSTANCE = new KaleidoscopeDiffReporter();
public KaleidoscopeDiffReporter()
{
super(Mac.KALEIDOSCOPE);
}
}
|
approvals/ApprovalTests.Java
|
approvaltests/src/main/java/org/approvaltests/reporters/macosx/KaleidoscopeDiffReporter.java
|
Java
|
apache-2.0
| 388
|
module Transparencia
class Candidato < Transparencia::Base
ENTRY_POINT = Settings.transparencia.services.candidatos
def self.find_all(q='estado=SP&partido=1')
key = ENTRY_POINT+'?'+q
candidatos = Rails.cache.fetch(key, expires_in: 30.days) { |url|
JSON.parse(get(url).body)
}
candidatos
end
def self.detail(id)
key = ENTRY_POINT+'/'+id
candidato = Rails.cache.fetch(key, expires_in: 30.days) { |url|
JSON.parse(get(url).body)
}
candidato
end
def self.graph(id)
key = ENTRY_POINT+'/'+id+'/estatisticas'
estatisticas = Rails.cache.fetch(key, expires_in: 30.days) { |url|
JSON.parse(get(url).body)
}
estatisticas
end
def self.candidatures(id)
key = ENTRY_POINT+'/'+id+'/candidaturas'
candidaturas = Rails.cache.fetch(key, expires_in: 30.days) { |url|
JSON.parse(get(url).body)
}
candidaturas
end
def self.riches(id)
key = ENTRY_POINT+'/'+id+'/bens'
bens = Rails.cache.fetch(key, expires_in: 30.days) { |url|
JSON.parse(get(url).body)
}
bens
end
def self.presidentes
key = ENTRY_POINT+'?estado=BR&cargo=1'
presidente = Rails.cache.fetch(key, expires_in: 30.days) { |url|
JSON.parse(get(url).body)
}
presidente
end
end
end
|
cristianounix/transparencia-brasil
|
lib/transparencia/candidato.rb
|
Ruby
|
apache-2.0
| 1,373
|
/*
* 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.hp.hpl.jena.reasoner.rulesys.test;
import java.util.*;
import com.hp.hpl.jena.graph.*;
import com.hp.hpl.jena.reasoner.*;
import com.hp.hpl.jena.reasoner.rulesys.*;
import com.hp.hpl.jena.reasoner.test.TestUtil;
import com.hp.hpl.jena.util.iterator.ExtendedIterator;
import com.hp.hpl.jena.vocabulary.*;
import java.io.*;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Early test cases for the LP version of the backward chaining system.
* <p>
* To be moved to a test directory once the code is working.
* </p>
* @author <a href="mailto:der@hplb.hpl.hp.com">Dave Reynolds</a>
* @version $Revision: 1.1 $ on $Date: 2009-06-29 08:55:42 $
*/
public class TestBasicLP extends TestCase {
// Useful constants
Node p = Node.createURI("p");
Node q = Node.createURI("q");
Node r = Node.createURI("r");
Node s = Node.createURI("s");
Node t = Node.createURI("t");
Node u = Node.createURI("u");
Node a = Node.createURI("a");
Node b = Node.createURI("b");
Node c = Node.createURI("c");
Node d = Node.createURI("d");
Node e = Node.createURI("e");
Node C1 = Node.createURI("C1");
Node C2 = Node.createURI("C2");
Node C3 = Node.createURI("C3");
Node C4 = Node.createURI("C4");
Node D1 = Node.createURI("D1");
Node D2 = Node.createURI("D2");
Node D3 = Node.createURI("D3");
Node sP = RDFS.Nodes.subPropertyOf;
Node sC = RDFS.Nodes.subClassOf;
Node ty = RDF.Nodes.type;
/**
* Boilerplate for junit
*/
public TestBasicLP( String name ) {
super( name );
}
/**
* Boilerplate for junit.
* This is its own test suite
*/
public static TestSuite suite() {
// return new TestSuite( TestBasicLP.class );
TestSuite suite = new TestSuite();
suite.addTest(new TestBasicLP( "testCME" ));
return suite;
}
/**
* Return an inference graph working over the given rule set and raw data.
* Can be overridden by subclasses of this test class.
* @param rules the rule set to use
* @param data the graph of triples to process
*/
public InfGraph makeInfGraph(List<Rule> rules, Graph data) {
FBRuleReasoner reasoner = new FBRuleReasoner(rules);
FBRuleInfGraph infgraph = (FBRuleInfGraph) reasoner.bind(data);
// infgraph.setTraceOn(true);
return infgraph;
}
/**
* Return an inference graph working over the given rule set and raw data.
* Can be overridden by subclasses of this test class.
* @param rules the rule set to use
* @param data the graph of triples to process
* @param tabled an array of predicates that should be tabled
*/
public InfGraph makeInfGraph(List<Rule> rules, Graph data, Node[] tabled) {
FBRuleReasoner reasoner = new FBRuleReasoner(rules);
FBRuleInfGraph infgraph = (FBRuleInfGraph) reasoner.bind(data);
for (int i = 0; i < tabled.length; i++) {
infgraph.setTabled(tabled[i]);
}
return infgraph;
}
/**
* Test basic rule operations - lookup, no matching rules
*/
public void testBaseRules1() {
doBasicTest("[r1: (?x r c) <- (?x p b)]",
new Triple(Node.ANY, p, b),
new Object[] {
new Triple(a, p, b)
} );
}
/**
* Test basic rule operations - simple chain rule
*/
public void testBaseRules2() {
doBasicTest("[r1: (?x r c) <- (?x p b)]",
new Triple(Node.ANY, r, c),
new Object[] {
new Triple(a, r, c)
} );
}
/**
* Test basic rule operations - chain rule with head unification
*/
public void testBaseRules3() {
doBasicTest("[r1: (?x r ?x) <- (?x p b)]",
new Triple(Node.ANY, r, a),
new Object[] {
new Triple(a, r, a)
} );
}
/**
* Test basic rule operations - rule with head unification, non-temp var
*/
public void testBaseRules4() {
doBasicTest("[r1: (?x r ?x) <- (?y p b), (?x p b)]",
new Triple(Node.ANY, r, a),
new Object[] {
new Triple(a, r, a)
} );
}
/**
* Test basic rule operations - simple cascade
*/
public void testBaseRules5() {
doBasicTest("[r1: (?x q ?y) <- (?x r ?y)(?y s ?x)]" +
"[r2: (?x r ?y) <- (?x p ?y)]" +
"[r3: (?x s ?y) <- (?y p ?x)]",
new Triple(Node.ANY, q, Node.ANY),
new Object[] {
new Triple(a, q, b)
} );
}
/**
* Test basic rule operations - chain rule which will fail at head time
*/
public void testBaseRules6() {
doBasicTest("[r1: (?x r ?x) <- (?x p b)]",
new Triple(a, r, b),
new Object[] {
} );
}
/**
* Test basic rule operations - chain rule which will fail in search
*/
public void testBaseRules7() {
doBasicTest("[r1: (?x r ?y) <- (?x p c)]",
new Triple(a, r, b),
new Object[] {
} );
}
/**
* Test basic rule operations - simple chain
*/
public void testBaseRules8() {
doBasicTest("[r1: (?x q ?y) <- (?x r ?y)]" +
"[r2: (?x r ?y) <- (?x p ?y)]",
new Triple(Node.ANY, q, Node.ANY),
new Object[] {
new Triple(a, q, b)
} );
}
/**
* Test basic rule operations - simple chain
*/
public void testBaseRules9() {
doBasicTest("[r1: (?x q ?y) <- (?x r ?y)]" +
"[r2: (?x r ?y) <- (?y p ?x)]",
new Triple(Node.ANY, q, Node.ANY),
new Object[] {
new Triple(b, q, a)
} );
}
/**
* Test backtracking - simple triple query.
*/
public void testBacktrack1() {
doTest("[r1: (?x r ?y) <- (?x p ?y)]",
new Triple[] {
new Triple(a, p, b),
new Triple(a, p, c),
new Triple(a, p, d)
},
new Triple(a, p, Node.ANY),
new Object[] {
new Triple(a, p, b),
new Triple(a, p, c),
new Triple(a, p, d)
} );
}
/**
* Test backtracking - chain to simple triple query.
*/
public void testBacktrack2() {
doTest("[r1: (?x r ?y) <- (?x p ?y)]",
new Triple[] {
new Triple(a, p, b),
new Triple(a, p, c),
new Triple(a, p, d)
},
new Triple(a, r, Node.ANY),
new Object[] {
new Triple(a, r, b),
new Triple(a, r, c),
new Triple(a, r, d)
} );
}
/**
* Test backtracking - simple choice point
*/
public void testBacktrack3() {
doTest("[r1: (?x r C1) <- (?x p b)]" +
"[r2: (?x r C2) <- (?x p b)]" +
"[r3: (?x r C3) <- (?x p b)]",
new Triple[] {
new Triple(a, p, b)
},
new Triple(a, r, Node.ANY),
new Object[] {
new Triple(a, r, C1),
new Triple(a, r, C2),
new Triple(a, r, C3)
} );
}
/**
* Test backtracking - nested choice point
*/
public void testBacktrack4() {
doTest("[r1: (?x r C1) <- (?x p b)]" +
"[r2: (?x r C2) <- (?x p b)]" +
"[r3: (?x r C3) <- (?x p b)]" +
"[r4: (?x s ?z) <- (?x p ?w), (?x r ?y) (?y p ?z)]",
new Triple[] {
new Triple(a, p, b),
new Triple(C1, p, D1),
new Triple(C2, p, D2),
new Triple(C3, p, D3)
},
new Triple(a, s, Node.ANY),
new Object[] {
new Triple(a, s, D1),
new Triple(a, s, D2),
new Triple(a, s, D3)
} );
}
/**
* Test backtracking - nested choice point with multiple triple matches
*/
public void testBacktrack5() {
doTest("[r1: (?x r C3) <- (C1 p ?x)]" +
"[r2: (?x r C2) <- (C2 p ?x)]" +
"[r4: (?x s ?y) <- (?x r ?y)]",
new Triple[] {
new Triple(C1, p, D1),
new Triple(C1, p, a),
new Triple(C2, p, D2),
new Triple(C2, p, b)
},
new Triple(Node.ANY, s, Node.ANY),
new Object[] {
new Triple(D1, s, C3),
new Triple(a, s, C3),
new Triple(D2, s, C2),
new Triple(b, s, C2)
} );
}
/**
* Test backtracking - nested choice point with multiple triple matches, and
* checking temp v. permanent variable usage
*/
public void testBacktrack6() {
doTest("[r1: (?x r C1) <- (?x p a)]" +
"[r2: (?x r C2) <- (?x p b)]" +
"[r3: (?x q C1) <- (?x p b)]" +
"[r4: (?x q C2) <- (?x p a)]" +
"[r5: (?x s ?y) <- (?x r ?y) (?x q ?y)]",
new Triple[] {
new Triple(D1, p, a),
new Triple(D2, p, a),
new Triple(D2, p, b),
new Triple(D3, p, b)
},
new Triple(Node.ANY, s, Node.ANY),
new Object[] {
new Triple(D2, s, C1),
new Triple(D2, s, C2),
} );
}
/**
* Test backtracking - nested choice point with simple triple matches
*/
public void testBacktrack7() {
doTest( "[r1: (?x r C1) <- (?x p b)]" +
"[r2: (?x r C2) <- (?x p b)]" +
"[r3: (?x r C3) <- (?x p b)]" +
"[r3: (?x r D1) <- (?x p b)]" +
"[r4: (?x q C2) <- (?x p b)]" +
"[r5: (?x q C3) <- (?x p b)]" +
"[r5: (?x q D1) <- (?x p b)]" +
"[r6: (?x t C1) <- (?x p b)]" +
"[r7: (?x t C2) <- (?x p b)]" +
"[r8: (?x t C3) <- (?x p b)]" +
"[r9: (?x s ?y) <- (?x r ?y) (?x q ?y) (?x t ?y)]",
new Triple[] {
new Triple(a, p, b),
},
new Triple(Node.ANY, s, Node.ANY),
new Object[] {
new Triple(a, s, C2),
new Triple(a, s, C3),
} );
}
/**
* Test backtracking - nested choice point with simple triple matches,
* permanent vars but used just once in body
*/
public void testBacktrack8() {
doTest( "[r1: (?x r C1) <- (?x p b)]" +
"[r2: (?x r C2) <- (?x p b)]" +
"[r3: (?x r C3) <- (?x p b)]" +
"[r3: (?x r D1) <- (?x p b)]" +
"[r4: (?x q C2) <- (?x p b)]" +
"[r5: (?x q C3) <- (?x p b)]" +
"[r5: (?x q D1) <- (?x p b)]" +
"[r6: (?x t C1) <- (?x p b)]" +
"[r7: (?x t C2) <- (?x p b)]" +
"[r8: (?x t C3) <- (?x p b)]" +
"[r9: (?x s ?y) <- (?w r C1) (?x q ?y) (?w t C1)]",
new Triple[] {
new Triple(a, p, b),
},
new Triple(Node.ANY, s, Node.ANY),
new Object[] {
new Triple(a, s, D1),
new Triple(a, s, C2),
new Triple(a, s, C3),
} );
}
/**
* Test backtracking - multiple triple matches
*/
public void testBacktrack9() {
doTest("[r1: (?x s ?y) <- (?x r ?y) (?x q ?y)]",
new Triple[] {
new Triple(a, r, D1),
new Triple(a, r, D2),
new Triple(a, r, D3),
new Triple(b, r, D2),
new Triple(a, q, D2),
new Triple(b, q, D2),
new Triple(b, q, D3),
},
new Triple(Node.ANY, s, Node.ANY),
new Object[] {
new Triple(a, s, D2),
new Triple(b, s, D2),
} );
}
/**
* Test backtracking - multiple triple matches
*/
public void testBacktrack10() {
doTest("[r1: (?x s ?y) <- (?x r ?y) (?x q ?z), equal(?y, ?z)(?x, p, ?y)]" +
"[(a p D1) <- ]" +
"[(a p D2) <- ]" +
"[(b p D1) <- ]",
new Triple[] {
new Triple(a, r, D1),
new Triple(a, r, D2),
new Triple(a, r, D3),
new Triple(b, r, D2),
new Triple(a, q, D2),
new Triple(b, q, D2),
new Triple(b, q, D3),
},
new Triple(Node.ANY, s, Node.ANY),
new Object[] {
new Triple(a, s, D2),
} );
}
/**
* Test clause order is right
*/
public void testClauseOrder() {
List<Rule> rules = Rule.parseRules(
"[r1: (?x r C1) <- (?x p b)]" +
"[r1: (?x r C2) <- (?x p b)]" +
"[r2: (?x r C3) <- (?x r C3) (?x p b)]");
Graph data = Factory.createGraphMem();
data.add(new Triple(a, p, b));
InfGraph infgraph = makeInfGraph(rules, data);
ExtendedIterator<Triple> i = infgraph.find(Node.ANY, r, Node.ANY);
assertTrue(i.hasNext());
assertEquals(i.next(), new Triple(a, r, C1));
i.close();
}
/**
* Test axioms work.
*/
public void testAxioms() {
doTest("[a1: -> (a r C1) ]" +
"[a2: -> (a r C2) ]" +
"[a3: (b r C1) <- ]" +
"[r1: (?x s ?y) <- (?x r ?y)]",
new Triple[] {
},
new Triple(Node.ANY, s, Node.ANY),
new Object[] {
new Triple(a, s, C1),
new Triple(a, s, C2),
new Triple(b, s, C1),
} );
}
/**
* Test nested invocation of rules with permanent vars
*/
public void testNestedPvars() {
doTest("[r1: (?x r ?y) <- (?x p ?z) (?z q ?y)]" +
"[r1: (?y t ?x) <- (?x p ?z) (?z q ?y)]" +
"[r3: (?x s ?y) <- (?x r ?y) (?y t ?x)]",
new Triple[] {
new Triple(a, p, C1),
new Triple(a, p, C2),
new Triple(a, p, C3),
new Triple(C2, q, b),
new Triple(C3, q, c),
new Triple(D1, q, D2),
},
new Triple(Node.ANY, s, Node.ANY),
new Object[] {
new Triple(a, s, b),
new Triple(a, s, c),
} );
}
/**
* Test simple invocation of a builtin
*/
public void testBuiltin1() {
doTest("[r1: (?x r ?y) <- (?x p ?v), sum(?v 2 ?y)]",
new Triple[] {
new Triple(a, p, Util.makeIntNode(3)),
new Triple(b, p, Util.makeIntNode(4))
},
new Triple(Node.ANY, r, Node.ANY),
new Object[] {
new Triple(a, r, Util.makeIntNode(5)),
new Triple(b, r, Util.makeIntNode(6)),
} );
}
/**
* Test simple invocation of a builtin
*/
public void testBuiltin2() {
doTest("[r1: (?x r C1) <- (?x p ?v), lessThan(?v 3)]",
new Triple[] {
new Triple(a, p, Util.makeIntNode(1)),
new Triple(b, p, Util.makeIntNode(2)),
new Triple(c, p, Util.makeIntNode(3))
},
new Triple(Node.ANY, r, Node.ANY),
new Object[] {
new Triple(a, r, C1),
new Triple(b, r, C1),
} );
}
/**
* Test wildcard predicate usage - simple triple search.
* Rules look odd because we have to hack around the recursive loops.
*/
public void testWildPredicate1() {
doTest("[r1: (b r ?y) <- (a ?y ?v)]",
new Triple[] {
new Triple(a, p, C1),
new Triple(a, q, C2),
new Triple(a, q, C3),
},
new Triple(b, r, Node.ANY),
new Object[] {
new Triple(b, r, p),
new Triple(b, r, q)
} );
}
/**
* Test wildcard predicate usage - combind triple search and multiclause matching.
* Rules look odd because we have to hack around the recursive loops.
*/
public void testWildPredicate2() {
doTest("[r1: (a r ?y) <- (b ?y ?v)]" +
"[r2: (?x q ?y) <- (?x p ?y)]" +
"[r3: (?x s C1) <- (?x p C1)]" +
"[r4: (?x t C2) <- (?x p C2)]",
new Triple[] {
new Triple(b, p, C1),
new Triple(b, q, C2),
new Triple(b, q, C3),
new Triple(a, p, C1),
new Triple(a, p, C2),
new Triple(c, p, C1),
},
new Triple(a, Node.ANY, Node.ANY),
new Object[] {
new Triple(a, r, p),
new Triple(a, r, q),
new Triple(a, q, C1),
new Triple(a, q, C2),
new Triple(a, s, C1),
new Triple(a, t, C2),
new Triple(a, p, C1),
new Triple(a, p, C2),
new Triple(a, r, s),
} );
}
/**
* Test wildcard predicate usage - combined triple search and multiclause matching.
* Rules look odd because we have to hack around the recursive loops.
*/
public void testWildPredicate3() {
String rules = "[r1: (a r ?y) <- (b ?y ?v)]" +
"[r2: (?x q ?y) <- (?x p ?y)]" +
"[r3: (?x s C1) <- (?x p C1)]" +
"[r4: (?x t ?y) <- (?x ?y C1)]";
Triple[] data =
new Triple[] {
new Triple(b, p, C1),
new Triple(b, q, C2),
new Triple(b, q, C3),
new Triple(a, p, C1),
new Triple(a, p, C2),
new Triple(c, p, C1),
};
doTest(rules, data,
new Triple(a, Node.ANY, C1),
new Object[] {
new Triple(a, q, C1),
new Triple(a, s, C1),
new Triple(a, p, C1),
} );
doTest(rules, data,
new Triple(a, t, Node.ANY),
new Object[] {
new Triple(a, t, q),
new Triple(a, t, s),
new Triple(a, t, p),
} );
doTest(rules, data,
new Triple(Node.ANY, t, q),
new Object[] {
new Triple(a, t, q),
new Triple(b, t, q),
new Triple(c, t, q)
} );
}
/**
* Test wildcard predicate usage - wildcard in head as well
*/
public void testWildPredicate4() {
doTest("[r1: (a ?p ?x) <- (b ?p ?x)]",
new Triple[] {
new Triple(b, p, C1),
new Triple(b, q, C2),
new Triple(b, q, C3),
new Triple(c, q, d),
},
new Triple(a, Node.ANY, Node.ANY),
new Object[] {
new Triple(a, p, C1),
new Triple(a, q, C2),
new Triple(a, q, C3),
} );
}
/**
* Test functor usage.
*/
public void testFunctors1() {
String ruleSrc = "[r1: (?x s ?y) <- (?x p foo(?z, ?y))] ";
Triple[] triples =
new Triple[] {
new Triple(a, p, Functor.makeFunctorNode("foo", new Node[] {C1, C2})),
new Triple(a, p, Functor.makeFunctorNode("bar", new Node[] {C1, D1})),
new Triple(b, p, Functor.makeFunctorNode("foo", new Node[] {C1, C2})),
new Triple(a, p, Functor.makeFunctorNode("foo", new Node[] {C1, C3})),
new Triple(a, p, D1),
};
doTest(ruleSrc, triples, new Triple(Node.ANY, s, Node.ANY),
new Object[] {
new Triple(a, s, C2),
new Triple(b, s, C2),
new Triple(a, s, C3)
} );
}
/**
* Test functor usage.
*/
public void testFunctors2() {
String ruleSrc = "[r1: (?x r foo(?y,?z)) <- (?x p ?y), (?x q ?z)]" +
"[r2: (?x s ?y) <- (?x r foo(?z, ?y))] ";
Triple[] triples =
new Triple[] {
new Triple(a, p, C1),
new Triple(a, p, C3),
new Triple(a, q, C2),
new Triple(b, p, D1),
new Triple(b, q, D2),
new Triple(b, q, D3),
};
doTest(ruleSrc, triples, new Triple(Node.ANY, s, Node.ANY),
new Object[] {
new Triple(a, s, C2),
new Triple(b, s, D2),
new Triple(b, s, D3)
} );
}
/**
* Test functor usage.
*/
public void testFunctors3() {
String ruleSrc = "[r1: (?x r foo(p,?y)) <- (?x p ?y)]" +
"[r2: (?x r foo(q,?y)) <- (?x q ?y)]" +
"[r3: (?x r ?y) <- (?x t ?y)] " +
"[r4: (?x s ?y) <- (?x r ?y), notFunctor(?y)] " +
"[r5: (?x s ?y) <- (?x r foo(?y, ?z))] ";
Triple[] triples =
new Triple[] {
new Triple(a, p, C1),
new Triple(b, q, D1),
new Triple(b, p, D2),
new Triple(c, t, d)
};
doTest(ruleSrc, triples, new Triple(Node.ANY, s, Node.ANY),
new Object[] {
new Triple(a, s, p),
new Triple(b, s, p),
new Triple(b, s, q),
new Triple(c, s, d)
} );
}
/**
* Test tabled predicates. Simple chain call case.
*/
public void testTabled1() {
doTest("[r1: (?a q ?b) <- (?a p ?b)]" +
"[r2: (?x r ?y) <- (?x q ?y)]",
new Node[] { q },
new Triple[] {
new Triple(a, p, b),
new Triple(b, p, c),
},
new Triple(Node.ANY, r, Node.ANY),
new Object[] {
new Triple(a, r, b),
new Triple(b, r, c)
} );
}
/**
* Test tabled predicates. Simple transitive closure case.
*/
public void testTabled2() {
doTest("[r1: (?a p ?c) <- (?a p ?b)(?b p ?c)]",
new Node[] { p },
new Triple[] {
new Triple(a, p, b),
new Triple(b, p, c),
new Triple(b, p, d),
},
new Triple(Node.ANY, p, Node.ANY),
new Object[] {
new Triple(a, p, b),
new Triple(b, p, c),
new Triple(a, p, c),
new Triple(b, p, d),
new Triple(a, p, d),
} );
}
/**
* Test tabled predicates. Simple transitive closure over normal predicates
*/
public void testTabled3() {
doTest("[r1: (?x p ?z) <- (?x p ?y), (?y p ?z)]" +
"[r2: (?x p ?z) <- (?x e ?z), (?z q ?z)]",
new Node[] { p },
new Triple[] {
new Triple(a, e, b),
new Triple(a, e, d),
new Triple(b, e, c),
new Triple(a, q, a),
new Triple(b, q, b),
new Triple(c, q, c),
},
new Triple(a, p, Node.ANY),
new Object[] {
new Triple(a, p, b),
// new Triple(b, p, c),
new Triple(a, p, c)
} );
}
/**
* Test tabled predicates. Co-routining example.
*/
public void testTabled4() {
doTest("[r1: (?x a ?y) <- (?x c ?y)]" +
"[r2: (?x a ?y) <- (?x b ?z), (?z c ?y)]" +
"[r3: (?x b ?y) <- (?x d ?y)]" +
"[r4: (?x b ?y) <- (?x a ?z) (?z c ?y)]",
new Node[] { a, b },
new Triple[] {
new Triple(p, c, q),
new Triple(q, c, r),
new Triple(p, d, q),
new Triple(q, d, r),
},
new Triple(p, a, Node.ANY),
new Object[] {
new Triple(p, a, q),
new Triple(p, a, r)
} );
}
/**
* Test tabled predicates. Simple transitive closure case.
*/
public void testTabled5() {
doTest("[r1: (?a p ?c) <- (?a p ?b)(?b p ?c)]" +
"[r2: (?a r ?b) <- (?a q ?b)]",
new Node[] { p },
new Triple[] {
new Triple(a, p, b),
new Triple(b, p, c),
new Triple(a, q, d),
new Triple(c, q, d),
},
new Triple(a, Node.ANY, Node.ANY),
new Object[] {
new Triple(a, p, b),
new Triple(a, p, c),
new Triple(a, q, d),
new Triple(a, r, d),
} );
}
/**
* Test tabled predicates. Simple transitive closure case, tabling set
* by rule base.
*/
public void testTabled6() {
doTest("[-> table(p)] [r1: (?a p ?c) <- (?a p ?b)(?b p ?c)]",
new Triple[] {
new Triple(a, p, b),
new Triple(b, p, c),
new Triple(b, p, d),
},
new Triple(Node.ANY, p, Node.ANY),
new Object[] {
new Triple(a, p, b),
new Triple(b, p, c),
new Triple(a, p, c),
new Triple(b, p, d),
new Triple(a, p, d),
} );
}
/**
* Test tabled calls with aliased local vars in the call.
*/
public void testTabled7() {
doTest("[r1: (?a q ?b) <- (?a p ?b)]" +
"[r2: (?a q ?a) <- (?a s ?a)]" +
"[r2: (?a r ?z) <- (?a q ?a)]",
new Node[] { },
new Triple[] {
new Triple(a, p, b),
new Triple(c, p, c),
new Triple(a, p, a),
new Triple(b, s, e),
new Triple(d, s, d),
},
new Triple(Node.ANY, r, C1),
new Object[] {
new Triple(a, r, C1),
new Triple(c, r, C1),
new Triple(d, r, C1),
} );
}
/**
* Test RDFS example.
*/
public void testRDFS1() {
doTest(
"[ (?a rdf:type C1) <- (?a rdf:type C2) ]" +
"[ (?a rdf:type C2) <- (?a rdf:type C3) ]" +
"[ (?a rdf:type C3) <- (?a rdf:type C4) ]",
new Node[] { ty },
new Triple[] {
new Triple(a, ty, C1),
new Triple(b, ty, C2),
new Triple(c, ty, C3),
new Triple(d, ty, C4),
},
new Triple(Node.ANY, ty, C1),
new Object[] {
new Triple(a, ty, C1),
new Triple(b, ty, C1),
new Triple(c, ty, C1),
new Triple(d, ty, C1),
} );
}
/**
* Test RDFS example - branched version
*/
public void testRDFS2() {
doTest(
"[ (?a rdf:type C1) <- (?a rdf:type C2) ]" +
"[ (?a rdf:type C1) <- (?a rdf:type C3) ]" +
"[ (?a rdf:type C1) <- (?a rdf:type C4) ]",
new Node[] { ty },
new Triple[] {
new Triple(a, ty, C1),
new Triple(b, ty, C2),
new Triple(c, ty, C3),
new Triple(d, ty, C4),
},
new Triple(Node.ANY, ty, C1),
new Object[] {
new Triple(a, ty, C1),
new Triple(b, ty, C1),
new Triple(c, ty, C1),
new Triple(d, ty, C1),
} );
}
/**
* A problem from the original backchainer tests - interaction
* of tabling and functor expansion.
*/
public void testProblem1() {
doTest(
"[r1: (a q f(?x,?y)) <- (a s ?x), (a t ?y)]" +
"[r2: (a p ?x) <- (a q ?x)]" +
"[r3: (a r ?y) <- (a p f(?x, ?y))]",
new Node[] { p },
new Triple[] {
new Triple(a, s, b),
new Triple(a, t, c)
},
new Triple(a, r, Node.ANY),
new Object[] {
new Triple(a, r, c)
} );
}
/**
* A problem from the original backchainer tests - tabled closure operation.
*/
public void testProblem2() {
String ruleSrc =
"[rdfs8: (?a rdfs:subClassOf ?c) <- (?a rdfs:subClassOf ?b), (?b rdfs:subClassOf ?c)]" +
"[rdfs7: (?a rdfs:subClassOf ?a) <- (?a rdf:type rdfs:Class)]";
doTest( ruleSrc,
new Node[] { ty, sC },
new Triple[] {
new Triple(C1, sC, C2),
new Triple(C2, sC, C3),
new Triple(C1, ty, RDFS.Class.asNode()),
new Triple(C2, ty, RDFS.Class.asNode()),
new Triple(C3, ty, RDFS.Class.asNode())
},
new Triple(Node.ANY, sC, Node.ANY),
new Object[] {
new Triple(C1, sC, C2),
new Triple(C1, sC, C3),
new Triple(C1, sC, C1),
new Triple(C2, sC, C3),
new Triple(C2, sC, C2),
new Triple(C3, sC, C3)
} );
}
/**
* A problem from the original backchainer tests - bound/unbound primitives
*/
public void testProblem3() {
String rules = "[r1: (?x r ?y ) <- bound(?x), (?x p ?y) ]" +
"[r2: (?x r ?y) <- unbound(?x), (?x q ?y)]";
doTest(rules,
new Triple[] {
new Triple(a, p, b),
new Triple(a, q, c)
},
new Triple(a, r, Node.ANY),
new Object[] {
new Triple(a, r, b)
} );
doTest(rules,
new Triple[] {
new Triple(a, p, b),
new Triple(a, q, c)
},
new Triple(Node.ANY, r, Node.ANY),
new Object[] {
new Triple(a, r, c)
} );
}
/**
* A problem from the original backchainer tests - head unification test
*/
public void testProblem4() {
String rules = "[r1: (c r ?x) <- (?x p ?x)]" +
"[r2: (?x p ?y) <- (a q ?x), (b q ?y)]";
doTest(rules,
new Node[] { r, p },
new Triple[] {
new Triple(a, q, a),
new Triple(a, q, b),
new Triple(a, q, c),
new Triple(b, q, b),
new Triple(b, q, d),
},
new Triple(c, r, Node.ANY),
new Object[] {
new Triple(c, r, b)
} );
}
/**
* A problem from the original backchainer tests - RDFS example which threw an NPE
*/
public void testProblem5() {
String ruleSrc =
"[rdfs8: (?a rdfs:subClassOf ?c) <- (?a rdfs:subClassOf ?b), (?b rdfs:subClassOf ?c)]" +
"[rdfs9: (?a rdf:type ?y) <- (?x rdfs:subClassOf ?y), (?a rdf:type ?x)]" +
"[(rdf:type rdfs:range rdfs:Class) <-]" +
"[rdfs3: (?y rdf:type ?c) <- (?x ?p ?y), (?p rdfs:range ?c)]" +
"[rdfs7: (?a rdfs:subClassOf ?a) <- (?a rdf:type rdfs:Class)]";
doTest( ruleSrc,
new Node[] { ty, sC },
new Triple[] {
new Triple(p, sP, q),
new Triple(q, sP, r),
new Triple(C1, sC, C2),
new Triple(C2, sC, C3),
new Triple(a, ty, C1)
},
new Triple(a, ty, Node.ANY),
new Object[] {
new Triple(a, ty, C1),
new Triple(a, ty, C2),
new Triple(a, ty, C3)
} );
}
/**
* A problem from the original backchainer tests - RDFS example which threw an NPE
*/
public void testProblem6() {
String ruleSrc =
"[rdfs9: (?a rdf:type ?y) <- (?x rdfs:subClassOf ?y), (?a rdf:type ?x)]" +
"[restriction2: (?C owl:equivalentClass all(?P, ?D)) <- (?C owl:onProperty ?P), (?C owl:allValuesFrom ?D)]" +
"[rs2: (?X rdf:type all(?P,?C)) <- (?D owl:equivalentClass all(?P,?C)), (?X rdf:type ?D)]" +
"[rp4: (?Y rdf:type ?C) <- (?X rdf:type all(?P, ?C)), (?X ?P ?Y)]";
doTest( ruleSrc,
new Node[] { ty, sC, OWL.equivalentClass.asNode() },
new Triple[] {
new Triple(a, ty, r),
new Triple(a, p, b),
new Triple(r, sC, C1),
new Triple(C1, OWL.onProperty.asNode(), p),
new Triple(C1, OWL.allValuesFrom.asNode(), c)
},
new Triple(b, ty, c),
new Object[] {
new Triple(b, ty, c)
} );
}
/**
* A problem from the original backchainer tests - incorrect additional deduction.
* Was due to interpeter setup failing to clone input variables.
*/
public void testProblem7() {
String ruleSrc =
"[rdfs8: (?a rdfs:subClassOf ?c) <- (?a rdfs:subClassOf ?b), (?b rdfs:subClassOf ?c)]" +
"[rdfs9: (?a rdf:type ?y) <- (?x rdfs:subClassOf ?y), (?a rdf:type ?x)]" +
// "[(rdf:type rdfs:range rdfs:Class) <-]" +
// "[rdfs3: (?y rdf:type ?c) <- (?x ?p ?y), (?p rdfs:range ?c)]" +
"[rdfs3: (?y rdf:type rdfs:Class) <- (?x rdf:type ?y)]" +
"[rdfs7: (?a rdfs:subClassOf ?a) <- (?a rdf:type rdfs:Class)]";
List<Rule> rules = Rule.parseRules(ruleSrc);
Node[] tabled = new Node[] { ty, sC };
Triple[] triples = new Triple[] {
new Triple(C1, sC, C2),
new Triple(C2, sC, C3),
new Triple(a, ty, C1)
};
Graph data = Factory.createGraphMem();
for (int i = 0; i < triples.length; i++) {
data.add(triples[i]);
}
InfGraph infgraph = makeInfGraph(rules, data, tabled);
ExtendedIterator<Triple> it = infgraph.find(a, ty, null);
Triple result = it.next();
assertEquals(result.getSubject(), a);
assertEquals(result.getPredicate(), ty);
it.close();
// Make sure if we start again we get the full listing.
TestUtil.assertIteratorValues(this,
infgraph.find(a, ty, null),
new Object[] {
new Triple(a, ty, C1),
new Triple(a, ty, C2),
new Triple(a, ty, C3)
} );
}
/**
* A problem from the original backchainer tests - RDFS example which failed.
* Was due to unsupported multi-head statement.
*/
public void testProblem8() {
String ruleSrc =
"[rdfs9: (?a rdf:type ?y) <- bound(?y) (?x rdfs:subClassOf ?y) (?a rdf:type ?x)]" +
"[restriction4: (?C owl:equivalentClass max(?P, ?X)) <- (?C rdf:type owl:Restriction), (?C owl:onProperty ?P), (?C owl:maxCardinality ?X)]" +
"[restrictionProc11: (?X rdf:type max(?P, 1)) <- (?P rdf:type owl:FunctionalProperty), (?X rdf:type owl:Thing)]" +
"[equivalentClass1: (?Q rdfs:subClassOf ?P) <- (?P owl:equivalentClass ?Q) ]" +
"[equivalentClass1: (?P rdfs:subClassOf ?Q) <- (?P owl:equivalentClass ?Q) ]" +
"[restrictionSubclass1: (?X rdf:type ?D) <- bound(?D) (?D owl:equivalentClass ?R), isFunctor(?R) (?X rdf:type ?R)]";
doTest( ruleSrc,
new Node[] { ty, sC, OWL.equivalentClass.asNode() },
new Triple[] {
new Triple(a, ty, OWL.Thing.asNode()),
new Triple(p, ty, OWL.FunctionalProperty.asNode()),
new Triple(c, OWL.equivalentClass.asNode(), C1),
new Triple(C1, ty, OWL.Restriction.asNode()),
new Triple(C1, OWL.onProperty.asNode(), p),
new Triple(C1, OWL.maxCardinality.asNode(), Util.makeIntNode(1)),
},
new Triple(a, ty, c),
new Object[] {
new Triple(a, ty, c)
} );
}
/**
* Test derivation machinery
*/
public void testRuleDerivations() {
String rules = "[testRule1: (C2, p, ?a) <- (C1 p ?a)]" +
"[testRule2: (C2, q, ?a) <- (C1 q ?a)]" +
"[testRule3: (a p ?a) <- (C2 p ?a), (C2 q ?a)]";
List<Rule> ruleList = Rule.parseRules(rules);
Graph data = Factory.createGraphMem();
data.add(new Triple(C1, p, C3));
data.add(new Triple(C1, q, C4));
data.add(new Triple(C1, q, C3));
InfGraph infgraph = makeInfGraph(ruleList, data, new Node[]{p, q});
infgraph.setDerivationLogging(true);
TestUtil.assertIteratorValues(this, infgraph.find(a, null, null),
new Triple[] {
new Triple(a, p, C3)
});
Iterator<Derivation> derivs = infgraph.getDerivation(new Triple(a, p, C3));
StringWriter outString = new StringWriter(250);
PrintWriter out = new PrintWriter(outString);
while (derivs.hasNext()) {
Derivation d = derivs.next();
d.printTrace(out, true);
}
out.flush();
String testString = TestUtil.normalizeWhiteSpace("Rule testRule3 concluded (a p C3) <-\n" +
" Rule testRule1 concluded (C2 p C3) <-\n" +
" Fact (C1 p C3)\r\n" +
" Rule testRule2 concluded (C2 q C3) <-\n" +
" Fact (C1 q C3)\r\n");
assertEquals(testString, TestUtil.normalizeWhiteSpace(outString.getBuffer().toString()));
}
/**
* A suspect problem, originally derived from the OWL rules - risk of unbound variables escaping.
* Not managed to isolate or reproduce the problem yet.
*/
public void testProblem9() {
String ruleSrc =
"[test: (?x owl:sameAs ?x) <- (?x rdf:type owl:Thing) ]" +
"[sameIndividualAs6: (?X rdf:type owl:Thing) <- (?X owl:sameAs ?Y) ]" +
"[ans: (?x p C1) <- (?y owl:sameAs ?x)]";
Node sI = OWL.sameAs.asNode();
doTest( ruleSrc,
new Node[] { ty, sI }, // Tabled predicates
new Triple[] { // init data
new Triple(a, ty, OWL.Thing.asNode()),
new Triple(b, sI, c),
},
new Triple(Node.ANY, p, Node.ANY), // query
new Object[] { // result
new Triple(a, p, C1),
new Triple(b, p, C1),
new Triple(c, p, C1),
} );
// new Triple(Node.ANY, ty, Node.ANY), // query
// new Object[] { // result
// new Triple(a, ty, OWL.Thing.asNode()),
// new Triple(b, ty, OWL.Thing.asNode())
// } );
}
/**
* Test 3-arg builtins such as arithmetic.
*/
public void testArithBuiltins() {
doBuiltinTest(
"[(a,r,0) <- (a,p,?x), (a,q,?y), lessThan(?x,?y)]" +
"[(a,r,1) <- (a,p,?x), (a,q,?y), ge(?x, ?y)]",
Util.makeIntNode(2),Util.makeIntNode(3), Util.makeIntNode(0)
);
doBuiltinTest(
"[(a,r,0) <- (a,p,?x), (a,q,?y), lessThan(?x,?y)]" +
"[(a,r,1) <- (a,p,?x), (a,q,?y), ge(?x, ?y)]",
Util.makeIntNode(3),Util.makeIntNode(3), Util.makeIntNode(1)
);
doBuiltinTest(
"[(a,r,0) <- (a,p,?x), (a,q,?y), le(?x,?y)]" +
"[(a,r,1) <- (a,p,?x), (a,q,?y), greaterThan(?x, ?y)]",
Util.makeIntNode(3),Util.makeIntNode(3), Util.makeIntNode(0)
);
doBuiltinTest(
"[(a,r,?z) <- (a,p,?x), (a,q,?y), min(?x,?y,?z)]",
Util.makeIntNode(2),Util.makeIntNode(3), Util.makeIntNode(2)
);
doBuiltinTest(
"[(a,r,?z) <- (a,p,?x), (a,q,?y), min(?x,?y,?z)]",
Util.makeIntNode(4),Util.makeIntNode(3), Util.makeIntNode(3)
);
doBuiltinTest(
"[(a,r,?z) <- (a,p,?x), (a,q,?y), max(?x,?y,?z)]",
Util.makeIntNode(2),Util.makeIntNode(3), Util.makeIntNode(3)
);
doBuiltinTest(
"[(a,r,?z) <- (a,p,?x), (a,q,?y), max(?x,?y,?z)]",
Util.makeIntNode(4),Util.makeIntNode(3), Util.makeIntNode(4)
);
}
/**
* Test the temporary list builtins
*/
public void testListBuiltins() {
String ruleSrc = "[(a r ?n) <- (a p ?l), listLength(?l, ?n)]" +
"[(a s ?e) <- (a p ?l), listEntry(?l, 1, ?e)]";
List<Rule> rules = Rule.parseRules(ruleSrc);
Graph data = Factory.createGraphMem();
data.add(new Triple(a, p, Util.makeList(new Node[]{C1,C2,C3},data)));
InfGraph infgraph = makeInfGraph(rules, data);
TestUtil.assertIteratorValues(this,
infgraph.find(new Triple(a, r, Node.ANY)),
new Triple[] {
new Triple(a, r, Util.makeIntNode(3))
});
TestUtil.assertIteratorValues(this,
infgraph.find(new Triple(a, s, Node.ANY)),
new Triple[] {
new Triple(a, s, C2)
});
rules = Rule.parseRules(
"[(a s b) <- (a p ?l), (a, q, ?j) listEqual(?l, ?j)]" +
"[(a s c) <- (a p ?l), (a, q, ?j) listNotEqual(?l, ?j)]" +
"[(a s d) <- (a p ?l), (a, r, ?j) listEqual(?l, ?j)]" +
"[(a s e) <- (a p ?l), (a, r, ?j) listNotEqual(?l, ?j)]"
);
data = Factory.createGraphMem();
data.add(new Triple(a, p,
Util.makeList( new Node[]{C1, Util.makeIntNode(3), C3}, data) ));
data.add(new Triple(a, q,
Util.makeList( new Node[]{C3, C1, Util.makeLongNode(3)}, data) ));
data.add(new Triple(a, r,
Util.makeList( new Node[]{C3, C1, Util.makeLongNode(2)}, data) ));
infgraph = makeInfGraph(rules, data);
TestUtil.assertIteratorValues(this,
infgraph.find(new Triple(a, s, Node.ANY)),
new Triple[] {
new Triple(a, s, b),
new Triple(a, s, e),
});
rules = Rule.parseRules(
"[(b r ?j) <- (a p ?l), (a, q, ?j) listContains(?l, ?j)]" +
"[(b s ?j) <- (a p ?l), (a, q, ?j) listNotContains(?l, ?j)]"
);
data = Factory.createGraphMem();
data.add(new Triple(a, p,
Util.makeList( new Node[]{C1, Util.makeIntNode(3), C3}, data) ));
data.add(new Triple(a, q, C1));
data.add(new Triple(a, q, Util.makeLongNode(3)));
data.add(new Triple(a, q, C2));
infgraph = makeInfGraph(rules, data);
TestUtil.assertIteratorValues(this,
infgraph.find(new Triple(b, Node.ANY, Node.ANY)),
new Triple[] {
new Triple(b, r, C1),
new Triple(b, r, Util.makeIntNode(3)),
new Triple(b, s, C2),
});
}
/**
* Test that we detect concurrent modification of LP graphs with
* non-closed iterators.
*/
public void testCME() {
String ruleSrc = "(?a p 1) <- (?a p 0). (?a p 2) <- (?a p 0).";
List<Rule> rules = Rule.parseRules(ruleSrc);
Graph data = Factory.createGraphMem();
data.add(new Triple(a, p, Util.makeIntNode(0)));
InfGraph infgraph = makeInfGraph(rules, data);
// Check the base case works
TestUtil.assertIteratorValues(this,
infgraph.find(new Triple(a, p, Node.ANY)),
new Triple[] {
new Triple(a, p, Util.makeIntNode(0)),
new Triple(a, p, Util.makeIntNode(1)),
new Triple(a, p, Util.makeIntNode(2)),
});
// Now force a CME
boolean ok = false;
ExtendedIterator<Triple> i = infgraph.find(new Triple(a, p, Node.ANY));
try {
i.next();
infgraph.add( new Triple(a, p, Util.makeIntNode(4)) );
i.next();
} catch (ConcurrentModificationException e) {
ok = true;
} finally {
i.close();
}
assertTrue("Expect CME on unclosed iterators", ok);
}
/**
* Generic test operation.
* @param ruleSrc the source of the rules
* @param triples a set of triples to insert in the graph before the query
* @param query the TripleMatch to search for
* @param results the array of expected results
*/
private void doTest(String ruleSrc, Triple[] triples, TripleMatch query, Object[] results) {
List<Rule> rules = Rule.parseRules(ruleSrc);
Graph data = Factory.createGraphMem();
for (int i = 0; i < triples.length; i++) {
data.add(triples[i]);
}
InfGraph infgraph = makeInfGraph(rules, data);
TestUtil.assertIteratorValues(this, infgraph.find(query), results);
}
/**
* Generic test operation.
* @param ruleSrc the source of the rules
* @param tabled the predicates that should be tabled
* @param triples a set of triples to insert in the graph before the query
* @param query the TripleMatch to search for
* @param results the array of expected results
*/
private void doTest(String ruleSrc, Node[] tabled, Triple[] triples, TripleMatch query, Object[] results) {
List<Rule> rules = Rule.parseRules(ruleSrc);
Graph data = Factory.createGraphMem();
for (int i = 0; i < triples.length; i++) {
data.add(triples[i]);
}
InfGraph infgraph = makeInfGraph(rules, data, tabled);
TestUtil.assertIteratorValues(this, infgraph.find(query), results);
}
/**
* Generic base test operation on a graph with the single triple (a, p, b)
* @param ruleSrc the source of the rules
* @param query the TripleMatch to search for
* @param results the array of expected results
*/
private void doBasicTest(String ruleSrc, TripleMatch query, Object[] results) {
doTest(ruleSrc, new Triple[]{new Triple(a,p,b)}, query, results);
}
/**
* Generic test operation.
* @param rule to test a simple builtin operation
* @param param1 value to bind to first parameter by (a,p,_)
* @param param2 value to bind to first parameter by (a,q,_)
* @param result the expected result to be found by (a,r,_)
*/
private void doBuiltinTest(String ruleSrc, Node param1, Node param2, Node result) {
doTest(ruleSrc,
new Triple[] {
new Triple(a, p, param1),
new Triple(a, q, param2)
},
new Triple(a, r, Node.ANY),
new Triple[] {
new Triple(a, r, result)
});
}
}
|
danc86/jena-core
|
src/test/java/com/hp/hpl/jena/reasoner/rulesys/test/TestBasicLP.java
|
Java
|
apache-2.0
| 50,252
|
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////
#include "Basics/Common.h"
#include "ApplicationFeatures/ConfigFeature.h"
#include "ApplicationFeatures/LanguageFeature.h"
#include "ApplicationFeatures/ShutdownFeature.h"
#include "ApplicationFeatures/TempFeature.h"
#include "ApplicationFeatures/V8PlatformFeature.h"
#include "ApplicationFeatures/VersionFeature.h"
#include "Basics/ArangoGlobalContext.h"
#include "Logger/LoggerFeature.h"
#include "ProgramOptions/ProgramOptions.h"
#include "Random/RandomFeature.h"
#include "Shell/ClientFeature.h"
#include "Shell/ConsoleFeature.h"
#include "Shell/ShellFeature.h"
#include "Shell/V8ShellFeature.h"
#include "Ssl/SslFeature.h"
using namespace arangodb;
using namespace arangodb::application_features;
int main(int argc, char* argv[]) {
ArangoGlobalContext context(argc, argv);
context.installHup();
std::string name = context.binaryName();
std::shared_ptr<options::ProgramOptions> options(new options::ProgramOptions(
argv[0], "Usage: " + name + " [<options>]", "For more information use:"));
ApplicationServer server(options);
int ret;
server.addFeature(new ClientFeature(&server));
server.addFeature(new ConfigFeature(&server, name));
server.addFeature(new ConsoleFeature(&server));
server.addFeature(new LanguageFeature(&server));
server.addFeature(new LoggerFeature(&server, false));
server.addFeature(new RandomFeature(&server));
server.addFeature(new ShellFeature(&server, &ret));
server.addFeature(new ShutdownFeature(&server, {"Shell"}));
server.addFeature(new SslFeature(&server));
server.addFeature(new TempFeature(&server, name));
server.addFeature(new V8PlatformFeature(&server));
server.addFeature(new V8ShellFeature(&server, name));
server.addFeature(new VersionFeature(&server));
try {
server.run(argc, argv);
} catch (std::exception const& ex) {
LOG(ERR) << "arangosh terminated because of an unhandled exception: "
<< ex.what();
ret = EXIT_FAILURE;
} catch (...) {
LOG(ERR) << "arangosh terminated because of an unhandled exception of "
"unknown type";
ret = EXIT_FAILURE;
}
return context.exit(ret);
}
|
m0ppers/arangodb
|
arangosh/Shell/arangosh.cpp
|
C++
|
apache-2.0
| 3,091
|
<!DOCTYPE html>
<!--
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.
--><html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no, width=device-width">
<meta name="generator" content="joDoc">
<title>Apache Cordova API Documentation</title>
<link rel="stylesheet" type="text/css" href="index.css">
<link rel="stylesheet" type="text/css" href="mobile.css" media="only screen and (max-device-width: 1024px)">
<link rel="stylesheet" type="text/css" href="prettify/prettify.css">
</head>
<body>
<div id="header">
<h1><a href="index.html">Apache <strong>Cordova</strong> Documentation</a></h1>
<small>
<select><optgroup label="English" value="en">
<option value="edge">edge</option>
<option value="2.9.0rc1">2.9.0rc1</option>
<option value="2.9.0">2.9.0</option>
<option value="2.8.0">2.8.0</option>
<option value="2.7.0rc1">2.7.0rc1</option>
<option value="2.7.0">2.7.0</option>
<option value="2.6.0rc1">2.6.0rc1</option>
<option value="2.6.0">2.6.0</option>
<option value="2.5.0rc1">2.5.0rc1</option>
<option value="2.5.0">2.5.0</option>
<option value="2.4.0rc1">2.4.0rc1</option>
<option value="2.4.0">2.4.0</option>
<option selected value="2.3.0rc2">2.3.0rc2</option>
<option value="2.3.0rc1">2.3.0rc1</option>
<option value="2.3.0">2.3.0</option>
<option value="2.2.0rc2">2.2.0rc2</option>
<option value="2.2.0rc1">2.2.0rc1</option>
<option value="2.2.0">2.2.0</option>
<option value="2.1.0rc2">2.1.0rc2</option>
<option value="2.1.0rc1">2.1.0rc1</option>
<option value="2.1.0">2.1.0</option>
<option value="2.0.0rc1">2.0.0rc1</option>
<option value="2.0.0">2.0.0</option>
<option value="1.9.0rc1">1.9.0rc1</option>
<option value="1.9.0">1.9.0</option>
<option value="1.8.1">1.8.1</option>
<option value="1.8.0rc1">1.8.0rc1</option>
<option value="1.8.0">1.8.0</option>
<option value="1.7.0rc1">1.7.0rc1</option>
<option value="1.7.0">1.7.0</option>
<option value="1.6.1">1.6.1</option>
<option value="1.6.0rc1">1.6.0rc1</option>
<option value="1.6.0">1.6.0</option>
<option value="1.5.0rc1">1.5.0rc1</option>
<option value="1.5.0">1.5.0</option>
</optgroup>
<optgroup label="Japanese" value="jp">
<option value="2.2.0">2.2.0</option>
<option value="2.1.0">2.1.0</option>
<option value="2.0.0">2.0.0</option>
<option value="1.9.0">1.9.0</option>
<option value="1.8.1">1.8.1</option>
<option value="1.7.0">1.7.0</option>
</optgroup>
<optgroup label="Korean" value="kr"><option value="2.0.0">2.0.0</option></optgroup></select></small>
</div>
<div id="subheader">
<h1>Upgrading Cordova webOS</h1>
<small><select><option value="Upgrading%2520Cordova%2520webOS">Upgrading Cordova webOS</option>
<option value="Upgrading%20Cordova%20webOS_upgrade_to_2_1_0_from_2_0_0"> - Upgrade to 2.1.0 from 2.0.0</option></select></small>
</div>
<div id="sidebar">
<div class="vertical_divider"></div>
<h1>API Reference</h1>
<ul>
<li><a href="cordova_accelerometer_accelerometer.md.html#Accelerometer">Accelerometer</a></li>
<li><a href="cordova_camera_camera.md.html#Camera">Camera</a></li>
<li><a href="cordova_media_capture_capture.md.html#Capture">Capture</a></li>
<li><a href="cordova_compass_compass.md.html#Compass">Compass</a></li>
<li><a href="cordova_connection_connection.md.html#Connection">Connection</a></li>
<li><a href="cordova_contacts_contacts.md.html#Contacts">Contacts</a></li>
<li><a href="cordova_device_device.md.html#Device">Device</a></li>
<li><a href="cordova_events_events.md.html#Events">Events</a></li>
<li><a href="cordova_file_file.md.html#File">File</a></li>
<li><a href="cordova_geolocation_geolocation.md.html#Geolocation">Geolocation</a></li>
<li><a href="cordova_globalization_globalization.md.html#Globalization">Globalization</a></li>
<li><a href="cordova_inappbrowser_inappbrowser.md.html#InAppBrowser">InAppBrowser</a></li>
<li><a href="cordova_media_media.md.html#Media">Media</a></li>
<li><a href="cordova_notification_notification.md.html#Notification">Notification</a></li>
<li><a href="cordova_splashscreen_splashscreen.md.html#Splashscreen">Splashscreen</a></li>
<li><a href="cordova_storage_storage.md.html#Storage">Storage</a></li>
</ul>
<h1>Guides</h1>
<ul>
<li><a href="guide_getting-started_index.md.html#Getting%20Started%20Guides">Getting Started Guides</a></li>
<li><a href="guide_command-line_index.md.html#Command-Line%20Usage">Command-Line Usage</a></li>
<li><a href="guide_upgrading_index.md.html#Upgrading%20Guides">Upgrading Guides</a></li>
<li><a href="guide_project-settings_index.md.html#Project%20Settings">Project Settings</a></li>
<li><a href="guide_plugin-development_index.md.html#Plugin%20Development%20Guide">Plugin Development Guide</a></li>
<li><a href="guide_whitelist_index.md.html#Domain%20Whitelist%20Guide">Domain Whitelist Guide</a></li>
<li><a href="guide_cordova-webview_index.md.html#Embedding%20WebView">Embedding WebView</a></li>
<li><a href="_index.html">Keyword Index</a></li>
</ul>
</div>
<div id="scrollable">
<div id="content">
<h1><a name="Upgrading%20Cordova%20webOS">Upgrading Cordova webOS</a></h1>
<p>This document is for people who need to upgrade their Cordova versions from an older version to a current version of Cordova.</p>
<h2>
<a name="Upgrading%20Cordova%20webOS_upgrade_to_2_1_0_from_2_0_0">Upgrade to 2.1.0 from 2.0.0</a>
</h2>
<ol>
<li><p>remove cordova-2.0.0.js from your project</p></li>
<li>
<p>update the following line in your index.html:</p>
<p>change this:</p>
<script type="text/javascript" src="cordova-2.0.0.js"></script><p>to:</p>
<script type="text/javascript" src="cordova-2.1.0.js"></script>
</li>
<li><p>run the makefile to generate the newest version of the cordova-2.1.0.js file</p></li>
</ol>
</div>
</div>
<!-- Functionality and Syntax Highlighting -->
<script type="text/javascript" src="index.js"></script><script type="text/javascript" src="prettify/prettify.js"></script>
</body>
</html>
|
csantanapr/cordova-blog
|
public/docs/en/2.3.0rc2/guide_upgrading_webos_index.md.html
|
HTML
|
apache-2.0
| 6,883
|
<!-- Main content -->
<section class='content'>
<div class='row'>
<div class='col-xs-12'>
<div class='box'>
<div class='box-header'>
<h3 class='box-title'>Position_volunteer Read</h3>
<table class="table table-bordered">
<tr><td>Position</td><td><?php echo $position; ?></td></tr>
<tr><td></td><td><a href="<?php echo site_url('position_volunteer') ?>" class="btn btn-default">Back</a></td></tr>
</table>
</div><!-- /.box-body -->
</div><!-- /.box -->
</div><!-- /.col -->
</div><!-- /.row -->
</section><!-- /.content -->
|
indanazf/rweb
|
application/views/position_volunteer_read.php
|
PHP
|
apache-2.0
| 694
|
namespace EntLibExtensions.Infrastructure.WinService
{
using System.ComponentModel;
using System.Configuration.Install;
using System.Diagnostics;
using System.ServiceProcess;
/// <summary>
/// This class designed for service installation by using istallutil.exe
/// In case installation is provided by msi service extensions code below is ignored.
/// service information will be retrieved from wxs file.
/// </summary>
[RunInstaller(true)]
public abstract class ServiceInstallerBase : Installer
{
/// <summary>
/// Initializes a new instance of the <see cref="ServiceInstallerBase"/> class.
/// </summary>
/// <param name="options">
/// The options.
/// </param>
protected ServiceInstallerBase(WinServiceInstallationOptions options)
{
ServiceProcessInstaller serviceProcessInstaller = new ServiceProcessInstaller();
ServiceInstaller serviceInstaller = new ServiceInstaller();
// # Service Account Information
serviceProcessInstaller.Account = options.Account;
// # Service Information
serviceInstaller.DisplayName = options.DisplayName;
serviceInstaller.Description = options.Description;
serviceInstaller.StartType = ServiceStartMode.Automatic;
serviceInstaller.ServiceName = options.Options.ServiceName;
this.Installers.Add(serviceProcessInstaller);
this.Installers.Add(serviceInstaller);
EventLogInstaller defaultInstaller = null;
foreach (Installer installer in serviceInstaller.Installers)
{
var eventLogInstaller = installer as EventLogInstaller;
if (eventLogInstaller != null)
{
defaultInstaller = eventLogInstaller;
break;
}
}
if (defaultInstaller != null)
{
serviceInstaller.Installers.Remove(defaultInstaller);
}
}
}
}
|
IharYakimush/EntLibLight
|
Blocks/Infrastructure/src/Infrastructure/WinService/ServiceInstallerBase.cs
|
C#
|
apache-2.0
| 2,110
|
<?php
/**
* Get the ID generated in the last query
*
* @phpstub
*
* @param resource $link_identifier
*
* @return int The ID generated for an AUTO_INCREMENT column by the previous
* query on success, if the previous
* query does not generate an AUTO_INCREMENT value, or false if
* no MySQL connection was established.
*/
function mysql_insert_id($link_identifier = NULL)
{
}
|
schmittjoh/php-stubs
|
res/php/mysql/functions/mysql-insert-id.php
|
PHP
|
apache-2.0
| 422
|
/*
* Copyright (C) 2016 CaMnter yuanyu.camnter@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.camnter.savevolley.okhttp3.agera.core;
import android.support.annotation.NonNull;
import com.camnter.savevolley.okhttp3.volley.NetworkResponse;
import com.camnter.savevolley.okhttp3.volley.ParseError;
import com.camnter.savevolley.okhttp3.volley.Request;
import com.camnter.savevolley.okhttp3.volley.Response;
import com.camnter.savevolley.okhttp3.volley.VolleyError;
import com.camnter.savevolley.okhttp3.volley.toolbox.HttpHeaderParser;
import java.io.UnsupportedEncodingException;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Description:OkHttp3JsonReservoirRequest
* Created by:CaMnter
* Time:2016-06-23 16:00
*/
public class OkHttp3JsonReservoirRequest extends Okhttp3ReservoirRequest<JSONObject>
implements Response.Listener<JSONObject>, Response.ErrorListener {
private static final String PROTOCOL_CHARSET = "utf-8";
private final Response.Listener<JSONObject> mResponseListener;
public OkHttp3JsonReservoirRequest(@NonNull String url) {
this(Request.Method.GET, url);
}
public OkHttp3JsonReservoirRequest(int method,
@NonNull String url) {
super(method, url, null);
this.mResponseListener = this;
}
@Override protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
@Override protected void deliverResponse(JSONObject response) {
this.mResponseListener.onResponse(response);
}
@Override public void deliverError(VolleyError error) {
this.onErrorResponse(error);
}
@Override public void onErrorResponse(VolleyError error) {
this.mReservoir.accept(error);
}
@Override public void onResponse(JSONObject response) {
this.mReservoir.accept(response);
}
}
|
CaMnter/SaveVolley
|
extensions/savevolley-okhttp3-agera-core/src/main/java/com/camnter/savevolley/okhttp3/agera/core/OkHttp3JsonReservoirRequest.java
|
Java
|
apache-2.0
| 2,921
|
#include "MoFgRender.h"
MO_NAMESPACE_BEGIN
MO_CLASS_IMPLEMENT_INHERITS(FRenderMaterialTexture, FInstance);
//============================================================
// <T>¹¹ÔìäÖÈ¾ÎÆÀí¡£</T>
//============================================================
FRenderMaterialTexture::FRenderMaterialTexture(){
}
//============================================================
// <T>Îö¹¹äÖÈ¾ÎÆÀí¡£</T>
//============================================================
FRenderMaterialTexture::~FRenderMaterialTexture(){
}
MO_NAMESPACE_END
|
favedit/MoCross
|
Source/Cross/Feature/MoFeatureGraphic/FRenderMaterialTexture.cpp
|
C++
|
apache-2.0
| 536
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <boost/regex.hpp>
#include "Node.hh"
namespace avro {
Node::~Node()
{ }
void
Node::checkName(const std::string &name) const
{
static const boost::regex exp("[A-Za-z_][A-Za-z0-9_]*");
if(!name.empty() && !boost::regex_match(name, exp)) {
throw Exception("Names must match [A-Za-z_][A-Za-z0-9_]*");
}
}
} // namespace avro
|
philz/avro
|
src/c++/impl/Node.cc
|
C++
|
apache-2.0
| 1,163
|
# MetaVertex.DataModel
This library assists with using strongly-typed POCO objects against "traditional" ADO.NET objects
such as `DbDataReader`, `DbParameter`, `DbCommand`, etc. It is a work in progress but the basic
functionality is in place.
It makes extensive use of C# attributes to mark up POCO types and properties to create and read
strongly-typed models.
## Use Cases
This package is most useful in these scenarios:
* Using a database provider which doesn't support Entity Framework.
* Working with an existing database or with lots of stored procedures.
* Working with a database that doesn't make good use of strong types (e.g. it uses strings for date
input parameters) and therefore needs custom casting / parsing etc.
The main `MetaVertex.DataModel` library contains provider-agnostic code. It targets **.NET Standard 1.4**.
The `MetaVertex.DataModel.Db2` library contains logic specific to [`IBM.Data.DB2.iSeries`](https://www.nuget.org/packages/IBM.Data.DB2.iSeries/).
It is written in **.NET 4.6** since the IBM library does not support .NET Standard.
## Usage
Better docs coming soon. For now, check out the unit tests and code comments. There are two general
types of POCO models supported:
1. "Result Models" which allow converting a `DbDataReader` based instance into a collection of POCO models.
2. "Query Models" which allow converting a POCO model into a collection of `DbParameter` based parameters.
Support for converting output parameters back into a POCO model is planned soon.
A simple example of returning `MyDataModel` result models from a `DbCommand.ExecuteReader()` call:
```csharp
public class MyDataModel
{
[DataField("NAME")]
public string Name { get; set; }
[DataField("START_DATE")]
public DateTime StartDate { get; set; }
[DataField("ITEM_COUNT")]
public int ItemCount { get; set; }
[DataField("ITEM_COST")]
public decimal Cost { get; set; }
public string NonMappedValue { get; set; }
}
```
Then in your data access layer:
```csharp
public IEnumerable<MyDataModel> GetDataModels(DbCommand cmd)
{
using (var reader = cmd.ExecuteReader())
{
var info = reader.GetModelInfo<MyDataModel>();
while (reader.Read())
{
yield return info.GetModel();
}
}
}
```
## Installation
Install from [the NuGet package](https://www.nuget.org/packages/MetaVertex.DataModel) using Visual Studio or PowerShell:
Install-Package MetaVertex.DataModel -Pre
Or, add as a `PackageReference` to your .NET Core `csproj` file:
<ItemGroup>
<PackageReference Include="MetaVertex.DataModel" Version="0.2.0-a022" />
</ItemGroup>
|
metavertex/MetaVertex.DataModel
|
README.md
|
Markdown
|
apache-2.0
| 2,840
|
// Copyright 2016 The HongJiang Library Project Authors. All right reserved.
// Use of this source code is governed by a Apache-style
// license that can be found in the LICENSE file.
//
// Administrator服務之簡體中文語言包
//
// @authors hjboss <hongjiangproject@gmail.com> 2016-07-05 13:45:04 CST $$
// @version 0.1.0
module.exports = {
error: {
apiKey: '客户端版本过低,请及时升级!',
notExists: '当前管理账号不存在',
password: '管理账号或密码出现错误',
noPermissions: '当前设备无权限访问',
timeout: '登录会话已过期,请点击注销重新登录'
},
'siteTitle': 'Collavis China',
'homeTitle': '康萊美姿 ',
'siteKeyword': '康萊美姿 collavis.com.cn',
'siteDescription': '康萊美姿 化妝品國際著名品牌',
'siteAuthor': 'collavis.com.cn',
'siteCopyright': 'collavis.com.cn, 2016 co.ltd',
'footerCompany': '濟南康婷生物科技有限公司 JINAN CO.LTD',
'footerCopyright': '聯繫我們:400-636-9331 聯系時間:週一至週五 09:00-18:00(法定節假日除外)',
}
|
hongjiangboss/collavis.com.cn
|
administrator/locales/zh.js
|
JavaScript
|
apache-2.0
| 1,245
|
#include <RefCounted.h>
#include <Lockable.h>
// DataSet.h
class DataSet : public RefCounted, public Lockable
{
public:
DataSet();
off_t open(const char *fileName, int npoleGuess, float sampRate);
int getNPoles() const { return _nPoles; }
off_t getFrameCount() const { return _frameCount; }
int getFrame(float frameno, float *pCoeffs);
protected:
~DataSet();
void allocArray(int nPoles);
private:
int _nPoles;
off_t _frameCount;
int _fdesc;
int _lpHeaderSize;
float *_array;
off_t _oldframe, _endframe;
int _framsize;
int _fprec;
int _recsize;
int _bprec;
int _bpframe;
int _npolem1;
bool _swapped;
};
|
RTcmix/RTcmix
|
insts/std/LPCPLAY/DataSet.h
|
C
|
apache-2.0
| 625
|
// Generated by typings
// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/de82425735f84a10b43921ae4b1d085b3752a626/mocha/mocha.d.ts
interface MochaSetupOptions {
//milliseconds to wait before considering a test slow
slow?: number;
// timeout in milliseconds
timeout?: number;
// ui name "bdd", "tdd", "exports" etc
ui?: string;
//array of accepted globals
globals?: any[];
// reporter instance (function or string), defaults to `mocha.reporters.Spec`
reporter?: any;
// bail on the first test failure
bail?: boolean;
// ignore global leaks
ignoreLeaks?: boolean;
// grep string or regexp to filter tests with
grep?: any;
}
interface MochaDone {
(error?: Error): void;
}
declare var mocha: Mocha;
declare var describe: Mocha.IContextDefinition;
declare var xdescribe: Mocha.IContextDefinition;
// alias for `describe`
declare var context: Mocha.IContextDefinition;
// alias for `describe`
declare var suite: Mocha.IContextDefinition;
declare var it: Mocha.ITestDefinition;
declare var xit: Mocha.ITestDefinition;
// alias for `it`
declare var test: Mocha.ITestDefinition;
declare var specify: Mocha.ITestDefinition;
declare function before(action: () => void): void;
declare function before(action: (done: MochaDone) => void): void;
declare function before(description: string, action: () => void): void;
declare function before(description: string, action: (done: MochaDone) => void): void;
declare function setup(action: () => void): void;
declare function setup(action: (done: MochaDone) => void): void;
declare function after(action: () => void): void;
declare function after(action: (done: MochaDone) => void): void;
declare function after(description: string, action: () => void): void;
declare function after(description: string, action: (done: MochaDone) => void): void;
declare function teardown(action: () => void): void;
declare function teardown(action: (done: MochaDone) => void): void;
declare function beforeEach(action: () => void): void;
declare function beforeEach(action: (done: MochaDone) => void): void;
declare function beforeEach(description: string, action: () => void): void;
declare function beforeEach(description: string, action: (done: MochaDone) => void): void;
declare function suiteSetup(action: () => void): void;
declare function suiteSetup(action: (done: MochaDone) => void): void;
declare function afterEach(action: () => void): void;
declare function afterEach(action: (done: MochaDone) => void): void;
declare function afterEach(description: string, action: () => void): void;
declare function afterEach(description: string, action: (done: MochaDone) => void): void;
declare function suiteTeardown(action: () => void): void;
declare function suiteTeardown(action: (done: MochaDone) => void): void;
declare class Mocha {
constructor(options?: {
grep?: RegExp;
ui?: string;
reporter?: string;
timeout?: number;
bail?: boolean;
});
/** Setup mocha with the given options. */
setup(options: MochaSetupOptions): Mocha;
bail(value?: boolean): Mocha;
addFile(file: string): Mocha;
/** Sets reporter by name, defaults to "spec". */
reporter(name: string): Mocha;
/** Sets reporter constructor, defaults to mocha.reporters.Spec. */
reporter(reporter: (runner: Mocha.IRunner, options: any) => any): Mocha;
ui(value: string): Mocha;
grep(value: string): Mocha;
grep(value: RegExp): Mocha;
invert(): Mocha;
ignoreLeaks(value: boolean): Mocha;
checkLeaks(): Mocha;
/**
* Function to allow assertion libraries to throw errors directly into mocha.
* This is useful when running tests in a browser because window.onerror will
* only receive the 'message' attribute of the Error.
*/
throwError(error: Error): void;
/** Enables growl support. */
growl(): Mocha;
globals(value: string): Mocha;
globals(values: string[]): Mocha;
useColors(value: boolean): Mocha;
useInlineDiffs(value: boolean): Mocha;
timeout(value: number): Mocha;
slow(value: number): Mocha;
enableTimeouts(value: boolean): Mocha;
asyncOnly(value: boolean): Mocha;
noHighlighting(value: boolean): Mocha;
/** Runs tests and invokes `onComplete()` when finished. */
run(onComplete?: (failures: number) => void): Mocha.IRunner;
}
// merge the Mocha class declaration with a module
declare namespace Mocha {
/** Partial interface for Mocha's `Runnable` class. */
interface IRunnable {
title: string;
fn: Function;
async: boolean;
sync: boolean;
timedOut: boolean;
}
/** Partial interface for Mocha's `Suite` class. */
interface ISuite {
parent: ISuite;
title: string;
fullTitle(): string;
}
/** Partial interface for Mocha's `Test` class. */
interface ITest extends IRunnable {
parent: ISuite;
pending: boolean;
fullTitle(): string;
}
/** Partial interface for Mocha's `Runner` class. */
interface IRunner {}
interface IContextDefinition {
(description: string, spec: () => void): ISuite;
only(description: string, spec: () => void): ISuite;
skip(description: string, spec: () => void): void;
timeout(ms: number): void;
}
interface ITestDefinition {
(expectation: string, assertion?: () => void): ITest;
(expectation: string, assertion?: (done: MochaDone) => void): ITest;
only(expectation: string, assertion?: () => void): ITest;
only(expectation: string, assertion?: (done: MochaDone) => void): ITest;
skip(expectation: string, assertion?: () => void): void;
skip(expectation: string, assertion?: (done: MochaDone) => void): void;
timeout(ms: number): void;
}
export module reporters {
export class Base {
stats: {
suites: number;
tests: number;
passes: number;
pending: number;
failures: number;
};
constructor(runner: IRunner);
}
export class Doc extends Base {}
export class Dot extends Base {}
export class HTML extends Base {}
export class HTMLCov extends Base {}
export class JSON extends Base {}
export class JSONCov extends Base {}
export class JSONStream extends Base {}
export class Landing extends Base {}
export class List extends Base {}
export class Markdown extends Base {}
export class Min extends Base {}
export class Nyan extends Base {}
export class Progress extends Base {
/**
* @param options.open String used to indicate the start of the progress bar.
* @param options.complete String used to indicate a complete test on the progress bar.
* @param options.incomplete String used to indicate an incomplete test on the progress bar.
* @param options.close String used to indicate the end of the progress bar.
*/
constructor(runner: IRunner, options?: {
open?: string;
complete?: string;
incomplete?: string;
close?: string;
});
}
export class Spec extends Base {}
export class TAP extends Base {}
export class XUnit extends Base {
constructor(runner: IRunner, options?: any);
}
}
}
declare module "mocha" {
export = Mocha;
}
|
rmichela/bastion
|
typings/globals/mocha/index.d.ts
|
TypeScript
|
apache-2.0
| 7,656
|
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package org.tud.inf.st.pccs.impl;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.EObjectImpl;
import org.tud.inf.st.pccs.AbstractParser;
import org.tud.inf.st.pccs.OperatorTableEntry;
import org.tud.inf.st.pccs.PccsPackage;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Operator Table Entry</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.tud.inf.st.pccs.impl.OperatorTableEntryImpl#getParser <em>Parser</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public abstract class OperatorTableEntryImpl extends EObjectImpl implements OperatorTableEntry {
/**
* The cached value of the '{@link #getParser() <em>Parser</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getParser()
* @generated
* @ordered
*/
protected AbstractParser parser;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected OperatorTableEntryImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected EClass eStaticClass() {
return PccsPackage.Literals.OPERATOR_TABLE_ENTRY;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public AbstractParser getParser() {
return parser;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetParser(AbstractParser newParser, NotificationChain msgs) {
AbstractParser oldParser = parser;
parser = newParser;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, PccsPackage.OPERATOR_TABLE_ENTRY__PARSER, oldParser, newParser);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setParser(AbstractParser newParser) {
if (newParser != parser) {
NotificationChain msgs = null;
if (parser != null)
msgs = ((InternalEObject)parser).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - PccsPackage.OPERATOR_TABLE_ENTRY__PARSER, null, msgs);
if (newParser != null)
msgs = ((InternalEObject)newParser).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - PccsPackage.OPERATOR_TABLE_ENTRY__PARSER, null, msgs);
msgs = basicSetParser(newParser, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, PccsPackage.OPERATOR_TABLE_ENTRY__PARSER, newParser, newParser));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case PccsPackage.OPERATOR_TABLE_ENTRY__PARSER:
return basicSetParser(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case PccsPackage.OPERATOR_TABLE_ENTRY__PARSER:
return getParser();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case PccsPackage.OPERATOR_TABLE_ENTRY__PARSER:
setParser((AbstractParser)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void eUnset(int featureID) {
switch (featureID) {
case PccsPackage.OPERATOR_TABLE_ENTRY__PARSER:
setParser((AbstractParser)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean eIsSet(int featureID) {
switch (featureID) {
case PccsPackage.OPERATOR_TABLE_ENTRY__PARSER:
return parser != null;
}
return super.eIsSet(featureID);
}
} //OperatorTableEntryImpl
|
paetti1988/qmate
|
PCCS/org.tud.inf.st.pceditor/src-gen/org/tud/inf/st/pccs/impl/OperatorTableEntryImpl.java
|
Java
|
apache-2.0
| 4,417
|
# AUTOGENERATED FILE
FROM balenalib/artik530-debian:bullseye-run
# remove several traces of debian python
RUN apt-get purge -y python.*
# http://bugs.python.org/issue19846
# > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK.
ENV LANG C.UTF-8
# install python dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates \
netbase \
&& rm -rf /var/lib/apt/lists/*
# key 63C7CC90: public key "Simon McVittie <smcv@pseudorandom.co.uk>" imported
# key 3372DCFA: public key "Donald Stufft (dstufft) <donald@stufft.io>" imported
RUN gpg --batch --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \
&& gpg --batch --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \
&& gpg --batch --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059
ENV PYTHON_VERSION 3.5.10
# if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'"
ENV PYTHON_PIP_VERSION 21.0.1
ENV SETUPTOOLS_VERSION 56.0.0
RUN set -x \
&& buildDeps=' \
curl \
' \
&& apt-get update && apt-get install -y $buildDeps --no-install-recommends && rm -rf /var/lib/apt/lists/* \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-armv7hf-openssl1.1.tar.gz" \
&& echo "4abc87b995e08c143de14f26d8ab6ffd9017aad400bf91bc36a802efda7fe27a Python-$PYTHON_VERSION.linux-armv7hf-openssl1.1.tar.gz" | sha256sum -c - \
&& tar -xzf "Python-$PYTHON_VERSION.linux-armv7hf-openssl1.1.tar.gz" --strip-components=1 \
&& rm -rf "Python-$PYTHON_VERSION.linux-armv7hf-openssl1.1.tar.gz" \
&& ldconfig \
&& if [ ! -e /usr/local/bin/pip3 ]; then : \
&& curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \
&& echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \
&& python3 get-pip.py \
&& rm get-pip.py \
; fi \
&& pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \
&& find /usr/local \
\( -type d -a -name test -o -name tests \) \
-o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \
-exec rm -rf '{}' + \
&& cd / \
&& rm -rf /usr/src/python ~/.cache
# make some useful symlinks that are expected to exist
RUN cd /usr/local/bin \
&& ln -sf pip3 pip \
&& { [ -e easy_install ] || ln -s easy_install-* easy_install; } \
&& ln -sf idle3 idle \
&& ln -sf pydoc3 pydoc \
&& ln -sf python3 python \
&& ln -sf python3-config python-config
# set PYTHONPATH to point to dist-packages
ENV PYTHONPATH /usr/lib/python3/dist-packages:$PYTHONPATH
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@python.sh" \
&& echo "Running test-stack@python" \
&& chmod +x test-stack@python.sh \
&& bash test-stack@python.sh \
&& rm -rf test-stack@python.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Debian Bullseye \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.5.10, Pip v21.0.1, Setuptools v56.0.0 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh
|
nghiant2710/base-images
|
balena-base-images/python/artik530/debian/bullseye/3.5.10/run/Dockerfile
|
Dockerfile
|
apache-2.0
| 4,097
|
package com.lucidastar.hodgepodge.ui.activity.otherfeature.saidl;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.lucidastar.hodgepodge.R;
public class StudentAidlActivity extends AppCompatActivity {
private LocalService localService;
MyConnection mServiceConnection;
boolean mBound = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_aidl);
}
@Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this,LocalService.class);
mServiceConnection = new MyConnection();
bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
}
public void testBinderService(View view){
int randomNum = localService.getRandomNum();
Toast.makeText(getApplicationContext(),"获取到了数字"+randomNum,Toast.LENGTH_SHORT).show();
Log.i("mine", "onServiceConnected: "+randomNum);
}
private class MyConnection implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.i("mine", "链接成功");
LocalService.LocalBinder binder = (LocalService.LocalBinder) service;
localService = binder.getService();
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(mServiceConnection);
}
}
|
Lucidastar/hodgepodgeForAndroid
|
app/src/main/java/com/lucidastar/hodgepodge/ui/activity/otherfeature/saidl/StudentAidlActivity.java
|
Java
|
apache-2.0
| 1,876
|
/*
* Copyright (c) 2021 Trail of Bits, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace {
DEF_COND_SEM(DoNOP) {
return memory;
}
} // namespace
DEF_ISEL(NOP) = DoNOP;
DEF_ISEL(HINT_1) = DoNOP;
DEF_ISEL(HINT_2) = DoNOP;
DEF_ISEL(HINT_3) = DoNOP;
DEF_ISEL(HINT_4) = DoNOP;
DEF_ISEL(HINT_5) = DoNOP;
DEF_ISEL(HINT_6) = DoNOP;
DEF_ISEL(HINT_7) = DoNOP;
DEF_ISEL(HINT_8) = DoNOP;
DEF_ISEL(HINT_9) = DoNOP;
DEF_ISEL(HINT_10) = DoNOP;
DEF_ISEL(HINT_11) = DoNOP;
|
trailofbits/remill
|
lib/Arch/AArch32/Semantics/MISC.cpp
|
C++
|
apache-2.0
| 991
|
package com.github.ckwen.je.spring.boot.security.web;
public interface ControllerConstant {
static final String ACTION_STATE = "actionState";
static final String SUCCESS = "success";
static final String ERROR = "error";
static final String ROLE_PREFIX = "ROLE_";
}
|
ckwen/je
|
je-spring-boot/je-spring-boot-security/src/main/java/com/github/ckwen/je/spring/boot/security/web/ControllerConstant.java
|
Java
|
apache-2.0
| 300
|
using Android.OS;
using Android.Views;
using Osmdroid.Views;
namespace OsmdroidAndroidSample.SampleFragments
{
public class SampleFragmentXmlLayout : BaseSampleFragment
{
public static string Title = "MapView in XML layout";
public override string GetSampleTitle()
{
return Title;
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var v = inflater.Inflate(Resource.Layout.MapView, null);
MapView = v.FindViewById<MapView>(Resource.Id.mapview);
return v;
}
}
}
|
osmdroid/OsmdroidXamarin
|
OsmdroidAndroidSample/SampleFragments/SampleFragmentXmlLayout.cs
|
C#
|
apache-2.0
| 639
|
# Leucosphaera bainesii Gilg SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
H. G. A. Engler & K. A. E. Prantl, Nat. Pflanzenfam. Nachtr. 1:153. 1897
#### Original name
null
### Remarks
null
|
mdoering/backbone
|
life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Amaranthaceae/Leucosphaera/Leucosphaera bainesii/README.md
|
Markdown
|
apache-2.0
| 244
|
from __future__ import division
import datetime as dt
missing = object()
try:
import numpy as np
except ImportError:
np = None
def int_to_rgb(number):
"""Given an integer, return the rgb"""
number = int(number)
r = number % 256
g = (number // 256) % 256
b = (number // (256 * 256)) % 256
return r, g, b
def rgb_to_int(rgb):
"""Given an rgb, return an int"""
return rgb[0] + (rgb[1] * 256) + (rgb[2] * 256 * 256)
def get_duplicates(seq):
seen = set()
duplicates = set(x for x in seq if x in seen or seen.add(x))
return duplicates
def np_datetime_to_datetime(np_datetime):
ts = (np_datetime - np.datetime64('1970-01-01T00:00:00Z')) / np.timedelta64(1, 's')
dt_datetime = dt.datetime.utcfromtimestamp(ts)
return dt_datetime
class VBAWriter(object):
class Block(object):
def __init__(self, writer, start):
self.writer = writer
self.start = start
def __enter__(self):
self.writer.writeln(self.start)
self.writer._indent += 1
def __exit__(self, exc_type, exc_val, exc_tb):
self.writer._indent -= 1
#self.writer.writeln(self.end)
def __init__(self, f):
self.f = f
self._indent = 0
self._freshline = True
def block(self, template, **kwargs):
return VBAWriter.Block(self, template.format(**kwargs))
def start_block(self, template, **kwargs):
self.writeln(template, **kwargs)
self._indent += 1
def end_block(self, template, **kwargs):
self.writeln(template, **kwargs)
self._indent -= 1
def write(self, template, **kwargs):
if self._freshline:
self.f.write('\t' * self._indent)
self._freshline = False
if kwargs:
template = template.format(**kwargs)
self.f.write(template)
if template[-1] == '\n':
self._freshline = True
def write_label(self, label):
self._indent -= 1
self.write(label + ':\n')
self._indent += 1
def writeln(self, template, **kwargs):
self.write(template + '\n', **kwargs)
|
Juanlu001/xlwings
|
xlwings/utils.py
|
Python
|
apache-2.0
| 2,171
|
using UnityEngine;
public class Test
{
public void Method()
{
// This won't complete, because we don't complete ALL types, and this resolves to UnityEngine.Grid
var so = ScriptableObject.CreateInstance("Edit{caret}");
}
}
|
JetBrains/resharper-unity
|
resharper/resharper-unity/test/data/Unity/CSharp/Resolve/UnityObjectTypeInStringLiteral/CodeCompletion/ScriptableObjectCreateInstance03.cs
|
C#
|
apache-2.0
| 251
|
/*
* Copyright 2016-2020 Daniel Urban and contributors listed in 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 dev.tauri.seals
package circe
import io.circe._
import io.circe.syntax._
import org.scalatest.matchers.{ Matcher, MatchResult }
import scala.Vector
trait BaseJsonSpec extends tests.BaseSpec {
def roundtripJson[A : Encoder : Decoder](a: A): A = {
val json: Json = a.asJson
json.as[A].fold(
f => fail(f.toString),
r => r
)
}
def checkJson[A : Encoder : Decoder](a: A): A = {
val res: A = roundtripJson(a)
res should === (a)
a should === (res)
a.## should === (res.##)
res
}
def checkJsonId[A <: AnyRef : Encoder : Decoder](a: A): A = {
val res = checkJson(a)
res shouldBe theSameInstanceAs (a)
res
}
// TODO: also check cursor history
def failWith(msg: String = ".*"): Matcher[Decoder.Result[Model]] = Matcher { res =>
res.fold(
failure => MatchResult(
failure.message.matches(msg),
"actual error message {0} does not match {1}",
"actual error message {0} matches {1}", // FIXME
args = Vector(failure.message, msg)
),
success => MatchResult(
false,
"a decoding success (with result {0}) is not a failure with message {1}",
"a decoding success (with result {0}) is a failure with message {1}", // FIXME
args = Vector(success, msg)
)
)
}
}
|
durban/seals
|
circe/src/test/scala/dev/tauri/seals/circe/BaseJsonSpec.scala
|
Scala
|
apache-2.0
| 1,957
|
<?php
namespace Hamcrest\Text;
/*
Copyright (c) 2010 hamcrest.org
*/
/**
* Tests if the argument is a string that contains a substring ignoring case.
*/
class StringContainsIgnoringCase extends SubstringMatcher
{
public function __construct($substring)
{
parent::__construct($substring);
}
/**
* Matches if value is a string that contains $substring regardless of the case.
*
* @factory
*/
public static function containsStringIgnoringCase($substring)
{
return new self($substring);
}
// -- Protected Methods
protected function evalSubstringOf($item)
{
return (false !== stripos((string) $item, $this->_substring));
}
protected function relationship()
{
return 'containing in any case';
}
}
|
focuslife/v0.1
|
vendor/hamcrest/hamcrest-php/hamcrest/Hamcrest/Text/StringContainsIgnoringCase.php
|
PHP
|
apache-2.0
| 850
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.