code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
import {inject, customElement, bindable} from 'aurelia-framework';
import mapsapi from 'google-maps-api';
@customElement('place-picker')
// Get an API key from https://developers.google.com/maps/documentation/javascript/get-api-key.
@inject(Element, mapsapi('AIzaSyA1QmM_IG94DN0kCl7l1dblf4C8vRiuxus', ['places']))
export class PlacePicker {
@bindable location;
constructor(element, mapsApi) {
this.element = element;
this.mapsApi = mapsApi;
}
attached() {
// This loads the Google Maps API asynchronously.
this.mapsApi.then(maps => {
// Now that it's loaded, add a map to our HTML.
var mapContainer = this.element.querySelector('.place-picker-map');
var map = new maps.Map(mapContainer, {
center: {lat: -33.8688, lng: 151.2195},
zoom: 13
});
// Also convert our input field into a place autocomplete field.
var input = this.element.querySelector('input');
var autocomplete = new google.maps.places.Autocomplete(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
autocomplete.bindTo('bounds', map);
// Create a marker that will show where the selected place is.
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
// Create a lambda that moves the marker and the map viewport.
let updateMarker = () => {
var position = new google.maps.LatLng(this.location.lat, this.location.lng);
map.setCenter(position);
marker.setPosition(position);
marker.setVisible(true);
};
// Ensure that the current location is shown properly.
updateMarker();
// Update the location and its marker every time a new place is selected.
autocomplete.addListener('place_changed', () => {
marker.setVisible(false);
var place = autocomplete.getPlace();
if (place.geometry) {
this.location.name = place.name;
this.location.lat = place.geometry.location.lat();
this.location.lng = place.geometry.location.lng();
updateMarker();
}
});
});
}
}
| ne0guille/skeleton-navigation | skeleton-esnext/src/place-picker.js | JavaScript | cc0-1.0 | 2,167 |
(function () {
'use strict';
angular
.module('tierraDeColoresApp')
.service('fiscalService', fiscalService);
fiscalService.$inject = ['$q', '$http', 'cookieService', 'BaseURL', 'toaster', '$rootScope'];
function fiscalService($q, $http, cookieService, BaseURL, toaster, $rootScope) {
const exec = require('child_process').exec;
const http = require('http');
const fs = require('fs');
const path = require('path');
var parser = document.createElement('a');
parser.href = BaseURL;
var Auth = {
'usuario': 'AFIP_SMH/P-441F',
'password': 'T13RR4$7j15vker4L-L'
};
this.read = function () {
var datosRecu = null;
var deferred = $q.defer();
var filePath = path.join(__dirname, 'FILE.ans');
fs.readFile(filePath, {encoding: 'utf-8'}, function (err, data) {
if (!err) {
datosRecu = data;
deferred.resolve(datosRecu);
}
});
return deferred.promise;
};
function print(tipo) {
exec('wspooler.exe -p4 -l -f FILE.200', function (err, stdout, stderr) {
if (err !== null) {
console.log(err);
$rootScope.$broadcast("printState", {tipo: tipo, status: false});
} else {
$rootScope.$broadcast("printState", {tipo: tipo, status: true});
}
});
}
this.cleanFiles = function () {
fs.unlink('FILE.200', function (err) {
if (err) {
console.log(err);
}
console.log('successfully deleted FILE.200');
});
fs.unlink('FILE.ans', function (err) {
if (err) {
console.log(err);
}
console.log('successfully deleted FILE.ans');
});
return true;
};
this.factura_aOrFactura_b = function (factura, cliente, type) {
var options = null;
var token = cookieService.get('token');
var tipo;
token.then(function (data) {
options = {
host: parser.hostname,
port: parser.port,
method: 'POST',
headers: {
'Authorization': 'Bearer ' + data
}
};
if (type === 0) {
options.path = '/fiscal/factura_a?factura=' + factura + "&cliente=" + cliente;
tipo = "Factura A";
} else if (1) {
options.path = '/fiscal/factura_b?factura=' + factura + "&cliente=" + cliente;
tipo = "Factura B";
}
var files = fs.createWriteStream("FILE.200");
var request = http.get(options, function (response) {
if (response.statusCode === 200) {
response.pipe(files);
print(tipo);
}
});
});
};
this.ticketOrRegalo = function (factura, serial) {
var token = cookieService.get('token');
var type;
token.then(function (data) {
var options = {
host: parser.hostname,
port: parser.port,
method: 'POST',
headers: {
'Authorization': 'Bearer ' + data
}
};
if (serial !== null & typeof serial !== 'undefined') {
options.path = '/fiscal/regalo?factura=' + factura + "&serial=" + serial;
type = "Regalo";
} else {
options.path = '/fiscal/ticket?factura=' + factura;
}
var files = fs.createWriteStream("FILE.200");
var request = http.get(options, function (response) {
if (response.statusCode === 200) {
response.pipe(files);
print();
}
});
});
};
this.comprobanteZ = function () {
var deferred = $q.defer();
const exec = require('child_process').exec;
exec('wspooler.exe -p4 -l -f compZ.200', (err, stdout, stderr) => {
if (err !== null) {
deferred.resolve(false);
console.log(err);
console.log(stderr);
console.log(stdout);
} else {
deferred.resolve(true);
}
});
return deferred.promise;
};
this.isConnected = function () {
var deferred = $q.defer();
const exec = require('child_process').exec;
exec('wspooler.exe -p4 -l -f CONNECTED.200', (err, stdout, stderr) => {
if (err !== null) {
deferred.resolve(false);
console.log(err);
console.log(stderr);
console.log(stdout);
} else {
deferred.resolve(true);
}
});
return deferred.promise;
};
}
})(); | CosmicaJujuy/TierraDesktop | scripts/angular/service/FiscalService.js | JavaScript | cc0-1.0 | 5,523 |
/**!
* LibreMoney DgsListing api 0.2
* Copyright (c) LibreMoney Team <libremoney@yandex.com>
* CC0 license
*/
/*
import nxt.Account;
import nxt.Attachment;
import nxt.Constants;
import nxt.NxtException;
import nxt.util.Convert;
import org.json.simple.JSONStreamAware;
import static nxt.http.JSONResponses.INCORRECT_DGS_LISTING_DESCRIPTION;
import static nxt.http.JSONResponses.INCORRECT_DGS_LISTING_NAME;
import static nxt.http.JSONResponses.INCORRECT_DGS_LISTING_TAGS;
import static nxt.http.JSONResponses.MISSING_NAME;
*/
//super(new APITag[] {APITag.DGS, APITag.CREATE_TRANSACTION}, "name", "description", "tags", "quantity", "priceNQT");
function DgsListing(req, res) {
res.send('This is not implemented');
/*
String name = Convert.emptyToNull(req.getParameter("name"));
String description = Convert.nullToEmpty(req.getParameter("description"));
String tags = Convert.nullToEmpty(req.getParameter("tags"));
long priceNQT = ParameterParser.getPriceNQT(req);
int quantity = ParameterParser.getGoodsQuantity(req);
if (name == null) {
return MISSING_NAME;
}
name = name.trim();
if (name.length() > Constants.MAX_DGS_LISTING_NAME_LENGTH) {
return INCORRECT_DGS_LISTING_NAME;
}
if (description.length() > Constants.MAX_DGS_LISTING_DESCRIPTION_LENGTH) {
return INCORRECT_DGS_LISTING_DESCRIPTION;
}
if (tags.length() > Constants.MAX_DGS_LISTING_TAGS_LENGTH) {
return INCORRECT_DGS_LISTING_TAGS;
}
Account account = ParameterParser.getSenderAccount(req);
Attachment attachment = new Attachment.DigitalGoodsListing(name, description, tags, quantity, priceNQT);
return createTransaction(req, account, attachment);
*/
}
module.exports = DgsListing;
| libremoney/main | Lm/Modules/DigitalGoods/Api/DgsListing.js | JavaScript | cc0-1.0 | 1,680 |
package com.sp.jb.service;
import com.sp.jb.model.Circle;
import com.sp.jb.model.Triangle;
public class ShapeService {
private Circle circle;
private Triangle triangle;
public Circle getCircle() {
return circle;
}
public void setCircle(Circle circle) {
this.circle = circle;
}
public Triangle getTriangle() {
return triangle;
}
public void setTriangle(Triangle triangle) {
this.triangle = triangle;
}
}
| samirprakash/spring-aop | src/com/sp/jb/service/ShapeService.java | Java | cc0-1.0 | 482 |
<div class="title font-quicksand"><?php _e("Payment Plans",ET_DOMAIN);?></div>
<div class="desc">
<?php _e("Set payment plans your employers can choose from when posting new jobs.",ET_DOMAIN);?>
<!-- <a class="find-out font-quicksand" href="#">
<?php _e("Find out more",ET_DOMAIN);?><span class="icon" data-icon="i"></span>
</a> -->
<div class="inner">
<div id="payment_lists">
<?php
$plans = et_get_payment_plans();
$json_plans = array();
if ( is_array($plans) ){
echo '<ul class="pay-plans-list sortable">';
foreach ((array)$plans as $plan) {
$tooltip = array(
'delete' => __('Delete', ET_DOMAIN),
'edit' => __('Edit', ET_DOMAIN),
);
$feature = $plan['featured'] == 1 ? '<em class="icon-text">^</em>' : '';
?>
<li class="item" id="payment_<?php echo $plan['ID'] ?>" data="<?php echo $plan['ID'] ?>">
<div class="sort-handle"></div>
<span><?php echo $plan['title'] . ' ' . $feature?></span>
<?php printf( __('%s for %s days', ET_DOMAIN), et_get_price_format($plan['price']), $plan['duration'] ) ?>
<div class="actions">
<a href="#" title="<?php _e('Edit', ET_DOMAIN) ?>" class="icon act-edit" rel="<?php echo $plan['ID'] ?>" data-icon="p"></a>
<a href="#" title="<?php _e('Delete', ET_DOMAIN) ?>" class="icon act-del" rel="<?php echo $plan['ID'] ?>" data-icon="D"></a>
</div>
</li>
<?php
}
echo '</ul>';
}
else {
echo '<p>' . __('There is no added plan yet' ,ET_DOMAIN) . '</p>';
}
?>
</div>
<script type="application/json" id="payment_plans_data">
<?php echo json_encode( array_map('et_create_payment_plan_response', array_values($plans)) ) ?>
</script>
<div class="item">
<form id="payment_plans_form" action="" class="engine-payment-form">
<input type="hidden" name="action" value="et-save-payment">
<input type="hidden" name="et_action" value="et-save-payment">
<div class="form payment-plan">
<div class="form-item">
<div class="label"><?php _e("Enter a name for your plan",ET_DOMAIN);?></div>
<input class="bg-grey-input not-empty" name="payment_name" type="text" />
</div>
<div class="form-item f-left-all clearfix">
<div class="width33p">
<div class="label"><?php _e("Price",ET_DOMAIN);?></div>
<input class="bg-grey-input width50p not-empty is-number" name="payment_price" type="text" />
<?php echo $selected_currency['label']; ?>
</div>
<div class="width33p">
<div class="label"><?php _e("Availability",ET_DOMAIN);?></div>
<input class="bg-grey-input width50p not-empty is-number" type="text" name="payment_duration" />
<?php _e("days",ET_DOMAIN);?>
</div>
<div class="width33p">
<div class="label"><?php _e("Number of jobs",ET_DOMAIN);?></div>
<input class="bg-grey-input width50p not-empty is-number" type="text" name="payment_quantity" />
<?php _e("posts",ET_DOMAIN);?>
</div>
</div>
<div class="form-item">
<div class="label"><?php _e("Featured Job",ET_DOMAIN);?></div>
<input type="hidden" name="payment_featured" value="0">
<input type="checkbox" name="payment_featured" value="1"/> <?php _e("Jobs posted under this plan will be featured.",ET_DOMAIN);?>
</div>
<div class="submit">
<button id="add_playment_plan" class="btn-button engine-submit-btn">
<span><?php _e("Save Plan",ET_DOMAIN);?></span><span class="icon" data-icon="+"></span>
</button>
</div>
</div>
</form>
</div>
<script type="text/template" id="template_edit_form">
<form action="" class="edit-plan engine-payment-form">
<input type="hidden" name="action" value="et-save-payment">
<input type="hidden" name="et_action" value="et-save-payment">
<input type="hidden" name="id" value="{{id }}">
<div class="form payment-plan">
<div class="form-item">
<div class="label"><?php _e("Enter a name for your plan",ET_DOMAIN);?></div>
<input class="bg-grey-input not-empty" name="title" type="text" value="{{title }}" />
</div>
<div class="form-item f-left-all clearfix">
<div class="width33p">
<div class="label"><?php _e("Price",ET_DOMAIN);?></div>
<input class="bg-grey-input width50p not-empty is-number" name="price" type="text" value="{{ price }}"/>
<?php et_display_currency($selected_currency['label'], $selected_currency,' ','')?>
</div>
<div class="width33p">
<div class="label"><?php _e("Availability",ET_DOMAIN);?></div>
<input class="bg-grey-input width50p not-empty is-number" type="text" name="duration" value="{{ duration }}" />
days
</div>
<div class="width33p">
<div class="label"><?php _e("Jobs",ET_DOMAIN);?></div>
<input class="bg-grey-input width50p not-empty is-number" type="text" name="quantity" value="{{ quantity }}" />
<?php _e("jobs",ET_DOMAIN);?>
</div>
</div>
<div class="form-item">
<div class="label"><?php _e("Featured Job",ET_DOMAIN);?></div>
<input type="checkbox" name="featured" value="1" <# if ( featured == 1 ) { #> checked="checked" <# } #>/> <?php _e("Jobs posted under this plan will be featured.",ET_DOMAIN);?>
</div>
<div class="submit">
<button id="save_playment_plan" class="btn-button engine-submit-btn">
<span><?php _e("Save Plan",ET_DOMAIN);?></span><span class="icon" data-icon="+"></span>
</button>
or <a href="#" class="cancel-edit">Cancel</a>
</div>
</div>
</form>
</script>
</div>
</div> | C0DS3T/Yuki_Limousin | cv/wp-content/themes/jobengine/admin/setting-payment-plans.php | PHP | cc0-1.0 | 5,736 |
/* ==========================================================================
Shallow Extends
Copyright (c) 2014 Alexey Maslennikov
========================================================================== */
'use strict';
/**
* @param {object} JavaScript object.
* @returns {boolean} True if object is plain Javascript object.
*/
function _isPlainObject( object ) {
return toString.call( object ) === '[object Object]';
}
/**
* Copies properties of all sources to the destination object overriding its own
* existing properties. When extending from multiple sources, fields of every
* next source will override same named fields of previous sources.
*
* @param {object} destination object.
* @returns {bbject} extended destination object.
*/
function extend( destination ) {
destination = destination || {};
for ( var i = 1; i < arguments.length; i++ ) {
var source = arguments[i] || {};
for ( var key in source ) {
if ( source.hasOwnProperty( key ) ) {
var value = source[key];
if ( _isPlainObject( value ) ) {
extend( destination[key] = {}, value );
}else {
destination[key] = source[key];
}
}
}
}
return destination;
}
// Expose public methods.
module.exports = { extend: extend };
| imuchnik/cfgov-refresh | src/static/js/modules/util/shallow-extend.js | JavaScript | cc0-1.0 | 1,290 |
from django.db import models
# Create your models here.
class Profil(models.Model):
awal = ''
PILIHAN_JENJANG = (
(awal, '----'),
('Pertama', 'Perekayasa Pertama'),
('Muda', 'Perekayasa Muda'),
('Madya', 'Perekayasa Madya'),
('Utama', 'Perekayasa Utama'),
)
nip = models.CharField(max_length=50, verbose_name='NIP')
pendidikan = models.CharField(max_length=150, verbose_name='Pendidikan')
instansi = models.TextField(verbose_name='Nama Lengkap Unit')
instansi_kode = models.CharField(max_length=20, verbose_name='Singkatan Unit')
satuan = models.TextField(verbose_name='Nama Lengkap Satuan kerja', blank=True)
kantor = models.TextField(verbose_name='Nama Lengkap Kantor', blank=True)
pangkat = models.TextField(verbose_name='Pangkat/Golongan Ruang/TMT')
jabatan = models.CharField(max_length=150, verbose_name='Jabatan')
jenjang = models.CharField(max_length=10, verbose_name='Jenjang Perekayasa', choices=PILIHAN_JENJANG, default=awal)
user = models.ForeignKey('auth.User', verbose_name='Personil', on_delete=models.CASCADE)
class Meta:
verbose_name_plural = 'Profil'
def __str__(self):
return self.nip
| akbarpn136/perek-dj | utiliti/models.py | Python | cc0-1.0 | 1,225 |
/*
* This file is part of memoization.java. It is subject to the license terms in the LICENSE file found in the top-level
* directory of this distribution and at http://creativecommons.org/publicdomain/zero/1.0/. No part of memoization.java,
* including this file, may be copied, modified, propagated, or distributed except according to the terms contained
* in the LICENSE file.
*/
package de.xn__ho_hia.memoization.map;
import static java.util.Objects.requireNonNull;
import java.util.concurrent.ConcurrentMap;
import java.util.function.DoubleBinaryOperator;
import de.xn__ho_hia.memoization.shared.DoubleBinaryFunction;
import de.xn__ho_hia.quality.suppression.CompilerWarnings;
final class ConcurrentMapBasedDoubleBinaryOperatorMemoizer<KEY>
extends ConcurrentMapBasedMemoizer<KEY, Double>
implements DoubleBinaryOperator {
private final DoubleBinaryFunction<KEY> keyFunction;
private final DoubleBinaryOperator operator;
@SuppressWarnings(CompilerWarnings.NLS)
public ConcurrentMapBasedDoubleBinaryOperatorMemoizer(
final ConcurrentMap<KEY, Double> cache,
final DoubleBinaryFunction<KEY> keyFunction,
final DoubleBinaryOperator operator) {
super(cache);
this.keyFunction = requireNonNull(keyFunction,
"Provide a key function, might just be 'MemoizationDefaults.doubleBinaryOperatorHashCodeKeyFunction()'.");
this.operator = requireNonNull(operator,
"Cannot memoize a NULL DoubleBinaryOperator - provide an actual DoubleBinaryOperator to fix this.");
}
@Override
public double applyAsDouble(final double left, final double right) {
final KEY key = keyFunction.apply(left, right);
return computeIfAbsent(key, givenKey -> Double.valueOf(operator.applyAsDouble(left, right)))
.doubleValue();
}
}
| sebhoss/memoization.java | memoization-core/src/main/java/de/xn__ho_hia/memoization/map/ConcurrentMapBasedDoubleBinaryOperatorMemoizer.java | Java | cc0-1.0 | 1,887 |
#!/usr/bin/python3
#
# Checks that the upstream DNS has been set correctly and that
# TLS certificates have been signed, etc., and if not tells the user
# what to do next.
import sys, os, os.path, re, subprocess, datetime, multiprocessing.pool
import dns.reversename, dns.resolver
import dateutil.parser, dateutil.tz
import idna
import psutil
from dns_update import get_dns_zones, build_tlsa_record, get_custom_dns_config, get_secondary_dns, get_custom_dns_record
from web_update import get_web_domains, get_domains_with_a_records
from ssl_certificates import get_ssl_certificates, get_domain_ssl_files, check_certificate
from mailconfig import get_mail_domains, get_mail_aliases
from utils import shell, sort_domains, load_env_vars_from_file, load_settings
def run_checks(rounded_values, env, output, pool):
# run systems checks
output.add_heading("System")
# check that services are running
if not run_services_checks(env, output, pool):
# If critical services are not running, stop. If bind9 isn't running,
# all later DNS checks will timeout and that will take forever to
# go through, and if running over the web will cause a fastcgi timeout.
return
# clear bind9's DNS cache so our DNS checks are up to date
# (ignore errors; if bind9/rndc isn't running we'd already report
# that in run_services checks.)
shell('check_call', ["/usr/sbin/rndc", "flush"], trap=True)
run_system_checks(rounded_values, env, output)
# perform other checks asynchronously
run_network_checks(env, output)
run_domain_checks(rounded_values, env, output, pool)
def get_ssh_port():
# Returns ssh port
try:
output = shell('check_output', ['sshd', '-T'])
except FileNotFoundError:
# sshd is not installed. That's ok.
return None
returnNext = False
for e in output.split():
if returnNext:
return int(e)
if e == "port":
returnNext = True
# Did not find port!
return None
def run_services_checks(env, output, pool):
# Check that system services are running.
services = [
{ "name": "Local DNS (bind9)", "port": 53, "public": False, },
#{ "name": "NSD Control", "port": 8952, "public": False, },
{ "name": "Local DNS Control (bind9/rndc)", "port": 953, "public": False, },
{ "name": "Dovecot LMTP LDA", "port": 10026, "public": False, },
{ "name": "Postgrey", "port": 10023, "public": False, },
{ "name": "Spamassassin", "port": 10025, "public": False, },
{ "name": "OpenDKIM", "port": 8891, "public": False, },
{ "name": "OpenDMARC", "port": 8893, "public": False, },
{ "name": "Memcached", "port": 11211, "public": False, },
{ "name": "Mail-in-a-Box Management Daemon", "port": 10222, "public": False, },
{ "name": "SSH Login (ssh)", "port": get_ssh_port(), "public": True, },
{ "name": "Public DNS (nsd4)", "port": 53, "public": True, },
{ "name": "Incoming Mail (SMTP/postfix)", "port": 25, "public": True, },
{ "name": "Outgoing Mail (SMTP 587/postfix)", "port": 587, "public": True, },
#{ "name": "Postfix/master", "port": 10587, "public": True, },
{ "name": "IMAPS (dovecot)", "port": 993, "public": True, },
{ "name": "Mail Filters (Sieve/dovecot)", "port": 4190, "public": True, },
{ "name": "HTTP Web (nginx)", "port": 80, "public": True, },
{ "name": "HTTPS Web (nginx)", "port": 443, "public": True, },
]
all_running = True
fatal = False
ret = pool.starmap(check_service, ((i, service, env) for i, service in enumerate(services)), chunksize=1)
for i, running, fatal2, output2 in sorted(ret):
if output2 is None: continue # skip check (e.g. no port was set, e.g. no sshd)
all_running = all_running and running
fatal = fatal or fatal2
output2.playback(output)
if all_running:
output.print_ok("All system services are running.")
return not fatal
def check_service(i, service, env):
if not service["port"]:
# Skip check (no port, e.g. no sshd).
return (i, None, None, None)
output = BufferedOutput()
running = False
fatal = False
# Helper function to make a connection to the service, since we try
# up to three ways (localhost, IPv4 address, IPv6 address).
def try_connect(ip):
# Connect to the given IP address on the service's port with a one-second timeout.
import socket
s = socket.socket(socket.AF_INET if ":" not in ip else socket.AF_INET6, socket.SOCK_STREAM)
s.settimeout(1)
try:
s.connect((ip, service["port"]))
return True
except OSError as e:
# timed out or some other odd error
return False
finally:
s.close()
if service["public"]:
# Service should be publicly accessible.
if try_connect(env["PUBLIC_IP"]):
# IPv4 ok.
if not env.get("PUBLIC_IPV6") or service.get("ipv6") is False or try_connect(env["PUBLIC_IPV6"]):
# No IPv6, or service isn't meant to run on IPv6, or IPv6 is good.
running = True
# IPv4 ok but IPv6 failed. Try the PRIVATE_IPV6 address to see if the service is bound to the interface.
elif service["port"] != 53 and try_connect(env["PRIVATE_IPV6"]):
output.print_error("%s is running (and available over IPv4 and the local IPv6 address), but it is not publicly accessible at %s:%d." % (service['name'], env['PUBLIC_IP'], service['port']))
else:
output.print_error("%s is running and available over IPv4 but is not accessible over IPv6 at %s port %d." % (service['name'], env['PUBLIC_IPV6'], service['port']))
# IPv4 failed. Try the private IP to see if the service is running but not accessible (except DNS because a different service runs on the private IP).
elif service["port"] != 53 and try_connect("127.0.0.1"):
output.print_error("%s is running but is not publicly accessible at %s:%d." % (service['name'], env['PUBLIC_IP'], service['port']))
else:
output.print_error("%s is not running (port %d)." % (service['name'], service['port']))
# Why is nginx not running?
if not running and service["port"] in (80, 443):
output.print_line(shell('check_output', ['nginx', '-t'], capture_stderr=True, trap=True)[1].strip())
else:
# Service should be running locally.
if try_connect("127.0.0.1"):
running = True
else:
output.print_error("%s is not running (port %d)." % (service['name'], service['port']))
# Flag if local DNS is not running.
if not running and service["port"] == 53 and service["public"] == False:
fatal = True
return (i, running, fatal, output)
def run_system_checks(rounded_values, env, output):
check_ssh_password(env, output)
check_software_updates(env, output)
check_miab_version(env, output)
check_system_aliases(env, output)
check_free_disk_space(rounded_values, env, output)
check_free_memory(rounded_values, env, output)
def check_ssh_password(env, output):
# Check that SSH login with password is disabled. The openssh-server
# package may not be installed so check that before trying to access
# the configuration file.
if not os.path.exists("/etc/ssh/sshd_config"):
return
sshd = open("/etc/ssh/sshd_config").read()
if re.search("\nPasswordAuthentication\s+yes", sshd) \
or not re.search("\nPasswordAuthentication\s+no", sshd):
output.print_error("""The SSH server on this machine permits password-based login. A more secure
way to log in is using a public key. Add your SSH public key to $HOME/.ssh/authorized_keys, check
that you can log in without a password, set the option 'PasswordAuthentication no' in
/etc/ssh/sshd_config, and then restart the openssh via 'sudo service ssh restart'.""")
else:
output.print_ok("SSH disallows password-based login.")
def is_reboot_needed_due_to_package_installation():
return os.path.exists("/var/run/reboot-required")
def check_software_updates(env, output):
# Check for any software package updates.
pkgs = list_apt_updates(apt_update=False)
if is_reboot_needed_due_to_package_installation():
output.print_error("System updates have been installed and a reboot of the machine is required.")
elif len(pkgs) == 0:
output.print_ok("System software is up to date.")
else:
output.print_error("There are %d software packages that can be updated." % len(pkgs))
for p in pkgs:
output.print_line("%s (%s)" % (p["package"], p["version"]))
def check_system_aliases(env, output):
# Check that the administrator alias exists since that's where all
# admin email is automatically directed.
check_alias_exists("System administrator address", "administrator@" + env['PRIMARY_HOSTNAME'], env, output)
def check_free_disk_space(rounded_values, env, output):
# Check free disk space.
st = os.statvfs(env['STORAGE_ROOT'])
bytes_total = st.f_blocks * st.f_frsize
bytes_free = st.f_bavail * st.f_frsize
if not rounded_values:
disk_msg = "The disk has %s GB space remaining." % str(round(bytes_free/1024.0/1024.0/1024.0*10.0)/10)
else:
disk_msg = "The disk has less than %s%% space left." % str(round(bytes_free/bytes_total/10 + .5)*10)
if bytes_free > .3 * bytes_total:
output.print_ok(disk_msg)
elif bytes_free > .15 * bytes_total:
output.print_warning(disk_msg)
else:
output.print_error(disk_msg)
def check_free_memory(rounded_values, env, output):
# Check free memory.
percent_free = 100 - psutil.virtual_memory().percent
memory_msg = "System memory is %s%% free." % str(round(percent_free))
if percent_free >= 20:
if rounded_values: memory_msg = "System free memory is at least 20%."
output.print_ok(memory_msg)
elif percent_free >= 10:
if rounded_values: memory_msg = "System free memory is below 20%."
output.print_warning(memory_msg)
else:
if rounded_values: memory_msg = "System free memory is below 10%."
output.print_error(memory_msg)
def run_network_checks(env, output):
# Also see setup/network-checks.sh.
output.add_heading("Network")
# Stop if we cannot make an outbound connection on port 25. Many residential
# networks block outbound port 25 to prevent their network from sending spam.
# See if we can reach one of Google's MTAs with a 5-second timeout.
code, ret = shell("check_call", ["/bin/nc", "-z", "-w5", "aspmx.l.google.com", "25"], trap=True)
if ret == 0:
output.print_ok("Outbound mail (SMTP port 25) is not blocked.")
else:
output.print_error("""Outbound mail (SMTP port 25) seems to be blocked by your network. You
will not be able to send any mail. Many residential networks block port 25 to prevent hijacked
machines from being able to send spam. A quick connection test to Google's mail server on port 25
failed.""")
# Stop if the IPv4 address is listed in the ZEN Spamhaus Block List.
# The user might have ended up on an IP address that was previously in use
# by a spammer, or the user may be deploying on a residential network. We
# will not be able to reliably send mail in these cases.
rev_ip4 = ".".join(reversed(env['PUBLIC_IP'].split('.')))
zen = query_dns(rev_ip4+'.zen.spamhaus.org', 'A', nxdomain=None)
if zen is None:
output.print_ok("IP address is not blacklisted by zen.spamhaus.org.")
else:
output.print_error("""The IP address of this machine %s is listed in the Spamhaus Block List (code %s),
which may prevent recipients from receiving your email. See http://www.spamhaus.org/query/ip/%s."""
% (env['PUBLIC_IP'], zen, env['PUBLIC_IP']))
def run_domain_checks(rounded_time, env, output, pool):
# Get the list of domains we handle mail for.
mail_domains = get_mail_domains(env)
# Get the list of domains we serve DNS zones for (i.e. does not include subdomains).
dns_zonefiles = dict(get_dns_zones(env))
dns_domains = set(dns_zonefiles)
# Get the list of domains we serve HTTPS for.
web_domains = set(get_web_domains(env))
domains_to_check = mail_domains | dns_domains | web_domains
# Get the list of domains that we don't serve web for because of a custom CNAME/A record.
domains_with_a_records = get_domains_with_a_records(env)
# Serial version:
#for domain in sort_domains(domains_to_check, env):
# run_domain_checks_on_domain(domain, rounded_time, env, dns_domains, dns_zonefiles, mail_domains, web_domains)
# Parallelize the checks across a worker pool.
args = ((domain, rounded_time, env, dns_domains, dns_zonefiles, mail_domains, web_domains, domains_with_a_records)
for domain in domains_to_check)
ret = pool.starmap(run_domain_checks_on_domain, args, chunksize=1)
ret = dict(ret) # (domain, output) => { domain: output }
for domain in sort_domains(ret, env):
ret[domain].playback(output)
def run_domain_checks_on_domain(domain, rounded_time, env, dns_domains, dns_zonefiles, mail_domains, web_domains, domains_with_a_records):
output = BufferedOutput()
# we'd move this up, but this returns non-pickleable values
ssl_certificates = get_ssl_certificates(env)
# The domain is IDNA-encoded in the database, but for display use Unicode.
try:
domain_display = idna.decode(domain.encode('ascii'))
output.add_heading(domain_display)
except (ValueError, UnicodeError, idna.IDNAError) as e:
# Looks like we have some invalid data in our database.
output.add_heading(domain)
output.print_error("Domain name is invalid: " + str(e))
if domain == env["PRIMARY_HOSTNAME"]:
check_primary_hostname_dns(domain, env, output, dns_domains, dns_zonefiles)
if domain in dns_domains:
check_dns_zone(domain, env, output, dns_zonefiles)
if domain in mail_domains:
check_mail_domain(domain, env, output)
if domain in web_domains:
check_web_domain(domain, rounded_time, ssl_certificates, env, output)
if domain in dns_domains:
check_dns_zone_suggestions(domain, env, output, dns_zonefiles, domains_with_a_records)
return (domain, output)
def check_primary_hostname_dns(domain, env, output, dns_domains, dns_zonefiles):
# If a DS record is set on the zone containing this domain, check DNSSEC now.
has_dnssec = False
for zone in dns_domains:
if zone == domain or domain.endswith("." + zone):
if query_dns(zone, "DS", nxdomain=None) is not None:
has_dnssec = True
check_dnssec(zone, env, output, dns_zonefiles, is_checking_primary=True)
ip = query_dns(domain, "A")
ns_ips = query_dns("ns1." + domain, "A") + '/' + query_dns("ns2." + domain, "A")
my_ips = env['PUBLIC_IP'] + ((" / "+env['PUBLIC_IPV6']) if env.get("PUBLIC_IPV6") else "")
# Check that the ns1/ns2 hostnames resolve to A records. This information probably
# comes from the TLD since the information is set at the registrar as glue records.
# We're probably not actually checking that here but instead checking that we, as
# the nameserver, are reporting the right info --- but if the glue is incorrect this
# will probably fail.
if ns_ips == env['PUBLIC_IP'] + '/' + env['PUBLIC_IP']:
output.print_ok("Nameserver glue records are correct at registrar. [ns1/ns2.%s ↦ %s]" % (env['PRIMARY_HOSTNAME'], env['PUBLIC_IP']))
elif ip == env['PUBLIC_IP']:
# The NS records are not what we expect, but the domain resolves correctly, so
# the user may have set up external DNS. List this discrepancy as a warning.
output.print_warning("""Nameserver glue records (ns1.%s and ns2.%s) should be configured at your domain name
registrar as having the IP address of this box (%s). They currently report addresses of %s. If you have set up External DNS, this may be OK."""
% (env['PRIMARY_HOSTNAME'], env['PRIMARY_HOSTNAME'], env['PUBLIC_IP'], ns_ips))
else:
output.print_error("""Nameserver glue records are incorrect. The ns1.%s and ns2.%s nameservers must be configured at your domain name
registrar as having the IP address %s. They currently report addresses of %s. It may take several hours for
public DNS to update after a change."""
% (env['PRIMARY_HOSTNAME'], env['PRIMARY_HOSTNAME'], env['PUBLIC_IP'], ns_ips))
# Check that PRIMARY_HOSTNAME resolves to PUBLIC_IP[V6] in public DNS.
ipv6 = query_dns(domain, "AAAA") if env.get("PUBLIC_IPV6") else None
if ip == env['PUBLIC_IP'] and ipv6 in (None, env['PUBLIC_IPV6']):
output.print_ok("Domain resolves to box's IP address. [%s ↦ %s]" % (env['PRIMARY_HOSTNAME'], my_ips))
else:
output.print_error("""This domain must resolve to your box's IP address (%s) in public DNS but it currently resolves
to %s. It may take several hours for public DNS to update after a change. This problem may result from other
issues listed above."""
% (my_ips, ip + ((" / " + ipv6) if ipv6 is not None else "")))
# Check reverse DNS matches the PRIMARY_HOSTNAME. Note that it might not be
# a DNS zone if it is a subdomain of another domain we have a zone for.
existing_rdns_v4 = query_dns(dns.reversename.from_address(env['PUBLIC_IP']), "PTR")
existing_rdns_v6 = query_dns(dns.reversename.from_address(env['PUBLIC_IPV6']), "PTR") if env.get("PUBLIC_IPV6") else None
if existing_rdns_v4 == domain and existing_rdns_v6 in (None, domain):
output.print_ok("Reverse DNS is set correctly at ISP. [%s ↦ %s]" % (my_ips, env['PRIMARY_HOSTNAME']))
elif existing_rdns_v4 == existing_rdns_v6 or existing_rdns_v6 is None:
output.print_error("""Your box's reverse DNS is currently %s, but it should be %s. Your ISP or cloud provider will have instructions
on setting up reverse DNS for your box.""" % (existing_rdns_v4, domain) )
else:
output.print_error("""Your box's reverse DNS is currently %s (IPv4) and %s (IPv6), but it should be %s. Your ISP or cloud provider will have instructions
on setting up reverse DNS for your box.""" % (existing_rdns_v4, existing_rdns_v6, domain) )
# Check the TLSA record.
tlsa_qname = "_25._tcp." + domain
tlsa25 = query_dns(tlsa_qname, "TLSA", nxdomain=None)
tlsa25_expected = build_tlsa_record(env)
if tlsa25 == tlsa25_expected:
output.print_ok("""The DANE TLSA record for incoming mail is correct (%s).""" % tlsa_qname,)
elif tlsa25 is None:
if has_dnssec:
# Omit a warning about it not being set if DNSSEC isn't enabled,
# since TLSA shouldn't be used without DNSSEC.
output.print_warning("""The DANE TLSA record for incoming mail is not set. This is optional.""")
else:
output.print_error("""The DANE TLSA record for incoming mail (%s) is not correct. It is '%s' but it should be '%s'.
It may take several hours for public DNS to update after a change."""
% (tlsa_qname, tlsa25, tlsa25_expected))
# Check that the hostmaster@ email address exists.
check_alias_exists("Hostmaster contact address", "hostmaster@" + domain, env, output)
def check_alias_exists(alias_name, alias, env, output):
mail_aliases = dict([(address, receivers) for address, receivers, *_ in get_mail_aliases(env)])
if alias in mail_aliases:
if mail_aliases[alias]:
output.print_ok("%s exists as a mail alias. [%s ↦ %s]" % (alias_name, alias, mail_aliases[alias]))
else:
output.print_error("""You must set the destination of the mail alias for %s to direct email to you or another administrator.""" % alias)
else:
output.print_error("""You must add a mail alias for %s which directs email to you or another administrator.""" % alias)
def check_dns_zone(domain, env, output, dns_zonefiles):
# If a DS record is set at the registrar, check DNSSEC first because it will affect the NS query.
# If it is not set, we suggest it last.
if query_dns(domain, "DS", nxdomain=None) is not None:
check_dnssec(domain, env, output, dns_zonefiles)
# We provide a DNS zone for the domain. It should have NS records set up
# at the domain name's registrar pointing to this box. The secondary DNS
# server may be customized.
# (I'm not sure whether this necessarily tests the TLD's configuration,
# as it should, or if one successful NS line at the TLD will result in
# this query being answered by the box, which would mean the test is only
# half working.)
custom_dns_records = list(get_custom_dns_config(env)) # generator => list so we can reuse it
correct_ip = get_custom_dns_record(custom_dns_records, domain, "A") or env['PUBLIC_IP']
custom_secondary_ns = get_secondary_dns(custom_dns_records, mode="NS")
secondary_ns = custom_secondary_ns or ["ns2." + env['PRIMARY_HOSTNAME']]
existing_ns = query_dns(domain, "NS")
correct_ns = "; ".join(sorted(["ns1." + env['PRIMARY_HOSTNAME']] + secondary_ns))
ip = query_dns(domain, "A")
probably_external_dns = False
if existing_ns.lower() == correct_ns.lower():
output.print_ok("Nameservers are set correctly at registrar. [%s]" % correct_ns)
elif ip == correct_ip:
# The domain resolves correctly, so maybe the user is using External DNS.
output.print_warning("""The nameservers set on this domain at your domain name registrar should be %s. They are currently %s.
If you are using External DNS, this may be OK."""
% (correct_ns, existing_ns) )
probably_external_dns = True
else:
output.print_error("""The nameservers set on this domain are incorrect. They are currently %s. Use your domain name registrar's
control panel to set the nameservers to %s."""
% (existing_ns, correct_ns) )
# Check that each custom secondary nameserver resolves the IP address.
if custom_secondary_ns and not probably_external_dns:
for ns in custom_secondary_ns:
# We must first resolve the nameserver to an IP address so we can query it.
ns_ip = query_dns(ns, "A")
if not ns_ip:
output.print_error("Secondary nameserver %s is not valid (it doesn't resolve to an IP address)." % ns)
continue
# Now query it to see what it says about this domain.
ip = query_dns(domain, "A", at=ns_ip, nxdomain=None)
if ip == correct_ip:
output.print_ok("Secondary nameserver %s resolved the domain correctly." % ns)
elif ip is None:
output.print_error("Secondary nameserver %s is not configured to resolve this domain." % ns)
else:
output.print_error("Secondary nameserver %s is not configured correctly. (It resolved this domain as %s. It should be %s.)" % (ns, ip, correct_ip))
def check_dns_zone_suggestions(domain, env, output, dns_zonefiles, domains_with_a_records):
# Warn if a custom DNS record is preventing this or the automatic www redirect from
# being served.
if domain in domains_with_a_records:
output.print_warning("""Web has been disabled for this domain because you have set a custom DNS record.""")
if "www." + domain in domains_with_a_records:
output.print_warning("""A redirect from 'www.%s' has been disabled for this domain because you have set a custom DNS record on the www subdomain.""" % domain)
# Since DNSSEC is optional, if a DS record is NOT set at the registrar suggest it.
# (If it was set, we did the check earlier.)
if query_dns(domain, "DS", nxdomain=None) is None:
check_dnssec(domain, env, output, dns_zonefiles)
def check_dnssec(domain, env, output, dns_zonefiles, is_checking_primary=False):
# See if the domain has a DS record set at the registrar. The DS record may have
# several forms. We have to be prepared to check for any valid record. We've
# pre-generated all of the valid digests --- read them in.
ds_file = '/etc/nsd/zones/' + dns_zonefiles[domain] + '.ds'
if not os.path.exists(ds_file): return # Domain is in our database but DNS has not yet been updated.
ds_correct = open(ds_file).read().strip().split("\n")
digests = { }
for rr_ds in ds_correct:
ds_keytag, ds_alg, ds_digalg, ds_digest = rr_ds.split("\t")[4].split(" ")
digests[ds_digalg] = ds_digest
# Some registrars may want the public key so they can compute the digest. The DS
# record that we suggest using is for the KSK (and that's how the DS records were generated).
alg_name_map = { '7': 'RSASHA1-NSEC3-SHA1', '8': 'RSASHA256' }
dnssec_keys = load_env_vars_from_file(os.path.join(env['STORAGE_ROOT'], 'dns/dnssec/%s.conf' % alg_name_map[ds_alg]))
dnsssec_pubkey = open(os.path.join(env['STORAGE_ROOT'], 'dns/dnssec/' + dnssec_keys['KSK'] + '.key')).read().split("\t")[3].split(" ")[3]
# Query public DNS for the DS record at the registrar.
ds = query_dns(domain, "DS", nxdomain=None)
ds_looks_valid = ds and len(ds.split(" ")) == 4
if ds_looks_valid: ds = ds.split(" ")
if ds_looks_valid and ds[0] == ds_keytag and ds[1] == ds_alg and ds[3] == digests.get(ds[2]):
if is_checking_primary: return
output.print_ok("DNSSEC 'DS' record is set correctly at registrar.")
else:
if ds == None:
if is_checking_primary: return
output.print_warning("""This domain's DNSSEC DS record is not set. The DS record is optional. The DS record activates DNSSEC.
To set a DS record, you must follow the instructions provided by your domain name registrar and provide to them this information:""")
else:
if is_checking_primary:
output.print_error("""The DNSSEC 'DS' record for %s is incorrect. See further details below.""" % domain)
return
output.print_error("""This domain's DNSSEC DS record is incorrect. The chain of trust is broken between the public DNS system
and this machine's DNS server. It may take several hours for public DNS to update after a change. If you did not recently
make a change, you must resolve this immediately by following the instructions provided by your domain name registrar and
provide to them this information:""")
output.print_line("")
output.print_line("Key Tag: " + ds_keytag + ("" if not ds_looks_valid or ds[0] == ds_keytag else " (Got '%s')" % ds[0]))
output.print_line("Key Flags: KSK")
output.print_line(
("Algorithm: %s / %s" % (ds_alg, alg_name_map[ds_alg]))
+ ("" if not ds_looks_valid or ds[1] == ds_alg else " (Got '%s')" % ds[1]))
# see http://www.iana.org/assignments/dns-sec-alg-numbers/dns-sec-alg-numbers.xhtml
output.print_line("Digest Type: 2 / SHA-256")
# http://www.ietf.org/assignments/ds-rr-types/ds-rr-types.xml
output.print_line("Digest: " + digests['2'])
if ds_looks_valid and ds[3] != digests.get(ds[2]):
output.print_line("(Got digest type %s and digest %s which do not match.)" % (ds[2], ds[3]))
output.print_line("Public Key: ")
output.print_line(dnsssec_pubkey, monospace=True)
output.print_line("")
output.print_line("Bulk/Record Format:")
output.print_line("" + ds_correct[0])
output.print_line("")
def check_mail_domain(domain, env, output):
# Check the MX record.
recommended_mx = "10 " + env['PRIMARY_HOSTNAME']
mx = query_dns(domain, "MX", nxdomain=None)
if mx is None:
mxhost = None
else:
# query_dns returns a semicolon-delimited list
# of priority-host pairs.
mxhost = mx.split('; ')[0].split(' ')[1]
if mxhost == None:
# A missing MX record is okay on the primary hostname because
# the primary hostname's A record (the MX fallback) is... itself,
# which is what we want the MX to be.
if domain == env['PRIMARY_HOSTNAME']:
output.print_ok("Domain's email is directed to this domain. [%s has no MX record, which is ok]" % (domain,))
# And a missing MX record is okay on other domains if the A record
# matches the A record of the PRIMARY_HOSTNAME. Actually this will
# probably confuse DANE TLSA, but we'll let that slide for now.
else:
domain_a = query_dns(domain, "A", nxdomain=None)
primary_a = query_dns(env['PRIMARY_HOSTNAME'], "A", nxdomain=None)
if domain_a != None and domain_a == primary_a:
output.print_ok("Domain's email is directed to this domain. [%s has no MX record but its A record is OK]" % (domain,))
else:
output.print_error("""This domain's DNS MX record is not set. It should be '%s'. Mail will not
be delivered to this box. It may take several hours for public DNS to update after a
change. This problem may result from other issues listed here.""" % (recommended_mx,))
elif mxhost == env['PRIMARY_HOSTNAME']:
good_news = "Domain's email is directed to this domain. [%s ↦ %s]" % (domain, mx)
if mx != recommended_mx:
good_news += " This configuration is non-standard. The recommended configuration is '%s'." % (recommended_mx,)
output.print_ok(good_news)
else:
output.print_error("""This domain's DNS MX record is incorrect. It is currently set to '%s' but should be '%s'. Mail will not
be delivered to this box. It may take several hours for public DNS to update after a change. This problem may result from
other issues listed here.""" % (mx, recommended_mx))
# Check that the postmaster@ email address exists. Not required if the domain has a
# catch-all address or domain alias.
if "@" + domain not in [address for address, *_ in get_mail_aliases(env)]:
check_alias_exists("Postmaster contact address", "postmaster@" + domain, env, output)
# Stop if the domain is listed in the Spamhaus Domain Block List.
# The user might have chosen a domain that was previously in use by a spammer
# and will not be able to reliably send mail.
dbl = query_dns(domain+'.dbl.spamhaus.org', "A", nxdomain=None)
if dbl is None:
output.print_ok("Domain is not blacklisted by dbl.spamhaus.org.")
else:
output.print_error("""This domain is listed in the Spamhaus Domain Block List (code %s),
which may prevent recipients from receiving your mail.
See http://www.spamhaus.org/dbl/ and http://www.spamhaus.org/query/domain/%s.""" % (dbl, domain))
def check_web_domain(domain, rounded_time, ssl_certificates, env, output):
# See if the domain's A record resolves to our PUBLIC_IP. This is already checked
# for PRIMARY_HOSTNAME, for which it is required for mail specifically. For it and
# other domains, it is required to access its website.
if domain != env['PRIMARY_HOSTNAME']:
ok_values = []
for (rtype, expected) in (("A", env['PUBLIC_IP']), ("AAAA", env.get('PUBLIC_IPV6'))):
if not expected: continue # IPv6 is not configured
value = query_dns(domain, rtype)
if value == expected:
ok_values.append(value)
else:
output.print_error("""This domain should resolve to your box's IP address (%s %s) if you would like the box to serve
webmail or a website on this domain. The domain currently resolves to %s in public DNS. It may take several hours for
public DNS to update after a change. This problem may result from other issues listed here.""" % (rtype, expected, value))
return
# If both A and AAAA are correct...
output.print_ok("Domain resolves to this box's IP address. [%s ↦ %s]" % (domain, '; '.join(ok_values)))
# We need a TLS certificate for PRIMARY_HOSTNAME because that's where the
# user will log in with IMAP or webmail. Any other domain we serve a
# website for also needs a signed certificate.
check_ssl_cert(domain, rounded_time, ssl_certificates, env, output)
def query_dns(qname, rtype, nxdomain='[Not Set]', at=None):
# Make the qname absolute by appending a period. Without this, dns.resolver.query
# will fall back a failed lookup to a second query with this machine's hostname
# appended. This has been causing some false-positive Spamhaus reports. The
# reverse DNS lookup will pass a dns.name.Name instance which is already
# absolute so we should not modify that.
if isinstance(qname, str):
qname += "."
# Use the default nameservers (as defined by the system, which is our locally
# running bind server), or if the 'at' argument is specified, use that host
# as the nameserver.
resolver = dns.resolver.get_default_resolver()
if at:
resolver = dns.resolver.Resolver()
resolver.nameservers = [at]
# Set a timeout so that a non-responsive server doesn't hold us back.
resolver.timeout = 5
# Do the query.
try:
response = resolver.query(qname, rtype)
except (dns.resolver.NoNameservers, dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):
# Host did not have an answer for this query; not sure what the
# difference is between the two exceptions.
return nxdomain
except dns.exception.Timeout:
return "[timeout]"
# There may be multiple answers; concatenate the response. Remove trailing
# periods from responses since that's how qnames are encoded in DNS but is
# confusing for us. The order of the answers doesn't matter, so sort so we
# can compare to a well known order.
return "; ".join(sorted(str(r).rstrip('.') for r in response))
def check_ssl_cert(domain, rounded_time, ssl_certificates, env, output):
# Check that TLS certificate is signed.
# Skip the check if the A record is not pointed here.
if query_dns(domain, "A", None) not in (env['PUBLIC_IP'], None): return
# Where is the certificate file stored?
tls_cert = get_domain_ssl_files(domain, ssl_certificates, env, allow_missing_cert=True)
if tls_cert is None:
output.print_warning("""No TLS (SSL) certificate is installed for this domain. Visitors to a website on
this domain will get a security warning. If you are not serving a website on this domain, you do
not need to take any action. Use the TLS Certificates page in the control panel to install a
TLS certificate.""")
return
# Check that the certificate is good.
cert_status, cert_status_details = check_certificate(domain, tls_cert["certificate"], tls_cert["private-key"], rounded_time=rounded_time)
if cert_status == "OK":
# The certificate is ok. The details has expiry info.
output.print_ok("TLS (SSL) certificate is signed & valid. " + cert_status_details)
elif cert_status == "SELF-SIGNED":
# Offer instructions for purchasing a signed certificate.
if domain == env['PRIMARY_HOSTNAME']:
output.print_error("""The TLS (SSL) certificate for this domain is currently self-signed. You will get a security
warning when you check or send email and when visiting this domain in a web browser (for webmail or
static site hosting).""")
else:
output.print_error("""The TLS (SSL) certificate for this domain is self-signed.""")
else:
output.print_error("The TLS (SSL) certificate has a problem: " + cert_status)
if cert_status_details:
output.print_line("")
output.print_line(cert_status_details)
output.print_line("")
_apt_updates = None
def list_apt_updates(apt_update=True):
# See if we have this information cached recently.
# Keep the information for 8 hours.
global _apt_updates
if _apt_updates is not None and _apt_updates[0] > datetime.datetime.now() - datetime.timedelta(hours=8):
return _apt_updates[1]
# Run apt-get update to refresh package list. This should be running daily
# anyway, so on the status checks page don't do this because it is slow.
if apt_update:
shell("check_call", ["/usr/bin/apt-get", "-qq", "update"])
# Run apt-get upgrade in simulate mode to get a list of what
# it would do.
simulated_install = shell("check_output", ["/usr/bin/apt-get", "-qq", "-s", "upgrade"])
pkgs = []
for line in simulated_install.split('\n'):
if line.strip() == "":
continue
if re.match(r'^Conf .*', line):
# remove these lines, not informative
continue
m = re.match(r'^Inst (.*) \[(.*)\] \((\S*)', line)
if m:
pkgs.append({ "package": m.group(1), "version": m.group(3), "current_version": m.group(2) })
else:
pkgs.append({ "package": "[" + line + "]", "version": "", "current_version": "" })
# Cache for future requests.
_apt_updates = (datetime.datetime.now(), pkgs)
return pkgs
def what_version_is_this(env):
# This function runs `git describe --abbrev=0` on the Mail-in-a-Box installation directory.
# Git may not be installed and Mail-in-a-Box may not have been cloned from github,
# so this function may raise all sorts of exceptions.
miab_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
tag = shell("check_output", ["/usr/bin/git", "describe", "--abbrev=0"], env={"GIT_DIR": os.path.join(miab_dir, '.git')}).strip()
return tag
def get_latest_miab_version():
# This pings https://mailinabox.email/setup.sh and extracts the tag named in
# the script to determine the current product version.
import urllib.request
return re.search(b'TAG=(.*)', urllib.request.urlopen("https://mailinabox.email/setup.sh?ping=1").read()).group(1).decode("utf8")
def check_miab_version(env, output):
config = load_settings(env)
if config.get("privacy", True):
output.print_warning("Mail-in-a-Box version check disabled by privacy setting.")
else:
try:
this_ver = what_version_is_this(env)
except:
this_ver = "Unknown"
latest_ver = get_latest_miab_version()
if this_ver == latest_ver:
output.print_ok("Mail-in-a-Box is up to date. You are running version %s." % this_ver)
else:
output.print_error("A new version of Mail-in-a-Box is available. You are running version %s. The latest version is %s. For upgrade instructions, see https://mailinabox.email. "
% (this_ver, latest_ver))
def run_and_output_changes(env, pool):
import json
from difflib import SequenceMatcher
out = ConsoleOutput()
# Run status checks.
cur = BufferedOutput()
run_checks(True, env, cur, pool)
# Load previously saved status checks.
cache_fn = "/var/cache/mailinabox/status_checks.json"
if os.path.exists(cache_fn):
prev = json.load(open(cache_fn))
# Group the serial output into categories by the headings.
def group_by_heading(lines):
from collections import OrderedDict
ret = OrderedDict()
k = []
ret["No Category"] = k
for line_type, line_args, line_kwargs in lines:
if line_type == "add_heading":
k = []
ret[line_args[0]] = k
else:
k.append((line_type, line_args, line_kwargs))
return ret
prev_status = group_by_heading(prev)
cur_status = group_by_heading(cur.buf)
# Compare the previous to the current status checks
# category by category.
for category, cur_lines in cur_status.items():
if category not in prev_status:
out.add_heading(category + " -- Added")
BufferedOutput(with_lines=cur_lines).playback(out)
else:
# Actual comparison starts here...
prev_lines = prev_status[category]
def stringify(lines):
return [json.dumps(line) for line in lines]
diff = SequenceMatcher(None, stringify(prev_lines), stringify(cur_lines)).get_opcodes()
for op, i1, i2, j1, j2 in diff:
if op == "replace":
out.add_heading(category + " -- Previously:")
elif op == "delete":
out.add_heading(category + " -- Removed")
if op in ("replace", "delete"):
BufferedOutput(with_lines=prev_lines[i1:i2]).playback(out)
if op == "replace":
out.add_heading(category + " -- Currently:")
elif op == "insert":
out.add_heading(category + " -- Added")
if op in ("replace", "insert"):
BufferedOutput(with_lines=cur_lines[j1:j2]).playback(out)
for category, prev_lines in prev_status.items():
if category not in cur_status:
out.add_heading(category)
out.print_warning("This section was removed.")
# Store the current status checks output for next time.
os.makedirs(os.path.dirname(cache_fn), exist_ok=True)
with open(cache_fn, "w") as f:
json.dump(cur.buf, f, indent=True)
class FileOutput:
def __init__(self, buf, width):
self.buf = buf
self.width = width
def add_heading(self, heading):
print(file=self.buf)
print(heading, file=self.buf)
print("=" * len(heading), file=self.buf)
def print_ok(self, message):
self.print_block(message, first_line="✓ ")
def print_error(self, message):
self.print_block(message, first_line="✖ ")
def print_warning(self, message):
self.print_block(message, first_line="? ")
def print_block(self, message, first_line=" "):
print(first_line, end='', file=self.buf)
message = re.sub("\n\s*", " ", message)
words = re.split("(\s+)", message)
linelen = 0
for w in words:
if self.width and (linelen + len(w) > self.width-1-len(first_line)):
print(file=self.buf)
print(" ", end="", file=self.buf)
linelen = 0
if linelen == 0 and w.strip() == "": continue
print(w, end="", file=self.buf)
linelen += len(w)
print(file=self.buf)
def print_line(self, message, monospace=False):
for line in message.split("\n"):
self.print_block(line)
class ConsoleOutput(FileOutput):
def __init__(self):
self.buf = sys.stdout
# Do nice line-wrapping according to the size of the terminal.
# The 'stty' program queries standard input for terminal information.
if sys.stdin.isatty():
try:
self.width = int(shell('check_output', ['stty', 'size']).split()[1])
except:
self.width = 76
else:
# However if standard input is not a terminal, we would get
# "stty: standard input: Inappropriate ioctl for device". So
# we test with sys.stdin.isatty first, and if it is not a
# terminal don't do any line wrapping. When this script is
# run from cron, or if stdin has been redirected, this happens.
self.width = None
class BufferedOutput:
# Record all of the instance method calls so we can play them back later.
def __init__(self, with_lines=None):
self.buf = [] if not with_lines else with_lines
def __getattr__(self, attr):
if attr not in ("add_heading", "print_ok", "print_error", "print_warning", "print_block", "print_line"):
raise AttributeError
# Return a function that just records the call & arguments to our buffer.
def w(*args, **kwargs):
self.buf.append((attr, args, kwargs))
return w
def playback(self, output):
for attr, args, kwargs in self.buf:
getattr(output, attr)(*args, **kwargs)
if __name__ == "__main__":
from utils import load_environment
env = load_environment()
pool = multiprocessing.pool.Pool(processes=10)
if len(sys.argv) == 1:
run_checks(False, env, ConsoleOutput(), pool)
elif sys.argv[1] == "--show-changes":
run_and_output_changes(env, pool)
elif sys.argv[1] == "--check-primary-hostname":
# See if the primary hostname appears resolvable and has a signed certificate.
domain = env['PRIMARY_HOSTNAME']
if query_dns(domain, "A") != env['PUBLIC_IP']:
sys.exit(1)
ssl_certificates = get_ssl_certificates(env)
tls_cert = get_domain_ssl_files(domain, ssl_certificates, env)
if not os.path.exists(tls_cert["certificate"]):
sys.exit(1)
cert_status, cert_status_details = check_certificate(domain, tls_cert["certificate"], tls_cert["private-key"], warn_if_expiring_soon=False)
if cert_status != "OK":
sys.exit(1)
sys.exit(0)
elif sys.argv[1] == "--version":
print(what_version_is_this(env))
| nstanke/mailinabox | management/status_checks.py | Python | cc0-1.0 | 41,760 |
<?php
ini_set('error_log', dirname(__DIR__).'/log/errors.log');
include_once(__DIR__.'/../system/rabbitdaemon.class.php');
$daemon = new \framework\RabbitDaemon($queueName = 'example', $exchangeName = 'email', $routeKey = 'email');
$daemon->main($argv);
?>
| netkiller/SOA | sbin/rabbitmq.php | PHP | cc0-1.0 | 261 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace WikiRecorder.Droid
{
[Activity(Label = "LoginActivity" ,MainLauncher=false)]
public class LoginActivity : BaseActivity
{
public override BaseFragment GetFragment()
{
return new LoginFragment ();
}
}
}
| devapalanisamy/Recorder-For-Wikitionary | WikiRecorder/WikiRecorder.Droid/Source/Activities/LoginActivity.cs | C# | cc0-1.0 | 448 |
import React from "react"
import { Link, graphql } from "gatsby"
import Bio from "../components/bio"
import Layout from "../components/layout"
import SEO from "../components/seo"
import { rhythm } from "../utils/typography"
class BlogIndex extends React.Component {
render() {
const { data } = this.props
const siteTitle = data.site.siteMetadata.title
const posts = data.allMarkdownRemark.edges
return (
<Layout location={this.props.location} title={siteTitle}>
<SEO
title="All posts"
keywords={[`blog`, `gatsby`, `javascript`, `react`]}
/>
<Bio />
{posts.map(({ node }) => {
const title = node.frontmatter.title || node.fields.slug;
var desc = node.frontmatter.excerpt || node.frontmatter.description;
if (!desc || desc.length === 0)
{
desc = node.excerpt;
}
return (
<div key={node.fields.slug}>
<h3
style={{
marginBottom: rhythm(1 / 4),
}}
>
<Link style={{ boxShadow: `none` }} to={node.fields.slug}>
{title}
</Link>
</h3>
<small>{node.frontmatter.date}</small>
<p
dangerouslySetInnerHTML={{
__html: desc
}}
/>
</div>
)
})}
</Layout>
)
}
}
export default BlogIndex
export const pageQuery = graphql`
query {
site {
siteMetadata {
title
}
}
allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) {
edges {
node {
excerpt
fields {
slug
}
frontmatter {
date(formatString: "MMMM DD, YYYY")
title
description
excerpt
}
}
}
}
}
`
| yetanotherchris/yetanotherchris.github.io | src/pages/archive.js | JavaScript | cc0-1.0 | 1,963 |
package patterns.behavioral.command;
// General interface for all the commands
public abstract class Command {
public abstract void execute();
}
| SigmaOne/DesignPatterns | src/main/java/patterns/behavioral/command/Command.java | Java | cc0-1.0 | 150 |
package org.cqframework.cql.tools.parsetree;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.ParserRuleContext;
import org.cqframework.cql.gen.cqlLexer;
import org.cqframework.cql.gen.cqlParser;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* A simple wrapper around the ANTLR4 testrig.
*/
public class Main {
public static void main(String[] args) throws IOException {
String inputFile = null;
if (args.length > 0) {
inputFile = args[0];
}
InputStream is = System.in;
if (inputFile != null) {
is = new FileInputStream(inputFile);
}
ANTLRInputStream input = new ANTLRInputStream(is);
cqlLexer lexer = new cqlLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
tokens.fill();
cqlParser parser = new cqlParser(tokens);
parser.setBuildParseTree(true);
ParserRuleContext tree = parser.library();
tree.inspect(parser);
}
}
| MeasureAuthoringTool/clinical_quality_language | Src/java/tools/cql-parsetree/src/main/java/org/cqframework/cql/tools/parsetree/Main.java | Java | cc0-1.0 | 1,105 |
<?php
declare(strict_types=1);
namespace Tests\Feature;
use App\Models\Note;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class SearchControllerTest extends TestCase
{
use RefreshDatabase;
/** @test */
public function searchPageReturnsResult(): void
{
Note::factory()->create([
'note' => 'I love [duckduckgo.com](https://duckduckgo.com)',
]);
$response = $this->get('/search?terms=love');
$response->assertSee('duckduckgo.com');
}
}
| jonnybarnes/jonnybarnes.uk | tests/Feature/SearchControllerTest.php | PHP | cc0-1.0 | 528 |
(function($) {
$.Redactor.opts.langs['uk'] = {
html: 'Код',
video: 'Відео',
image: 'Зображення',
table: 'Таблиця',
link: 'Посилання',
link_insert: 'Вставити посилання ...',
link_edit: 'Edit link',
unlink: 'Видалити посилання',
formatting: 'Стилі',
paragraph: 'Звичайний текст',
quote: 'Цитата',
code: 'Код',
header1: 'Заголовок 1',
header2: 'Заголовок 2',
header3: 'Заголовок 3',
header4: 'Заголовок 4',
header5: 'Заголовок 5',
bold: 'Жирний',
italic: 'Похилий',
fontcolor: 'Колір тексту',
backcolor: 'Заливка тексту',
unorderedlist: 'Звичайний список',
orderedlist: 'Нумерований список',
outdent: 'Зменшити відступ',
indent: 'Збільшити відступ',
cancel: 'Скасувати',
insert: 'Вставити',
save: 'Зберегти',
_delete: 'Видалити',
insert_table: 'Вставити таблицю',
insert_row_above: 'Додати рядок зверху',
insert_row_below: 'Додати рядок знизу',
insert_column_left: 'Додати стовпець ліворуч',
insert_column_right: 'Додати стовпець праворуч',
delete_column: 'Видалити стовпець',
delete_row: 'Видалити рядок',
delete_table: 'Видалити таблицю',
rows: 'Рядки',
columns: 'Стовпці',
add_head: 'Додати заголовок',
delete_head: 'Видалити заголовок',
title: 'Підказка',
image_view: 'Завантажити зображення',
image_position: 'Обтікання текстом',
none: 'ні',
left: 'ліворуч',
right: 'праворуч',
image_web_link: 'Посилання на зображення',
text: 'Текст',
mailto: 'Ел. пошта',
web: 'URL',
video_html_code: 'Код відео ролика',
file: 'Файл',
upload: 'Завантажити',
download: 'Завантажити',
choose: 'Вибрати',
or_choose: 'Або виберіть',
drop_file_here: 'Перетягніть файл сюди',
align_left: 'По лівому краю',
align_center: 'По центру',
align_right: 'По правому краю',
align_justify: 'Вирівняти текст по ширині',
horizontalrule: 'Горизонтальная лінійка',
fullscreen: 'На весь екран',
deleted: 'Закреслений',
anchor: 'Anchor',
link_new_tab: 'Open link in new tab',
underline: 'Underline',
alignment: 'Alignment',
filename: 'Name (optional)',
edit: 'Edit',
center: 'Center'
};
})(jQuery);
| andersonbglaeser/f5digital | f5admin/web-files/plugins/jquery-redactor/lang/uk.js | JavaScript | cc0-1.0 | 3,271 |
/*
* (C) Copyright 2015 Netcentric AG.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package biz.netcentric.cq.tools.actool.validators;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.jcr.RepositoryException;
import javax.jcr.security.AccessControlManager;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.day.cq.security.util.CqActions;
public class Validators {
private static final Logger LOG = LoggerFactory.getLogger(Validators.class);
public static boolean isValidNodePath(final String path) {
if (StringUtils.isBlank(path)) {
return true; // repository level permissions are created with 'left-out' path property
}
if (!path.startsWith("/")) {
return false;
}
return true;
}
/**
* Validates in the same way as <a href="https://github.com/apache/jackrabbit-oak/blob/7999b5cbce87295b502ea4d1622e729f5b96701d/oak-core/src/main/java/org/apache/jackrabbit/oak/security/user/UserManagerImpl.java#L421">Oak's UserManagerImpl</a>.
* @param id the authorizable id to validate
* @return {@code true} in case the given id is a valid authorizable id, otherwise {@code false}
*/
public static boolean isValidAuthorizableId(final String id) {
if (StringUtils.isBlank(id)) {
return false;
}
return true;
}
public static boolean isValidRegex(String expression) {
if (StringUtils.isBlank(expression)) {
return true;
}
boolean isValid = true;
if (expression.startsWith("*")) {
expression = expression.replaceFirst("\\*", "\\\\*");
}
try {
Pattern.compile(expression);
} catch (PatternSyntaxException e) {
LOG.error("Error while validating rep glob: {} ", expression, e);
isValid = false;
}
return isValid;
}
public static boolean isValidAction(String action) {
List<String> validActions = Arrays.asList(CqActions.ACTIONS);
if (action == null) {
return false;
}
if (!validActions.contains(action)) {
return false;
}
return true;
}
public static boolean isValidJcrPrivilege(String privilege, AccessControlManager aclManager) {
if (privilege == null) {
return false;
}
try {
aclManager.privilegeFromName(privilege);
} catch (RepositoryException e) {
return false;
}
return true;
}
public static boolean isValidPermission(String permission) {
if (permission == null) {
return false;
}
if (StringUtils.equals("allow", permission)
|| StringUtils.equals("deny", permission)) {
return true;
}
return false;
}
}
| mtstv/accesscontroltool | accesscontroltool-bundle/src/main/java/biz/netcentric/cq/tools/actool/validators/Validators.java | Java | epl-1.0 | 3,216 |
/*******************************************************************************
* Copyright (c) 1998, 2013 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import org.eclipse.persistence.config.CacheIsolationType;
import static org.eclipse.persistence.config.CacheIsolationType.SHARED;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static org.eclipse.persistence.annotations.CacheType.SOFT_WEAK;
import static org.eclipse.persistence.annotations.CacheCoordinationType.SEND_OBJECT_CHANGES;
/**
* The Cache annotation is used to configure the EclipseLink object cache.
* By default EclipseLink uses a shared object cache to cache all objects.
* The caching type and options can be configured on a per class basis to allow
* optimal caching.
* <p>
* This includes options for configuring the type of caching,
* setting the size, disabling the shared cache, expiring objects, refreshing,
* and cache coordination (clustering).
* <p>
* A Cache annotation may be defined on an Entity or MappedSuperclass. In the
* case of inheritance, a Cache annotation should only be defined on the root
* of the inheritance hierarchy.
*
* @see org.eclipse.persistence.annotations.CacheType
* @see org.eclipse.persistence.annotations.CacheCoordinationType
*
* @see org.eclipse.persistence.descriptors.ClassDescriptor
* @see org.eclipse.persistence.descriptors.invalidation.CacheInvalidationPolicy
*
* @author Guy Pelletier
* @since Oracle TopLink 11.1.1.0.0
*/
@Target({TYPE})
@Retention(RUNTIME)
public @interface Cache {
/**
* (Optional) The type of cache to use.
* The default is SOFT_WEAK.
*/
CacheType type() default SOFT_WEAK;
/**
* (Optional) The size of cache to use.
* The default is 100.
*/
int size() default 100;
/**
* (Optional) Cached instances in the shared cache,
* or only a per EntityManager isolated cache.
* The default is shared.
* @deprecated As of Eclipselink 2.2. See the attribute 'isolation'
*/
@Deprecated
boolean shared() default true;
/**
* (Optional) Controls the level of caching this Entity will use.
* The default is CacheIsolationType.SHARED which has EclipseLink
* Caching all Entities in the Shared Cache.
* @see org.eclipse.persistence.config.CacheIsolationType
*/
CacheIsolationType isolation() default SHARED;
/**
* (Optional) Expire cached instance after a fix period of time (ms).
* Queries executed against the cache after this will be forced back
* to the database for a refreshed copy.
* By default there is no expiry.
*/
int expiry() default -1; // minus one is no expiry.
/**
* (Optional) Expire cached instance a specific time of day. Queries
* executed against the cache after this will be forced back to the
* database for a refreshed copy.
*/
TimeOfDay expiryTimeOfDay() default @TimeOfDay(specified=false);
/**
* (Optional) Force all queries that go to the database to always
* refresh the cache.
* Default is false.
* Consider disabling the shared cache instead of forcing refreshing.
*/
boolean alwaysRefresh() default false;
/**
* (Optional) For all queries that go to the database, refresh the cache
* only if the data received from the database by a query is newer than
* the data in the cache (as determined by the optimistic locking field).
* This is normally used in conjunction with alwaysRefresh, and by itself
* it only affect explicit refresh calls or queries.
* Default is false.
*/
boolean refreshOnlyIfNewer() default false;
/**
* (Optional) Setting to true will force all queries to bypass the
* cache for hits but still resolve against the cache for identity.
* This forces all queries to hit the database.
*/
boolean disableHits() default false;
/**
* (Optional) The cache coordination mode.
* Note that cache coordination must also be configured for the persistence unit/session.
*/
CacheCoordinationType coordinationType() default SEND_OBJECT_CHANGES;
/**
* (Optional) The database change notification mode.
* Note that database event listener must also be configured for the persistence unit/session.
*/
DatabaseChangeNotificationType databaseChangeNotificationType() default DatabaseChangeNotificationType.INVALIDATE;
}
| bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs | foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/annotations/Cache.java | Java | epl-1.0 | 5,380 |
/**
* Java Beans.
*
* @author Archimedes Trajano
*/
package net.trajano.ms.vertx.beans;
| trajano/app-ms | ms-common-impl/src/main/java/net/trajano/ms/vertx/beans/package-info.java | Java | epl-1.0 | 92 |
package daanielz.tools.commands;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import daanielz.tools.Utils;
public class WorkbenchCmd implements CommandExecutor {
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if(sender instanceof Player){
Player p = (Player) sender;
if(cmd.getName().equalsIgnoreCase("workbench")){
if(!sender.hasPermission("vetesda.workbench")){
sender.sendMessage(Utils.getColor("&8» &7Nie masz uprawnien."));
} else{
p.openWorkbench(null, true);
}
} else if(cmd.getName().equalsIgnoreCase("enchanttable")){
if(!sender.hasPermission("vetesda.enchanttable")){
sender.sendMessage(Utils.getColor("&8» &7Nie masz uprawnien."));
} else{
p.openEnchanting(null, true);
}
}
} return true;
}
} | DaanielZ/DToolsZ | DToolsZ/src/daanielz/tools/commands/WorkbenchCmd.java | Java | epl-1.0 | 978 |
/*
* Copyright 2012 PRODYNA AG
*
* Licensed under the Eclipse Public License (EPL), Version 1.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.opensource.org/licenses/eclipse-1.0.php or
* http://www.nabucco.org/License.html
*
* 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.nabucco.framework.base.impl.service.timer;
import java.io.Serializable;
import org.nabucco.framework.base.facade.datatype.logger.NabuccoLogger;
import org.nabucco.framework.base.facade.datatype.logger.NabuccoLoggingFactory;
/**
* Timer
*
* @author Nicolas Moser, PRODYNA AG
*/
public abstract class Timer implements Serializable {
private static final long serialVersionUID = 1L;
private final String name;
private final TimerPriority priority;
private final NabuccoLogger logger = NabuccoLoggingFactory.getInstance().getLogger(this.getClass());
/**
* Creates a new {@link Timer} instance.
*
* @param name
* the timer name
* @param priority
* the timer priority
*/
public Timer(String name, TimerPriority priority) {
if (name == null) {
throw new IllegalArgumentException("Cannot create Timer for name [null].");
}
if (priority == null) {
throw new IllegalArgumentException("Cannot create Timer for priority [null].");
}
this.name = name;
this.priority = priority;
}
/**
* Getter for the logger.
*
* @return Returns the logger.
*/
protected NabuccoLogger getLogger() {
return this.logger;
}
/**
* Getter for the name.
*
* @return Returns the name.
*/
public final String getName() {
return this.name;
}
/**
* Getter for the priority.
*
* @return Returns the priority.
*/
public final TimerPriority getPriority() {
return this.priority;
}
/**
* Method that executes the appropriate timer logic.
*
* @throws TimerExecutionException
* when an exception during timer execution occurs
*/
public abstract void execute() throws TimerExecutionException;
@Override
public final int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.name == null) ? 0 : this.name.hashCode());
return result;
}
@Override
public final boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Timer other = (Timer) obj;
if (this.name == null) {
if (other.name != null) {
return false;
}
} else if (!this.name.equals(other.name)) {
return false;
}
return true;
}
@Override
public final String toString() {
StringBuilder builder = new StringBuilder();
builder.append(this.name);
builder.append(" [");
builder.append(this.getClass().getCanonicalName());
builder.append(", ");
builder.append(this.priority);
builder.append("]");
return builder.toString();
}
}
| NABUCCO/org.nabucco.framework.base | org.nabucco.framework.base.impl.service/src/main/man/org/nabucco/framework/base/impl/service/timer/Timer.java | Java | epl-1.0 | 3,676 |
// Copyright (c) 1996-2002 The Regents of the University of California. All
// Rights Reserved. Permission to use, copy, modify, and distribute this
// software and its documentation without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph appear in all copies. This software program and
// documentation are copyrighted by The Regents of the University of
// California. The software program and documentation are supplied "AS
// IS", without any accompanying services from The Regents. The Regents
// does not warrant that the operation of the program will be
// uninterrupted or error-free. The end-user understands that the program
// was developed for research purposes and is advised not to rely
// exclusively on the program for any reason. IN NO EVENT SHALL THE
// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
// PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
package org.argouml.application.api;
/** An plugin interface which identifies an ArgoUML data loader.
* <br>
* TODO: identify methods
*
* @author Thierry Lach
* @since ARGO0.11.3
*/
public interface PluggableProjectWriter extends Pluggable {
} /* End interface PluggableProjectWriter */
| argocasegeo/argocasegeo | src/org/argouml/application/api/PluggableProjectWriter.java | Java | epl-1.0 | 1,869 |
package org.junit.runners.fix.v411;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.runner.Runner;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.Suite;
import org.junit.runners.model.FrameworkField;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;
/**
* <p>
* The custom runner <code>Parameterized</code> implements parameterized tests.
* When running a parameterized test class, instances are created for the
* cross-product of the test methods and the test data elements.
* </p>
*
* For example, to test a Fibonacci function, write:
*
* <pre>
* @RunWith(Parameterized.class)
* public class FibonacciTest {
* @Parameters(name= "{index}: fib({0})={1}")
* public static Iterable<Object[]> data() {
* return Arrays.asList(new Object[][] { { 0, 0 }, { 1, 1 }, { 2, 1 },
* { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 } });
* }
*
* private int fInput;
*
* private int fExpected;
*
* public FibonacciTest(int input, int expected) {
* fInput= input;
* fExpected= expected;
* }
*
* @Test
* public void test() {
* assertEquals(fExpected, Fibonacci.compute(fInput));
* }
* }
* </pre>
*
* <p>
* Each instance of <code>FibonacciTest</code> will be constructed using the
* two-argument constructor and the data values in the
* <code>@Parameters</code> method.
*
* <p>
* In order that you can easily identify the individual tests, you may provide a
* name for the <code>@Parameters</code> annotation. This name is allowed
* to contain placeholders, which are replaced at runtime. The placeholders are
* <dl>
* <dt>{index}</dt>
* <dd>the current parameter index</dd>
* <dt>{0}</dt>
* <dd>the first parameter value</dd>
* <dt>{1}</dt>
* <dd>the second parameter value</dd>
* <dt>...</dt>
* <dd></dd>
* </dl>
* In the example given above, the <code>Parameterized</code> runner creates
* names like <code>[1: fib(3)=2]</code>. If you don't use the name parameter,
* then the current parameter index is used as name.
* </p>
*
* You can also write:
*
* <pre>
* @RunWith(Parameterized.class)
* public class FibonacciTest {
* @Parameters
* public static Iterable<Object[]> data() {
* return Arrays.asList(new Object[][] { { 0, 0 }, { 1, 1 }, { 2, 1 },
* { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 } });
* }
* @Parameter(0)
* public int fInput;
*
* @Parameter(1)
* public int fExpected;
*
* @Test
* public void test() {
* assertEquals(fExpected, Fibonacci.compute(fInput));
* }
* }
* </pre>
*
* <p>
* Each instance of <code>FibonacciTest</code> will be constructed with the default constructor
* and fields annotated by <code>@Parameter</code> will be initialized
* with the data values in the <code>@Parameters</code> method.
* </p>
*
* @since 4.0
*/
public class Parameterized extends Suite {
/**
* Annotation for a method which provides parameters to be injected into the
* test class constructor by <code>Parameterized</code>
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public static @interface Parameters {
/**
* <p>
* Optional pattern to derive the test's name from the parameters. Use
* numbers in braces to refer to the parameters or the additional data
* as follows:
* </p>
*
* <pre>
* {index} - the current parameter index
* {0} - the first parameter value
* {1} - the second parameter value
* etc...
* </pre>
* <p>
* Default value is "{index}" for compatibility with previous JUnit
* versions.
* </p>
*
* @return {@link MessageFormat} pattern string, except the index
* placeholder.
* @see MessageFormat
*/
String name() default "{index}";
}
/**
* Annotation for fields of the test class which will be initialized by the
* method annotated by <code>Parameters</code><br/>
* By using directly this annotation, the test class constructor isn't needed.<br/>
* Index range must start at 0.
* Default value is 0.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public static @interface Parameter {
/**
* Method that returns the index of the parameter in the array
* returned by the method annotated by <code>Parameters</code>.<br/>
* Index range must start at 0.
* Default value is 0.
*
* @return the index of the parameter.
*/
int value() default 0;
}
protected static final Map<Character, String> ESCAPE_SEQUENCES = new HashMap<Character, String>();
static {
ESCAPE_SEQUENCES.put('\0', "\\\\0");
ESCAPE_SEQUENCES.put('\t', "\\\\t");
ESCAPE_SEQUENCES.put('\b', "\\\\b");
ESCAPE_SEQUENCES.put('\n', "\\\\n");
ESCAPE_SEQUENCES.put('\r', "\\\\r");
ESCAPE_SEQUENCES.put('\f', "\\\\f");
}
private class TestClassRunnerForParameters extends BlockJUnit4ClassRunner {
private final Object[] fParameters;
private final String fName;
TestClassRunnerForParameters(final Class<?> type, final Object[] parameters, final String name) throws InitializationError {
super(type);
this.fParameters = parameters;
this.fName = name;
}
@Override
public Object createTest() throws Exception {
if (fieldsAreAnnotated()) {
return createTestUsingFieldInjection();
} else {
return createTestUsingConstructorInjection();
}
}
private Object createTestUsingConstructorInjection() throws Exception {
return getTestClass().getOnlyConstructor().newInstance(this.fParameters);
}
private Object createTestUsingFieldInjection() throws Exception {
List<FrameworkField> annotatedFieldsByParameter = getAnnotatedFieldsByParameter();
if (annotatedFieldsByParameter.size() != this.fParameters.length) {
throw new Exception(
"Wrong number of parameters and @Parameter fields." + " @Parameter fields counted: " + annotatedFieldsByParameter.size() + ", available parameters: " + this.fParameters.length + ".");
}
Object testClassInstance = getTestClass().getJavaClass().newInstance();
for (FrameworkField each : annotatedFieldsByParameter) {
Field field = each.getField();
Parameter annotation = field.getAnnotation(Parameter.class);
int index = annotation.value();
try {
field.set(testClassInstance, this.fParameters[index]);
} catch (IllegalArgumentException iare) {
throw new Exception(
getTestClass().getName() + ": Trying to set " + field.getName() + " with the value " + this.fParameters[index] + " that is not the right type (" + this.fParameters[index].getClass()
.getSimpleName() + " instead of " + field.getType().getSimpleName() + ").", iare);
}
}
return testClassInstance;
}
@Override
protected String getName() {
return this.fName;
}
@Override
protected String testName(final FrameworkMethod method) {
return method.getName() + getName();
}
@Override
protected void validateConstructor(final List<Throwable> errors) {
validateOnlyOneConstructor(errors);
if (fieldsAreAnnotated()) {
validateZeroArgConstructor(errors);
}
}
@Override
protected void validateFields(final List<Throwable> errors) {
super.validateFields(errors);
if (fieldsAreAnnotated()) {
List<FrameworkField> annotatedFieldsByParameter = getAnnotatedFieldsByParameter();
int[] usedIndices = new int[annotatedFieldsByParameter.size()];
for (FrameworkField each : annotatedFieldsByParameter) {
int index = each.getField().getAnnotation(Parameter.class).value();
if ((index < 0) || (index > (annotatedFieldsByParameter.size() - 1))) {
errors.add(new Exception(
"Invalid @Parameter value: " + index + ". @Parameter fields counted: " + annotatedFieldsByParameter.size() + ". Please use an index between 0 and " + (annotatedFieldsByParameter.size() - 1) + "."));
} else {
usedIndices[index]++;
}
}
for (int index = 0; index < usedIndices.length; index++) {
int numberOfUse = usedIndices[index];
if (numberOfUse == 0) {
errors.add(new Exception("@Parameter(" + index + ") is never used."));
} else if (numberOfUse > 1) {
errors.add(new Exception("@Parameter(" + index + ") is used more than once (" + numberOfUse + ")."));
}
}
}
}
@Override
protected Statement classBlock(final RunNotifier notifier) {
return childrenInvoker(notifier);
}
@Override
protected Annotation[] getRunnerAnnotations() {
return new Annotation[0];
}
}
private static final List<Runner> NO_RUNNERS = Collections.<Runner> emptyList();
private final ArrayList<Runner> runners = new ArrayList<Runner>();
/**
* Only called reflectively. Do not use programmatically.
*/
public Parameterized(final Class<?> klass) throws Throwable {
super(klass, NO_RUNNERS);
Parameters parameters = getParametersMethod().getAnnotation(Parameters.class);
createRunnersForParameters(allParameters(), parameters.name());
}
@Override
protected List<Runner> getChildren() {
return this.runners;
}
@SuppressWarnings("unchecked")
private Iterable<Object[]> allParameters() throws Throwable {
Object parameters = getParametersMethod().invokeExplosively(null);
if (parameters instanceof Iterable) {
return (Iterable<Object[]>) parameters;
} else {
throw parametersMethodReturnedWrongType();
}
}
private FrameworkMethod getParametersMethod() throws Exception {
List<FrameworkMethod> methods = getTestClass().getAnnotatedMethods(Parameters.class);
for (FrameworkMethod each : methods) {
if (each.isStatic() && each.isPublic()) {
return each;
}
}
throw new Exception("No public static parameters method on class " + getTestClass().getName());
}
private void createRunnersForParameters(final Iterable<Object[]> allParameters, final String namePattern) throws InitializationError, Exception {
try {
int i = 0;
for (Object[] parametersOfSingleTest : allParameters) {
String name = nameFor(namePattern, i, parametersOfSingleTest);
TestClassRunnerForParameters runner = new TestClassRunnerForParameters(getTestClass().getJavaClass(), parametersOfSingleTest, name);
this.runners.add(runner);
++i;
}
} catch (ClassCastException e) {
throw parametersMethodReturnedWrongType();
}
}
private String nameFor(final String namePattern, final int index, final Object[] parameters) {
String finalPattern = namePattern.replaceAll("\\{index\\}", Integer.toString(index));
String name = MessageFormat.format(finalPattern, parameters);
return "[" + sanitizeEscapeSequencesWithName(name) + "]";
}
private String sanitizeEscapeSequencesWithName(final String name) {
String result = name;
for (Map.Entry<Character, String> currentSequence : ESCAPE_SEQUENCES.entrySet()) {
result = result.replaceAll("" + currentSequence.getKey(), currentSequence.getValue());
}
return result;
}
private Exception parametersMethodReturnedWrongType() throws Exception {
String className = getTestClass().getName();
String methodName = getParametersMethod().getName();
String message = MessageFormat.format("{0}.{1}() must return an Iterable of arrays.", className, methodName);
return new Exception(message);
}
private List<FrameworkField> getAnnotatedFieldsByParameter() {
return getTestClass().getAnnotatedFields(Parameter.class);
}
private boolean fieldsAreAnnotated() {
return !getAnnotatedFieldsByParameter().isEmpty();
}
}
| aporo69/junit-issue-1167 | poc/src/main/java/org/junit/runners/fix/v411/Parameterized.java | Java | epl-1.0 | 13,537 |
/**
* This file was copied and re-packaged automatically by
* org.xtext.example.delphi.build.GenerateCS2AST
* from
* ..\..\org.eclipse.qvtd\plugins\org.eclipse.qvtd.runtime\src\org\eclipse\qvtd\runtime\evaluation\AbstractInvocation.java
*
* Do not edit this file.
*/
/*******************************************************************************
* Copyright (c) 2013, 2016 Willink Transformations and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* E.D.Willink - Initial API and implementation
*******************************************************************************/
package org.xtext.example.delphi.tx;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.ocl.pivot.ids.TypeId;
import org.xtext.example.delphi.internal.tx.AbstractInvocationInternal;
/**
* AbstractInvocation provides the mandatory shared functionality of the intrusive blocked/waiting linked list functionality.
*/
public abstract class AbstractInvocation extends AbstractInvocationInternal
{
public abstract static class Incremental extends AbstractInvocation implements Invocation.Incremental
{
public static final @NonNull List<@NonNull Object> EMPTY_OBJECT_LIST = Collections.emptyList();
public static final @NonNull List<SlotState.@NonNull Incremental> EMPTY_SLOT_LIST = Collections.emptyList();
protected final @NonNull InvocationConstructor constructor;
protected final int sequence;
private Set<@NonNull Object> createdObjects = null;
private Set<SlotState.@NonNull Incremental> readSlots = null;
private Set<SlotState.@NonNull Incremental> writeSlots = null;
protected Incremental(InvocationConstructor.@NonNull Incremental constructor) {
super(constructor);
this.constructor = constructor;
this.sequence = constructor.nextSequence();
}
@Override
public void addCreatedObject(@NonNull Object createdObject) {
if (createdObjects == null) {
createdObjects = new HashSet<>();
}
createdObjects.add(createdObject);
}
@Override
public void addReadSlot(SlotState.@NonNull Incremental readSlot) {
if (readSlots == null) {
readSlots = new HashSet<>();
}
readSlots.add(readSlot);
readSlot.addTargetInternal(this);
}
@Override
public void addWriteSlot(SlotState.@NonNull Incremental writeSlot) {
if (writeSlots == null) {
writeSlots = new HashSet<>();
}
writeSlots.add(writeSlot);
writeSlot.addSourceInternal(this);
}
protected @NonNull Connection createConnection(@NonNull String name, @NonNull TypeId typeId, boolean isStrict) {
return constructor.getInterval().createConnection(name, typeId, isStrict);
}
protected Connection.@NonNull Incremental createIncrementalConnection(@NonNull String name, @NonNull TypeId typeId, boolean isStrict) {
return constructor.getInterval().createIncrementalConnection(name, typeId, isStrict);
}
@Override
public @NonNull Iterable<@NonNull Object> getCreatedObjects() {
return createdObjects != null ? createdObjects : EMPTY_OBJECT_LIST;
}
@SuppressWarnings("null")
@Override
public @NonNull String getName() {
InvocationConstructor constructor2 = constructor; // May be invoked from toString() during constructor debugging
return (constructor2 != null ? constructor2.getName() : "null") + "-" + sequence;
}
@Override
public @NonNull Iterable<SlotState.@NonNull Incremental> getReadSlots() {
return readSlots != null ? readSlots : EMPTY_SLOT_LIST;
}
@Override
public @NonNull Iterable<SlotState.@NonNull Incremental> getWriteSlots() {
return writeSlots != null ? writeSlots : EMPTY_SLOT_LIST;
}
@Override
public @NonNull String toString() {
return getName();
}
}
protected AbstractInvocation(@NonNull InvocationConstructor constructor) {
super(constructor.getInterval());
}
@Override
public <R> R accept(@NonNull ExecutionVisitor<R> visitor) {
return visitor.visitInvocation(this);
}
@Override
public @NonNull String getName() {
return toString().replace("@", "\n@");
}
} | adolfosbh/cs2as | org.xtext.example.delphi/src-gen/org/xtext/example/delphi/tx/AbstractInvocation.java | Java | epl-1.0 | 4,339 |
/**
* Copyright (c) 2010-2015, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.model.sitemap.internal;
import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.ecore.EObject;
import org.openhab.model.core.ModelRepository;
import org.openhab.model.sitemap.Sitemap;
import org.openhab.model.sitemap.SitemapProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class provides access to the sitemap model files.
*
* @author Kai Kreuzer
*
*/
public class SitemapProviderImpl implements SitemapProvider {
private static final Logger logger = LoggerFactory.getLogger(SitemapProviderImpl.class);
private ModelRepository modelRepo = null;
public void setModelRepository(ModelRepository modelRepo) {
this.modelRepo = modelRepo;
}
public void unsetModelRepository(ModelRepository modelRepo) {
this.modelRepo = null;
}
/* (non-Javadoc)
* @see org.openhab.model.sitemap.internal.SitemapProvider#getSitemap(java.lang.String)
*/
public Sitemap getSitemap(String sitemapName) {
if(modelRepo!=null) {
//System.out.println("\n***SiteMapProviderImpl->getSitemap->"+modelRepo.getName());
Sitemap sitemap = (Sitemap) modelRepo.getModel(sitemapName + ".sitemap");
if(sitemap!=null) {
return sitemap;
} else {
logger.debug("Sitemap {} can not be found", sitemapName);
return null;
}
} else {
logger.debug("No model repository service is available");
return null;
}
}
public void iterate(EObject sitemap){
final TreeIterator<EObject> contentIterator=sitemap.eAllContents();
while (contentIterator.hasNext()) {
final EObject next=contentIterator.next();
}
}
}
| rahulopengts/myhome | bundles/model/org.openhab.model.sitemap/src/org/openhab/model/sitemap/internal/SitemapProviderImpl.java | Java | epl-1.0 | 1,935 |
/*
* Copyright 2012 PRODYNA AG
*
* Licensed under the Eclipse Public License (EPL), Version 1.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.opensource.org/licenses/eclipse-1.0.php or
* http://www.nabucco.org/License.html
*
* 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.nabucco.framework.base.facade.datatype;
import java.util.Arrays;
/**
* NByteArray
*
* @author Nicolas Moser, PRODYNA AG
*/
public abstract class NByteArray extends BasetypeSupport implements Basetype, Comparable<NByteArray> {
private static final long serialVersionUID = 1L;
private byte[] value;
/**
* Default constructor
*/
public NByteArray() {
this(null);
}
/**
* Constructor initializing the value.
*
* @param value
* the value to initialize
*/
public NByteArray(byte[] value) {
super(BasetypeType.BYTE_ARRAY);
this.value = value;
}
@Override
public byte[] getValue() {
return value;
}
@Override
public String getValueAsString() {
if (this.value == null) {
return null;
}
return new String(this.value);
}
@Override
public void setValue(Object value) throws IllegalArgumentException {
if (value != null && !(value instanceof byte[])) {
throw new IllegalArgumentException("Cannot set value '" + value + "' to NByteArray.");
}
this.setValue((byte[]) value);
}
/**
* Setter for the byte[] value.
*
* @param value
* the byte[] value to set.
*/
public void setValue(byte[] value) {
this.value = value;
}
/**
* Returns a <code>String</code> object representing this <code>NByteArray</code>'s value.
*
* @return a string representation of the value of this object in base 10.
*/
@Override
public String toString() {
if (this.value == null) {
return null;
}
return new String(this.value);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(this.value);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof NByteArray))
return false;
NByteArray other = (NByteArray) obj;
if (!Arrays.equals(this.value, other.value))
return false;
return true;
}
@Override
public int compareTo(NByteArray other) {
if (other == null) {
return -1;
}
if (getValue() == null) {
if (other.getValue() == null) {
return 0;
}
return 1;
}
if (other.getValue() == null) {
return -1;
}
if (this.value.length != other.value.length) {
if (this.value.length > other.value.length) {
return 1;
}
if (this.value.length < other.value.length) {
return -1;
}
}
for (int i = 0; i < this.value.length; i++) {
if (this.value[i] != other.value[i]) {
if (this.value[i] > other.value[i]) {
return 1;
}
if (this.value[i] < other.value[i]) {
return -1;
}
}
}
return 0;
}
@Override
public abstract NByteArray cloneObject();
/**
* Clones the properties of this basetype into the given basetype.
*
* @param clone
* the cloned basetype
*/
protected void cloneObject(NByteArray clone) {
if (this.value != null) {
clone.value = Arrays.copyOf(this.value, this.value.length);
}
}
}
| NABUCCO/org.nabucco.framework.base | org.nabucco.framework.base.facade.datatype/src/main/man/org/nabucco/framework/base/facade/datatype/NByteArray.java | Java | epl-1.0 | 4,346 |
namespace Inspiring.MvvmTest.Common.Events {
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class EventSubscriptionTests {
[TestMethod]
public void EventSubscription_DoesNotKeepReceiverAlive() {
Assert.Inconclusive("Events: TODO");
}
[TestMethod]
public void EventHandlerDelegate_IsNotGarbageCollectedWhenReceiverIsStillAlive() {
Assert.Inconclusive("Events: TODO");
}
[TestMethod]
public void EventHandlerDelegate_IsGarbageCollectionWhenReceiverIsCollected() {
Assert.Inconclusive("Events: TODO");
}
[TestMethod]
public void EventHandlerDelegate_IsNotCollectedWhenItReferencesAStaticMethod() {
Assert.Inconclusive("Events: TODO");
}
}
} | InspiringCode/Inspiring.MVVM | Source/MvvmTest/Common/Events/EventSubscriptionTests.cs | C# | epl-1.0 | 817 |
package ch.docbox.ws.cdachservicesv2;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.hl7.v3.CE;
/**
* <p>Java-Klasse für anonymous complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="code" type="{urn:hl7-org:v3}CE" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"code"
})
@XmlRootElement(name = "getInboxClinicalDocuments")
public class GetInboxClinicalDocuments {
protected CE code;
/**
* Ruft den Wert der code-Eigenschaft ab.
*
* @return
* possible object is
* {@link CE }
*
*/
public CE getCode() {
return code;
}
/**
* Legt den Wert der code-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link CE }
*
*/
public void setCode(CE value) {
this.code = value;
}
}
| DavidGutknecht/elexis-3-base | bundles/ch.elexis.docbox.ws.client/src-gen/ch/docbox/ws/cdachservicesv2/GetInboxClinicalDocuments.java | Java | epl-1.0 | 1,395 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.03.18 at 03:48:09 PM CET
//
package ch.fd.invoice440.request;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for companyType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="companyType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="companyname" type="{http://www.forum-datenaustausch.ch/invoice}stringType1_35"/>
* <element name="department" type="{http://www.forum-datenaustausch.ch/invoice}stringType1_35" minOccurs="0"/>
* <element name="subaddressing" type="{http://www.forum-datenaustausch.ch/invoice}stringType1_35" minOccurs="0"/>
* <element name="postal" type="{http://www.forum-datenaustausch.ch/invoice}postalAddressType"/>
* <element name="telecom" type="{http://www.forum-datenaustausch.ch/invoice}telecomAddressType" minOccurs="0"/>
* <element name="online" type="{http://www.forum-datenaustausch.ch/invoice}onlineAddressType" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "companyType", propOrder = {
"companyname",
"department",
"subaddressing",
"postal",
"telecom",
"online"
})
public class CompanyType {
@XmlElement(required = true)
protected String companyname;
protected String department;
protected String subaddressing;
@XmlElement(required = true)
protected PostalAddressType postal;
protected TelecomAddressType telecom;
protected OnlineAddressType online;
/**
* Gets the value of the companyname property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCompanyname() {
return companyname;
}
/**
* Sets the value of the companyname property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCompanyname(String value) {
this.companyname = value;
}
/**
* Gets the value of the department property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDepartment() {
return department;
}
/**
* Sets the value of the department property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDepartment(String value) {
this.department = value;
}
/**
* Gets the value of the subaddressing property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSubaddressing() {
return subaddressing;
}
/**
* Sets the value of the subaddressing property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSubaddressing(String value) {
this.subaddressing = value;
}
/**
* Gets the value of the postal property.
*
* @return
* possible object is
* {@link PostalAddressType }
*
*/
public PostalAddressType getPostal() {
return postal;
}
/**
* Sets the value of the postal property.
*
* @param value
* allowed object is
* {@link PostalAddressType }
*
*/
public void setPostal(PostalAddressType value) {
this.postal = value;
}
/**
* Gets the value of the telecom property.
*
* @return
* possible object is
* {@link TelecomAddressType }
*
*/
public TelecomAddressType getTelecom() {
return telecom;
}
/**
* Sets the value of the telecom property.
*
* @param value
* allowed object is
* {@link TelecomAddressType }
*
*/
public void setTelecom(TelecomAddressType value) {
this.telecom = value;
}
/**
* Gets the value of the online property.
*
* @return
* possible object is
* {@link OnlineAddressType }
*
*/
public OnlineAddressType getOnline() {
return online;
}
/**
* Sets the value of the online property.
*
* @param value
* allowed object is
* {@link OnlineAddressType }
*
*/
public void setOnline(OnlineAddressType value) {
this.online = value;
}
}
| DavidGutknecht/elexis-3-base | bundles/at.medevit.elexis.tarmed.model/src-gen/ch/fd/invoice440/request/CompanyType.java | Java | epl-1.0 | 5,377 |
/*
* Copyright (c) 2012-2018 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.api.search.server.impl;
import java.util.List;
import org.eclipse.che.api.search.server.OffsetData;
/** Single item in {@code SearchResult}. */
public class SearchResultEntry {
private final String filePath;
private final List<OffsetData> data;
public SearchResultEntry(String filePath, List<OffsetData> data) {
this.filePath = filePath;
this.data = data;
}
public List<OffsetData> getData() {
return data;
}
/** Path of file that matches the search criteria. */
public String getFilePath() {
return filePath;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof SearchResultEntry)) {
return false;
}
SearchResultEntry that = (SearchResultEntry) o;
if (getFilePath() != null
? !getFilePath().equals(that.getFilePath())
: that.getFilePath() != null) {
return false;
}
return getData() != null ? getData().equals(that.getData()) : that.getData() == null;
}
@Override
public int hashCode() {
int result = getFilePath() != null ? getFilePath().hashCode() : 0;
result = 31 * result + (getData() != null ? getData().hashCode() : 0);
return result;
}
@Override
public String toString() {
return "SearchResultEntry{" + "filePath='" + filePath + '\'' + ", data=" + data + '}';
}
}
| sleshchenko/che | wsagent/che-core-api-project/src/main/java/org/eclipse/che/api/search/server/impl/SearchResultEntry.java | Java | epl-1.0 | 1,751 |
/*
* 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.tomcat.util.net;
/**
* Someone, please change the enum name.
*
* @author remm
*/
public enum SocketStatus {
OPEN, STOP, TIMEOUT, DISCONNECT, ERROR
}
| GazeboHub/ghub-portal-doc | doc/modelio/GHub Portal/mda/JavaDesigner/res/java/tomcat/java/org/apache/tomcat/util/net/SocketStatus.java | Java | epl-1.0 | 992 |
/**
* Copyright (c) 2012, 2016 Sme.UP and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.smeup.sys.db.core;
import org.eclipse.datatools.modelbase.sql.tables.Table;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Table Provider</b></em>'.
* <!-- end-user-doc -->
*
*
* @see org.smeup.sys.db.core.QDatabaseCorePackage#getTableProvider()
* @model interface="true" abstract="true"
* @generated
*/
public interface QTableProvider {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @model required="true"
* @generated
*/
Table getTable(String schema, String table);
} // QTableProvider
| smeup/asup | org.smeup.sys.db.core/src/org/smeup/sys/db/core/QTableProvider.java | Java | epl-1.0 | 865 |
/*******************************************************************************
* Copyright (c) 2012-2014 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.dto.generator;
import org.eclipse.che.dto.shared.CompactJsonDto;
import org.eclipse.che.dto.shared.DTO;
import org.eclipse.che.dto.shared.DelegateTo;
import org.eclipse.che.dto.shared.JsonFieldName;
import org.eclipse.che.dto.shared.SerializationIndex;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** Abstract base class for the source generating template for a single DTO. */
abstract class DtoImpl {
protected static final String COPY_JSONS_PARAM = "copyJsons";
private final Class<?> dtoInterface;
private final DtoTemplate enclosingTemplate;
private final boolean compactJson;
private final String implClassName;
private final List<Method> dtoMethods;
DtoImpl(DtoTemplate enclosingTemplate, Class<?> dtoInterface) {
this.enclosingTemplate = enclosingTemplate;
this.dtoInterface = dtoInterface;
this.implClassName = dtoInterface.getSimpleName() + "Impl";
this.compactJson = DtoTemplate.implementsInterface(dtoInterface, CompactJsonDto.class);
this.dtoMethods = ImmutableList.copyOf(calcDtoMethods());
}
protected boolean isCompactJson() {
return compactJson;
}
public Class<?> getDtoInterface() {
return dtoInterface;
}
public DtoTemplate getEnclosingTemplate() {
return enclosingTemplate;
}
protected String getJavaFieldName(String getterName) {
String fieldName;
if (getterName.startsWith("get")) {
fieldName = getterName.substring(3);
} else {
// starts with "is", see method '#ignoreMethod(Method)'
fieldName = getterName.substring(2);
}
return normalizeIdentifier(Character.toLowerCase(fieldName.charAt(0)) + fieldName.substring(1));
}
private String normalizeIdentifier(String fieldName) {
// use $ prefix according to http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.8
switch (fieldName) {
case "default":
fieldName = "$" + fieldName;
break;
// add other keywords here
}
return fieldName;
}
private String getCamelCaseName(String fieldName) {
// see normalizeIdentifier method
if (fieldName.charAt(0) == '$') {
fieldName = fieldName.substring(1);
}
return Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
}
protected String getImplClassName() {
return implClassName;
}
protected String getSetterName(String fieldName) {
return "set" + getCamelCaseName(fieldName);
}
protected String getWithName(String fieldName) {
return "with" + getCamelCaseName(fieldName);
}
protected String getListAdderName(String fieldName) {
return "add" + getCamelCaseName(fieldName);
}
protected String getMapPutterName(String fieldName) {
return "put" + getCamelCaseName(fieldName);
}
protected String getClearName(String fieldName) {
return "clear" + getCamelCaseName(fieldName);
}
protected String getEnsureName(String fieldName) {
return "ensure" + getCamelCaseName(fieldName);
}
/**
* Get the canonical name of the field by deriving it from a getter method's name.
*/
protected String getFieldNameFromGetterName(String getterName) {
String fieldName;
if (getterName.startsWith("get")) {
fieldName = getterName.substring(3);
} else {
// starts with "is", see method '#ignoreMethod(Method)'
fieldName = getterName.substring(2);
}
return Character.toLowerCase(fieldName.charAt(0)) + fieldName.substring(1);
}
/**
* Get the name of the JSON field that corresponds to the given getter method in a DTO-annotated type.
*/
protected String getJsonFieldName(Method getterMethod) {
// First, check if a custom field name is defined for the getter
JsonFieldName fieldNameAnn = getterMethod.getAnnotation(JsonFieldName.class);
if (fieldNameAnn != null) {
String customFieldName = fieldNameAnn.value();
if (customFieldName != null && !customFieldName.isEmpty()) {
return customFieldName;
}
}
// If no custom name is given for the field, deduce it from the camel notation
return getFieldNameFromGetterName(getterMethod.getName());
}
/**
* Our super interface may implement some other interface (or not). We need to know because if it does then we need to directly extend
* said super interfaces impl class.
*/
protected Class<?> getSuperDtoInterface(Class<?> dto) {
Class<?>[] superInterfaces = dto.getInterfaces();
if (superInterfaces.length > 0) {
for (Class<?> superInterface : superInterfaces) {
if (superInterface.isAnnotationPresent(DTO.class)) {
return superInterface;
}
}
}
return null;
}
protected List<Method> getDtoGetters(Class<?> dto) {
final Map<String, Method> getters = new HashMap<>();
if (enclosingTemplate.isDtoInterface(dto)) {
addDtoGetters(dto, getters);
addSuperGetters(dto, getters);
}
return new ArrayList<>(getters.values());
}
/**
* Get the names of all the getters in the super DTO interface and upper ancestors.
*/
protected Set<String> getSuperGetterNames(Class<?> dto) {
final Map<String, Method> getters = new HashMap<>();
Class<?> superDto = getSuperDtoInterface(dto);
if (superDto != null) {
addDtoGetters(superDto, getters);
addSuperGetters(superDto, getters);
}
return getters.keySet();
}
/**
* Adds all getters from parent <b>NOT DTO</b> interfaces for given {@code dto} interface.
* Does not add method when it is already present in getters map.
*/
private void addSuperGetters(Class<?> dto, Map<String, Method> getters) {
for (Class<?> superInterface : dto.getInterfaces()) {
if (!superInterface.isAnnotationPresent(DTO.class)) {
for (Method method : superInterface.getDeclaredMethods()) {
//when method is already present in map then child interface
//overrides it, which means that it should not be put into getters
if (isDtoGetter(method) && !getters.containsKey(method.getName())) {
getters.put(method.getName(), method);
}
}
addSuperGetters(superInterface, getters);
}
}
}
protected List<Method> getInheritedDtoGetters(Class<?> dto) {
List<Method> getters = new ArrayList<>();
if (enclosingTemplate.isDtoInterface(dto)) {
Class<?> superInterface = getSuperDtoInterface(dto);
while (superInterface != null) {
addDtoGetters(superInterface, getters);
superInterface = getSuperDtoInterface(superInterface);
}
addDtoGetters(dto, getters);
}
return getters;
}
private void addDtoGetters(Class<?> dto, Map<String, Method> getters) {
for (Method method : dto.getDeclaredMethods()) {
if (!method.isDefault() && isDtoGetter(method)) {
getters.put(method.getName(), method);
}
}
}
private void addDtoGetters(Class<?> dto, List<Method> getters) {
for (Method method : dto.getDeclaredMethods()) {
if (!method.isDefault() && isDtoGetter(method)) {
getters.add(method);
}
}
}
/** Check is specified method is DTO getter. */
protected boolean isDtoGetter(Method method) {
if (method.isAnnotationPresent(DelegateTo.class)) {
return false;
}
String methodName = method.getName();
if ((methodName.startsWith("get") || methodName.startsWith("is")) && method.getParameterTypes().length == 0) {
if (methodName.startsWith("is") && methodName.length() > 2) {
return method.getReturnType() == Boolean.class || method.getReturnType() == boolean.class;
}
return methodName.length() > 3;
}
return false;
}
/** Tests whether or not a given generic type is allowed to be used as a generic. */
protected static boolean isWhitelisted(Class<?> genericType) {
return DtoTemplate.jreWhitelist.contains(genericType);
}
/** Tests whether or not a given return type is a number primitive or its wrapper type. */
protected static boolean isNumber(Class<?> returnType) {
final Class<?>[] numericTypes = {int.class, long.class, short.class, float.class, double.class, byte.class,
Integer.class, Long.class, Short.class, Float.class, Double.class, Byte.class};
for (Class<?> standardPrimitive : numericTypes) {
if (returnType.equals(standardPrimitive)) {
return true;
}
}
return false;
}
/** Tests whether or not a given return type is a boolean primitive or its wrapper type. */
protected static boolean isBoolean(Class<?> returnType) {
return returnType.equals(Boolean.class) || returnType.equals(boolean.class);
}
protected static String getPrimitiveName(Class<?> returnType) {
if (returnType.equals(Integer.class) || returnType.equals(int.class)) {
return "int";
} else if (returnType.equals(Long.class) || returnType.equals(long.class)) {
return "long";
} else if (returnType.equals(Short.class) || returnType.equals(short.class)) {
return "short";
} else if (returnType.equals(Float.class) || returnType.equals(float.class)) {
return "float";
} else if (returnType.equals(Double.class) || returnType.equals(double.class)) {
return "double";
} else if (returnType.equals(Byte.class) || returnType.equals(byte.class)) {
return "byte";
} else if (returnType.equals(Boolean.class) || returnType.equals(boolean.class)) {
return "boolean";
} else if (returnType.equals(Character.class) || returnType.equals(char.class)) {
return "char";
}
throw new IllegalArgumentException("Unknown wrapper class type.");
}
/** Tests whether or not a given return type is a java.util.List. */
public static boolean isList(Class<?> returnType) {
return returnType.equals(List.class);
}
/** Tests whether or not a given return type is a java.util.Map. */
public static boolean isMap(Class<?> returnType) {
return returnType.equals(Map.class);
}
public static boolean isAny(Class<?> returnType) {
return returnType.equals(Object.class);
}
/**
* Expands the type and its first generic parameter (which can also have a first generic parameter (...)).
* <p/>
* For example, JsonArray<JsonStringMap<JsonArray<SomeDto>>> would produce [JsonArray, JsonStringMap, JsonArray,
* SomeDto].
*/
public static List<Type> expandType(Type curType) {
List<Type> types = new LinkedList<>();
do {
types.add(curType);
if (curType instanceof ParameterizedType) {
Type[] genericParamTypes = ((ParameterizedType)curType).getActualTypeArguments();
Type rawType = ((ParameterizedType)curType).getRawType();
boolean map = rawType instanceof Class<?> && rawType == Map.class;
if (!map && genericParamTypes.length != 1) {
throw new IllegalStateException("Multiple type parameters are not supported (neither are zero type parameters)");
}
Type genericParamType = map ? genericParamTypes[1] : genericParamTypes[0];
if (genericParamType instanceof Class<?>) {
Class<?> genericParamTypeClass = (Class<?>)genericParamType;
if (isWhitelisted(genericParamTypeClass)) {
assert genericParamTypeClass.equals(
String.class) : "For JSON serialization there can be only strings or DTO types. ";
}
}
curType = genericParamType;
} else {
if (curType instanceof Class) {
Class<?> clazz = (Class<?>)curType;
if (isList(clazz) || isMap(clazz)) {
throw new DtoTemplate.MalformedDtoInterfaceException(
"JsonArray and JsonStringMap MUST have a generic type specified (and no... ? doesn't cut it!).");
}
}
curType = null;
}
} while (curType != null);
return types;
}
public static Class<?> getRawClass(Type type) {
return (Class<?>)((type instanceof ParameterizedType) ? ((ParameterizedType)type).getRawType() : type);
}
/**
* Returns public methods specified in DTO interface.
* <p/>
* <p>For compact DTO (see {@link org.eclipse.che.dto.shared.CompactJsonDto}) methods are ordered corresponding to {@link
* org.eclipse.che.dto.shared.SerializationIndex} annotation.
* <p/>
* <p>Gaps in index sequence are filled with {@code null}s.
*/
protected List<Method> getDtoMethods() {
return dtoMethods;
}
private Method[] calcDtoMethods() {
if (!compactJson) {
return dtoInterface.getMethods();
}
Map<Integer, Method> methodsMap = new HashMap<>();
int maxIndex = 0;
for (Method method : dtoInterface.getMethods()) {
SerializationIndex serializationIndex = method.getAnnotation(SerializationIndex.class);
Preconditions.checkNotNull(serializationIndex, "Serialization index is not specified for %s in %s",
method.getName(), dtoInterface.getSimpleName());
// "53" is the number of bits in JS integer.
// This restriction will allow to add simple bit-field
// "serialization-skipping-list" in the future.
int index = serializationIndex.value();
Preconditions.checkState(index > 0 && index <= 53, "Serialization index out of range [1..53] for %s in %s",
method.getName(), dtoInterface.getSimpleName());
Preconditions.checkState(!methodsMap.containsKey(index), "Duplicate serialization index for %s in %s",
method.getName(), dtoInterface.getSimpleName());
maxIndex = Math.max(index, maxIndex);
methodsMap.put(index, method);
}
Method[] result = new Method[maxIndex];
for (int index = 0; index < maxIndex; index++) {
result[index] = methodsMap.get(index + 1);
}
return result;
}
protected boolean isLastMethod(Method method) {
Preconditions.checkNotNull(method);
return method == dtoMethods.get(dtoMethods.size() - 1);
}
/**
* Create a textual representation of a string literal that evaluates to the given value.
*/
protected String quoteStringLiteral(String value) {
StringWriter sw = new StringWriter();
try (JsonWriter writer = new JsonWriter(sw)) {
writer.setLenient(true);
writer.value(value);
writer.flush();
} catch (IOException ex) {
throw new RuntimeException("Unexpected I/O failure: " + ex.getLocalizedMessage(), ex);
}
return sw.toString();
}
/**
* @return String representing the source definition for the DTO impl as an inner class.
*/
abstract String serialize();
} | codenvy/che-core | platform-api/che-core-api-dto/src/main/java/org/eclipse/che/dto/generator/DtoImpl.java | Java | epl-1.0 | 17,115 |
/**
* Copyright (c) 2005-2012 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Eclipse Public License (EPL).
* Please see the license.txt included with this distribution for details.
* Any modifications to this file must keep this entire header intact.
*/
/*
* Created on Oct 28, 2006
* @author Fabio
*/
package org.python.pydev.plugin.nature;
import java.util.HashMap;
import java.util.Map;
import junit.framework.TestCase;
import org.python.pydev.editor.actions.PySelectionTest;
import org.python.pydev.editor.codecompletion.revisited.ProjectModulesManager;
import org.python.pydev.plugin.PydevPlugin;
import org.python.pydev.shared_core.SharedCorePlugin;
import org.python.pydev.tests.BundleInfoStub;
public class PythonNatureStoreTest extends TestCase {
public static void main(String[] args) {
junit.textui.TestRunner.run(PythonNatureStoreTest.class);
}
private String contents1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"
+
"<?eclipse-pydev version=\"1.0\"?>\r\n"
+
"\r\n"
+
"<pydev_project>\r\n"
+
"<pydev_property name=\"PyDevPluginID(null plugin).PYTHON_PROJECT_VERSION\">python 2.5</pydev_property>\r\n"
+
"<pydev_pathproperty name=\"PyDevPluginID(null plugin).PROJECT_SOURCE_PATH\">\r\n"
+
"<path>/test</path>\r\n" +
"</pydev_pathproperty>\r\n"
+
"<pydev_pathproperty name=\"PyDevPluginID(null plugin).PROJECT_EXTERNAL_SOURCE_PATH\"/>\r\n"
+
"</pydev_project>\r\n" +
"";
private String contents2 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"
+
"<?eclipse-pydev version=\"1.0\"?>\r\n"
+
"\r\n"
+
"<pydev_project>\r\n"
+
"<pydev_property name=\"PyDevPluginID(null plugin).PYTHON_PROJECT_VERSION\">python 2.5</pydev_property>\r\n"
+
"<pydev_pathproperty name=\"PyDevPluginID(null plugin).PROJECT_SOURCE_PATH\">\r\n"
+
"<path>/test/foo</path>\r\n" +
"<path>/bar/kkk</path>\r\n" +
"</pydev_pathproperty>\r\n"
+
"<pydev_pathproperty name=\"PyDevPluginID(null plugin).PROJECT_EXTERNAL_SOURCE_PATH\"/>\r\n"
+
"</pydev_project>\r\n" +
"";
private String contents3 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"
+
"<?eclipse-pydev version=\"1.0\"?>\r\n"
+
"\r\n"
+
"<pydev_project>\r\n"
+
"<pydev_property name=\"PyDevPluginID(null plugin).PYTHON_PROJECT_VERSION\">python 2.5</pydev_property>\r\n"
+
"<pydev_pathproperty name=\"PyDevPluginID(null plugin).PROJECT_SOURCE_PATH\">\r\n"
+
"<path>/test/foo</path>\r\n" +
"<path>/bar/kkk</path>\r\n" +
"</pydev_pathproperty>\r\n"
+
"<pydev_pathproperty name=\"PyDevPluginID(null plugin).PROJECT_EXTERNAL_SOURCE_PATH\"/>\r\n"
+
"<pydev_variables_property name=\"PyDevPluginID(null plugin).PROJECT_VARIABLE_SUBSTITUTION\">\r\n"
+
"<key>MY_KEY</key>\r\n" +
"<value>MY_VALUE</value>\r\n" +
"</pydev_variables_property>\r\n"
+
"</pydev_project>\r\n" +
"";
@Override
protected void setUp() throws Exception {
super.setUp();
ProjectModulesManager.IN_TESTS = true;
PydevPlugin.setBundleInfo(new BundleInfoStub());
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
public void testLoad() throws Exception {
// This test fails because of whitespace comparison problems. It may be better to
// use something like XMLUnit to compare the two XML files?
if (SharedCorePlugin.skipKnownFailures()) {
return;
}
PythonNatureStore store = new PythonNatureStore();
ProjectStub2 projectStub2 = new ProjectStub2("test");
//when setting the project, a side-effect must be that we create the xml file if it still does not exist
store.setProject(projectStub2);
//check the contents
String strContents = store.getLastLoadedContents();
PySelectionTest.checkStrEquals(contents1, strContents.replaceFirst(" standalone=\"no\"", "")); //depending on the java version, standalone="no" may be generated
//in ProjectStub2, the initial setting is /test (see the getPersistentProperty)
assertEquals("/test", store.getPathProperty(PythonPathNature.getProjectSourcePathQualifiedName()));
store.setPathProperty(PythonPathNature.getProjectSourcePathQualifiedName(), "/test/foo|/bar/kkk");
assertEquals("/test/foo|/bar/kkk", store.getPathProperty(PythonPathNature.getProjectSourcePathQualifiedName()));
strContents = store.getLastLoadedContents();
PySelectionTest.checkStrEquals(contents2, strContents.replaceFirst(" standalone=\"no\"", "")); //depending on the java version, standalone="no" may be generated
assertNull(store.getPathProperty(PythonPathNature.getProjectExternalSourcePathQualifiedName()));
Map<String, String> map = new HashMap<String, String>();
map.put("MY_KEY", "MY_VALUE");
store.setMapProperty(PythonPathNature.getProjectVariableSubstitutionQualifiedName(), map);
strContents = store.getLastLoadedContents();
PySelectionTest.checkStrEquals(contents3, strContents.replaceFirst(" standalone=\"no\"", "")); //depending on the java version, standalone="no" may be generated
assertEquals(map, store.getMapProperty(PythonPathNature.getProjectVariableSubstitutionQualifiedName()));
}
}
| aptana/Pydev | tests/org.python.pydev.tests/src/org/python/pydev/plugin/nature/PythonNatureStoreTest.java | Java | epl-1.0 | 5,941 |
/* ****************************************************************************
* FontInfo.java
* ****************************************************************************/
/* J_LZ_COPYRIGHT_BEGIN *******************************************************
* Copyright 2001-2006 Laszlo Systems, Inc. All Rights Reserved. *
* Use is subject to license terms. *
* J_LZ_COPYRIGHT_END *********************************************************/
package org.openlaszlo.compiler;
import org.openlaszlo.utils.ChainedException;
import java.io.Serializable;
import java.util.*;
/**
* Font information used for measuring text.
*
* @author <a href="mailto:bloch@laszlosystems.com">Eric Bloch</a>
*/
public class FontInfo implements java.io.Serializable {
public static final String NULL_FONT = null;
public static final int NULL_SIZE = -1;
public static final int NULL_STYLE = -1;
/** bit fields for text style */
public final static int PLAIN = 0x0;
/** bit fields for text style */
public final static int BOLD = 0x1;
/** bit fields for text style */
public final static int ITALIC = 0x2;
/** bit fields for text style */
public final static int BOLDITALIC = 0x3;
/** font face */
private String mName = null;
/** font size */
private int mSize;
/** used for compile-time width/height cascading */
private int mWidth = NULL_SIZE;
private int mHeight = NULL_SIZE;
/** font style bits */
public int styleBits = 0;
/** This can have three values:
-1 = unset
0 = false
1 = true
*/
public final static int FONTINFO_NULL = -1;
public final static int FONTINFO_FALSE = 0;
public final static int FONTINFO_TRUE = 1;
// resizable defaults to false
public int resizable = FONTINFO_NULL;
// multiline default to false
public int multiline = FONTINFO_NULL;
public String toString() {
return "FontInfo: name="+mName+", size="+mSize+", style="+getStyle();
}
public String toStringLong() {
return "FontInfo: name="+mName+", size="+mSize+", style="+getStyle()+", width="+mWidth+", height="+mHeight+", resizable="+resizable+", multiline="+multiline;
}
/**
* Create a new FontInfo
* @param name name
* @param sz size
* @param st style
*/
public FontInfo(String name, String sz, String st) {
mName = name;
setSize(sz);
setStyle(st);
}
public FontInfo(FontInfo i) {
this.mName = i.mName;
this.mSize = i.mSize;
this.styleBits = i.styleBits;
// static text optimization params
this.resizable = i.resizable;
this.multiline = i.multiline;
this.mWidth = i.getWidth();
this.mHeight = i.getHeight();
}
public FontInfo(String name, int sz, int st) {
mName = name;
mSize = sz;
styleBits = st;
}
/** Extra params for static textfield optimization.
Tracks width and height of a view.
*/
public int getWidth() {
return mWidth;
}
public int getHeight() {
return mHeight;
}
public void setWidth (int w) {
mWidth = w;
}
public void setHeight (int w) {
mHeight = w;
}
/**
* Set the name
* @param f the name
*/
public void setName(String f) {
mName = f;
}
/**
* Set the style
* @param st style
*/
public void setStyle(String st) {
styleBits = styleBitsFromString(st);
}
/**
* Set the style bits directly
* @param st stylebits
*/
public void setStyleBits(int st) {
styleBits = st;
}
/**
* Set the size
* @param sz the size
*/
public void setSize(String sz) {
mSize = Integer.parseInt(sz);
}
/**
* Set the size
* @param sz the size
*/
public void setSize(int sz) {
mSize = sz;
}
/**
* @return the size
*/
public int getSize() {
return mSize;
}
/**
* @return the stylebits
*/
public int getStyleBits() {
return styleBits;
}
/**
* @return the name
*/
public String getName() {
return mName;
}
public static FontInfo blankFontInfo() {
FontInfo fi = new FontInfo(FontInfo.NULL_FONT, FontInfo.NULL_SIZE, FontInfo.NULL_STYLE);
return fi;
}
/** Does this font spec contain a known font name,size,style ?
*/
public boolean isFullySpecified () {
return ((mSize != NULL_SIZE) &&
(styleBits != NULL_STYLE) &&
(mName != NULL_FONT) &&
// we don't understand constraint expressions, just string literals
(mName.charAt(0) != '$'));
}
/** If OTHER has non-null fields, copy
them from OTHER to us.
null fields are indicated by:
name == null,
size == -1,
stylebits == -1,
*/
public void mergeFontInfoFrom(FontInfo other) {
if (other.getSize()!= NULL_SIZE) {
mSize = other.getSize();
}
if (other.getStyleBits() != NULL_STYLE) {
styleBits = other.getStyleBits();
}
if (other.getName()!= NULL_FONT) {
mName = other.getName();
}
if (other.resizable != FONTINFO_NULL) {
resizable = other.resizable;
}
if (other.multiline != FONTINFO_NULL) {
multiline = other.multiline;
}
if (other.getWidth() != NULL_SIZE) {
mWidth = other.getWidth();
}
if (other.getHeight() != NULL_SIZE) {
mHeight = other.getHeight();
}
}
/**
* @return the name
*/
public final String getStyle() {
return styleBitsToString(styleBits);
}
/**
* @return the name
*/
public final String getStyle(boolean whitespace) {
return styleBitsToString(styleBits, whitespace);
}
/**
* Return the string representation of the style.
*
* @param styleBits an <code>int</code> encoding the style
* @param whitespace whether to separate style names by spaces; e.g. true for "bold italic", false for "bolditalic"
*/
public static String styleBitsToString(int styleBits, boolean whitespace) {
switch (styleBits) {
case PLAIN:
return "plain";
case BOLD:
return "bold";
case ITALIC:
return "italic";
case BOLDITALIC:
if (whitespace) {
return "bold italic";
} else {
return "bolditalic";
}
default:
return null;
}
}
/**
* Return the string representation of the style, e.g. "bold italic".
*
* @param styleBits an <code>int</code> value
*/
public static String styleBitsToString(int styleBits) {
return styleBitsToString(styleBits, true);
}
/**
/**
* @return the bits for a style
*/
public static int styleBitsFromString(String name) {
int style = PLAIN;
if (name != null) {
StringTokenizer st = new StringTokenizer(name);
while (st.hasMoreTokens()) {
String token = st.nextToken();
if (token.equals("bold")) {
style |= BOLD;
} else if (token.equals("italic")) {
style |= ITALIC;
} else if (token.equals("plain")) {
style |= PLAIN;
} else if (token.equals("bolditalic")) {
style |= ITALIC | BOLD;
} else {
throw new CompilationError(
/* (non-Javadoc)
* @i18n.test
* @org-mes="Unknown style " + p[0]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
FontInfo.class.getName(),"051018-315", new Object[] {name})
);
}
}
}
return style;
}
/**
* "bold italic", "italic bold" -> "bold italic" or "bolditalic"
* (depending on the value of <code>whitespace</code>
*
* @param style a <code>String</code> value
* @return a <code>String</code> value
*/
public static String normalizeStyleString(String style, boolean whitespace) {
if (style.matches("^\\s*\\$(\\w*)\\{(.*)}\\s*")) {
return style;
} else {
return styleBitsToString(styleBitsFromString(style), whitespace);
}
}
}
| mcarlson/openlaszlo | WEB-INF/lps/server/src/org/openlaszlo/compiler/FontInfo.java | Java | epl-1.0 | 8,728 |
package com.fnacmod.fnac;
//This code is copyright SoggyMustache, Link1234Gamer and Andrew_Playz
public class Reference {
public static final String MOD_ID = "fnac";
public static final String MOD_NAME = "Five Nights at Candy's Mod";
public static final String VERSION = "1.0";
public static final String CLIENT_PROXY_CLASS = "com.fnacmod.fnac.proxy.ClientProxy";
public static final String SERVER_PROXY_CLASS = "com.fnacmod.fnac.proxy.ServerProxy";
}
| Link1234Gamer/Five-Nights-at-Candy-s-Mod | src/main/java/com/fnacmod/fnac/Reference.java | Java | epl-1.0 | 466 |
package uk.ac.brighton.jamss;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;
/**
* Creates a sequencer used to play a percussion sequence taken
* from a .midi file.
* @author Nick Walker
*/
class MidiPlayer {
// Midi meta event
public static final int END_OF_TRACK_MESSAGE = 47;
private Sequencer sequencer;
public float tempo;
private boolean loop;
public boolean paused;
public void setBPMs(float beatsPerMinute){
tempo = beatsPerMinute;
}
/**
* Creates a new MidiPlayer object.
*/
public MidiPlayer() {
try {
sequencer = MidiSystem.getSequencer();
sequencer.open();
//sequencer.addMetaEventListener(this);
} catch (MidiUnavailableException ex) {
sequencer = null;
}
}
/**
* Loads a sequence from the file system. Returns null if an error occurs.
*/
public Sequence getSequence(String filename) {
try {
return getSequence(new FileInputStream(filename));
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
}
/**
* Loads a sequence from an input stream. Returns null if an error occurs.
*/
public Sequence getSequence(InputStream is) {
try {
if (!is.markSupported()) {
is = new BufferedInputStream(is);
}
Sequence s = MidiSystem.getSequence(is);
is.close();
return s;
} catch (InvalidMidiDataException ex) {
ex.printStackTrace();
return null;
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
}
/**
* Plays a sequence, optionally looping. This method returns immediately.
* The sequence is not played if it is invalid.
*/
public void play(Sequence sequence, boolean loop) {
if (sequencer != null && sequence != null && sequencer.isOpen()) {
try {
sequencer.setSequence(sequence);
sequencer.open();
/*if(loop) {
sequencer.setLoopStartPoint(0);
sequencer.setLoopEndPoint(-1);
sequencer.setLoopCount(Sequencer.LOOP_CONTINUOUSLY);
sequencer.setTempoInBPM(tempo);
}*/
sequencer.setTempoInBPM(tempo);
sequencer.start();
this.loop = loop;
} catch (InvalidMidiDataException ex) {
ex.printStackTrace();
} catch (MidiUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* This method is called by the sound system when a meta event occurs. In
* this case, when the end-of-track meta event is received, the sequence is
* restarted if looping is on.
*/
/*public void meta(MetaMessage event) {
if (event.getType() == END_OF_TRACK_MESSAGE) {
if (sequencer != null && sequencer.isOpen() && loop) {
sequencer.setMicrosecondPosition(0);
sequencer.setTempoInBPM(tempo);
sequencer.start();
}
}
}*/
/**
* Stops the sequencer and resets its position to the
* start of the sequence.
*/
public void stop() {
if (sequencer != null && sequencer.isOpen()) {
sequencer.stop();
sequencer.setMicrosecondPosition(0);
}
}
/**
* Closes the sequencer.
*/
public void close() {
if (sequencer != null && sequencer.isOpen()) {
sequencer.close();
}
}
/**
* Gets the sequencer.
*/
public Sequencer getSequencer() {
return sequencer;
}
/**
* Sets the paused state. Music may not immediately pause.
*/
public void setPaused(boolean paused) {
if (this.paused != paused && sequencer != null && sequencer.isOpen()) {
this.paused = paused;
if (paused) {
sequencer.stop();
} else {
sequencer.start();
}
}
}
/**
* Returns the paused state.
*/
public boolean isPaused() {
return paused;
}
} | NickLW/JamSS | src/uk/ac/brighton/jamss/MidiPlayer.java | Java | epl-1.0 | 4,026 |
/*******************************************************************************
* Copyright (c) 2000, 2008 IBM Corporation and others. All rights reserved.
* The contents of this file are made available under the terms
* of the GNU Lesser General Public License (LGPL) Version 2.1 that
* accompanies this distribution (lgpl-v21.txt). The LGPL is also
* available at http://www.gnu.org/licenses/lgpl.html. If the version
* of the LGPL at http://www.gnu.org is different to the version of
* the LGPL accompanying this distribution and there is any conflict
* between the two license versions, the terms of the LGPL accompanying
* this distribution shall govern.
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.swt.internal.gtk;
public class GtkFixed {
/** @field cast=(GList *) */
public long /*int*/ children;
}
| neelance/swt4ruby | swt4ruby/src/linux-x86_64/org/eclipse/swt/internal/gtk/GtkFixed.java | Java | epl-1.0 | 958 |
package org.allmyinfo.result;
import org.eclipse.jdt.annotation.NonNull;
public final class ValidStringResult implements StringResult
{
private final String value;
public ValidStringResult(final @NonNull String value)
{
this.value = value;
}
@Override
public boolean isPresent()
{
return true;
}
@Override
public boolean isValid()
{
return true;
}
@Override
public String getValue()
{
return value;
}
} | sschafer/atomic | org.allmyinfo.result/src/org/allmyinfo/result/ValidStringResult.java | Java | epl-1.0 | 432 |
/*******************************************************************************
* Copyright (C) 2007, Robin Rosenberg <robin.rosenberg@dewire.com>
* Copyright (C) 2006, Shawn O. Pearce <spearce@spearce.org>
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.eclipse.egit.core.test;
import java.net.URL;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.launching.JavaRuntime;
import org.osgi.framework.Bundle;
public class TestProject {
public IProject project;
public IJavaProject javaProject;
private IPackageFragmentRoot sourceFolder;
/**
* @throws CoreException
* If project already exists
*/
public TestProject() throws CoreException {
this(false);
}
/**
* @param remove
* should project be removed if already exists
* @throws CoreException
*/
public TestProject(final boolean remove) throws CoreException {
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
project = root.getProject("Project-1");
if (remove)
project.delete(true, null);
project.create(null);
project.open(null);
javaProject = JavaCore.create(project);
IFolder binFolder = createBinFolder();
setJavaNature();
javaProject.setRawClasspath(new IClasspathEntry[0], null);
createOutputFolder(binFolder);
addSystemLibraries();
}
public IProject getProject() {
return project;
}
public IJavaProject getJavaProject() {
return javaProject;
}
public void addJar(String plugin, String jar) throws JavaModelException {
Path result = findFileInPlugin(plugin, jar);
IClasspathEntry[] oldEntries = javaProject.getRawClasspath();
IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1];
System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length);
newEntries[oldEntries.length] = JavaCore.newLibraryEntry(result, null,
null);
javaProject.setRawClasspath(newEntries, null);
}
public IPackageFragment createPackage(String name) throws CoreException {
if (sourceFolder == null)
sourceFolder = createSourceFolder();
return sourceFolder.createPackageFragment(name, false, null);
}
public IType createType(IPackageFragment pack, String cuName, String source)
throws JavaModelException {
StringBuffer buf = new StringBuffer();
buf.append("package " + pack.getElementName() + ";\n");
buf.append("\n");
buf.append(source);
ICompilationUnit cu = pack.createCompilationUnit(cuName,
buf.toString(), false, null);
return cu.getTypes()[0];
}
public void dispose() throws CoreException {
waitForIndexer();
project.delete(true, true, null);
}
private IFolder createBinFolder() throws CoreException {
IFolder binFolder = project.getFolder("bin");
binFolder.create(false, true, null);
return binFolder;
}
private void setJavaNature() throws CoreException {
IProjectDescription description = project.getDescription();
description.setNatureIds(new String[] { JavaCore.NATURE_ID });
project.setDescription(description, null);
}
private void createOutputFolder(IFolder binFolder)
throws JavaModelException {
IPath outputLocation = binFolder.getFullPath();
javaProject.setOutputLocation(outputLocation, null);
}
public IPackageFragmentRoot createSourceFolder() throws CoreException {
IFolder folder = project.getFolder("src");
folder.create(false, true, null);
IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(folder);
IClasspathEntry[] oldEntries = javaProject.getRawClasspath();
IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1];
System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length);
newEntries[oldEntries.length] = JavaCore.newSourceEntry(root.getPath());
javaProject.setRawClasspath(newEntries, null);
return root;
}
private void addSystemLibraries() throws JavaModelException {
IClasspathEntry[] oldEntries = javaProject.getRawClasspath();
IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1];
System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length);
newEntries[oldEntries.length] = JavaRuntime
.getDefaultJREContainerEntry();
javaProject.setRawClasspath(newEntries, null);
}
private Path findFileInPlugin(String plugin, String file) {
Bundle bundle = Platform.getBundle(plugin);
URL resource = bundle.getResource(file);
return new Path(resource.getPath());
}
public void waitForIndexer() {
// new SearchEngine().searchAllTypeNames(ResourcesPlugin.getWorkspace(),
// null, null, IJavaSearchConstants.EXACT_MATCH,
// IJavaSearchConstants.CASE_SENSITIVE,
// IJavaSearchConstants.CLASS, SearchEngine
// .createJavaSearchScope(new IJavaElement[0]),
// new ITypeNameRequestor() {
// public void acceptClass(char[] packageName,
// char[] simpleTypeName, char[][] enclosingTypeNames,
// String path) {
// }
// public void acceptInterface(char[] packageName,
// char[] simpleTypeName, char[][] enclosingTypeNames,
// String path) {
// }
// }, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null);
}
/**
* @return Returns the sourceFolder.
*/
public IPackageFragmentRoot getSourceFolder() {
return sourceFolder;
}
/**
* @param sourceFolder The sourceFolder to set.
*/
public void setSourceFolder(IPackageFragmentRoot sourceFolder) {
this.sourceFolder = sourceFolder;
}
}
| spearce/egit | org.eclipse.egit.core.test/src/org/eclipse/egit/core/test/TestProject.java | Java | epl-1.0 | 6,918 |
/*
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* SEARCH Group, Incorporated - initial API and implementation
*
*/
package org.search.niem.uml.ui.acceptance_tests;
import static org.search.niem.uml.ui.util.UIExt.select;
import org.eclipse.jface.window.IShellProvider;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
public class UIUtils {
public static IWorkbench get_the_workbench() {
return PlatformUI.getWorkbench();
}
public static IWorkbenchWindow get_the_active_workbench_window() {
return get_the_workbench().getActiveWorkbenchWindow();
}
public static IWorkbenchPage get_the_active_workbench_page() {
return get_the_active_workbench_window().getActivePage();
}
public static IEditorPart get_the_active_editor() {
return get_the_active_workbench_page().getActiveEditor();
}
@SuppressWarnings("unchecked")
private static <V extends IViewPart> V find_the_view(final String id) {
for (final IWorkbenchPage p : get_the_active_workbench_window().getPages()) {
final IViewPart view = p.findView(id);
if (view != null) {
return (V) view;
}
}
return null;
}
@SuppressWarnings("unchecked")
public static <V extends IViewPart> V activate_the_view(final String id) throws PartInitException {
final IViewPart theView = find_the_view(id);
if (theView == null) {
return (V) get_the_active_workbench_page().showView(id);
}
theView.setFocus();
return (V) theView;
}
public static void close_all_open_editors() {
for (final IWorkbenchWindow w : get_the_workbench().getWorkbenchWindows()) {
for (final IWorkbenchPage p : w.getPages()) {
p.closeAllEditors(false);
}
}
}
public static void select_the_default_button(final IShellProvider provider) {
select(provider.getShell().getDefaultButton());
}
}
| info-sharing-environment/NIEM-Modeling-Tool | plugins/org.search.niem.uml.ui.acceptance_tests/src/test/java/org/search/niem/uml/ui/acceptance_tests/UIUtils.java | Java | epl-1.0 | 2,407 |
module.exports = function(context) {
const fs = require('fs');
const cordova_util = context.requireCordovaModule('cordova-lib/src/cordova/util');
let projectRoot = cordova_util.isCordova();
let configXML = cordova_util.projectConfig(projectRoot);
let data = fs.readFileSync(configXML, 'utf8');
for (var envVar in process.env) {
data = data.replace('$' + envVar, process.env[envVar]);
}
fs.writeFileSync(configXML, data, 'utf8');
};
| eclipsesource/tabris-js-hello-world | cordova/scripts/replace-config-env-vars.js | JavaScript | epl-1.0 | 454 |
/**
* Copyright 2009-2016 Université Paris Ouest and Sorbonne Universités,
Univ. Paris 06 - CNRS UMR 7606 (LIP6)
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Project leader / Initial Contributor:
* Lom Messan Hillah - <lom-messan.hillah@lip6.fr>
*
* Contributors:
* ${ocontributors} - <$oemails}>
*
* Mailing list:
* lom-messan.hillah@lip6.fr
*/
/**
* (C) Sorbonne Universités, UPMC Univ Paris 06, UMR CNRS 7606 (LIP6/MoVe)
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Lom HILLAH (LIP6) - Initial models and implementation
* Rachid Alahyane (UPMC) - Infrastructure and continuous integration
* Bastien Bouzerau (UPMC) - Architecture
* Guillaume Giffo (UPMC) - Code generation refactoring, High-level API
*/
package fr.lip6.move.pnml.symmetricnet.dots.impl;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.List;
import org.apache.axiom.om.OMElement;
import org.eclipse.emf.common.util.DiagnosticChain;
import org.eclipse.emf.ecore.EClass;
import fr.lip6.move.pnml.framework.general.PnmlExport;
import fr.lip6.move.pnml.framework.utils.IdRefLinker;
import fr.lip6.move.pnml.framework.utils.ModelRepository;
import fr.lip6.move.pnml.framework.utils.PNMLEncoding;
import fr.lip6.move.pnml.framework.utils.PrettyPrintData;
import fr.lip6.move.pnml.framework.utils.exception.InnerBuildException;
import fr.lip6.move.pnml.framework.utils.exception.InvalidIDException;
import fr.lip6.move.pnml.framework.utils.exception.VoidRepositoryException;
import fr.lip6.move.pnml.symmetricnet.dots.Dot;
import fr.lip6.move.pnml.symmetricnet.dots.DotsFactory;
import fr.lip6.move.pnml.symmetricnet.dots.DotsPackage;
import fr.lip6.move.pnml.symmetricnet.terms.Sort;
import fr.lip6.move.pnml.symmetricnet.terms.impl.BuiltInSortImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Dot</b></em>'.
* <!-- end-user-doc -->
* <p>
* </p>
*
* @generated
*/
public class DotImpl extends BuiltInSortImpl implements Dot {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected DotImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return DotsPackage.Literals.DOT;
}
/**
* Return the string containing the pnml output
*/
@Override
public String toPNML() {
//id 0
//idref 0
//attributes 0
//sons 0
Boolean prettyPrintStatus = ModelRepository.getInstance().isPrettyPrintActive();
String retline = "";
String headline = "";
PrettyPrintData prpd = null;
if (prettyPrintStatus) {
retline = "\n";
prpd = ModelRepository.getInstance().getPrettyPrintData();
headline = prpd.getCurrentLineHeader();
}
StringBuilder sb = new StringBuilder();
sb.append(headline);
sb.append("<dot");
if (prettyPrintStatus) {
headline = prpd.increaseLineHeaderLevel();
}
//begin attributes, id and id ref processing
sb.append("/>");
sb.append(retline);
//sons, follow processing
/****/
if (prettyPrintStatus) {
headline = prpd.decreaseLineHeaderLevel();
}
return sb.toString();
}
@Override
@SuppressWarnings("unchecked")
public void fromPNML(OMElement locRoot, IdRefLinker idr) throws InnerBuildException, InvalidIDException,
VoidRepositoryException {
//0
//0
//0
//0
@SuppressWarnings("unused")
DotsFactory fact = DotsFactory.eINSTANCE;
//processing id
//processing idref
//processing attributes
//processing sons
}
/**
* Return the string containing the pnml output
*/
@Override
public void toPNML(FileChannel fc) {
//id 0
//idref 0
//attributes 0
//sons 0
final int bufferSizeKB = 8;
final int bufferSize = bufferSizeKB * 1024;
final ByteBuffer bytebuf = ByteBuffer.allocateDirect(bufferSize);
final String charsetEncoding = PNMLEncoding.UTF_8.getName();
Boolean prettyPrintStatus = ModelRepository.getInstance().isPrettyPrintActive();
String retline = "";
String headline = "";
PrettyPrintData prpd = null;
if (prettyPrintStatus) {
retline = "\n";
prpd = ModelRepository.getInstance().getPrettyPrintData();
headline = prpd.getCurrentLineHeader();
}
StringBuilder sb = new StringBuilder();
sb.append(headline);
sb.append("<dot");
if (prettyPrintStatus) {
headline = prpd.increaseLineHeaderLevel();
}
//begin attributes, id and id ref processing
sb.append("/>");
sb.append(retline);
//sons, follow processing
/****/
if (prettyPrintStatus) {
headline = prpd.decreaseLineHeaderLevel();
}
try {
writeIntoStream(bytebuf, fc, sb.toString().getBytes(Charset.forName(charsetEncoding)));
} catch (IOException io) {
io.printStackTrace();
// fail fast
return;
}
sb = null;
}
/**
* Writes buffer of a given max size into file channel.
*/
private static final void writeIntoStream(final ByteBuffer bytebuf, final FileChannel fc, final byte[] contents)
throws IOException {
final int chopSize = 6 * 1024;
if (contents.length >= bytebuf.capacity()) {
List<byte[]> chops = PnmlExport.chopBytes(contents, chopSize);
for (byte[] buf : chops) {
bytebuf.put(buf);
bytebuf.flip();
fc.write(bytebuf);
bytebuf.clear();
}
} else {
bytebuf.put(contents);
bytebuf.flip();
fc.write(bytebuf);
bytebuf.clear();
}
}
/**
* -
*/
@Override
public boolean validateOCL(DiagnosticChain diagnostics) {
//this package has no validator class
return true;
}
@Override
public boolean equalSorts(Sort sort) {
boolean isEqual = false;
if (this.eClass().getName().equalsIgnoreCase(sort.eClass().getName())) {
//by default they are the same sort, unless they have been named.
isEqual = true;
if (this.getContainerNamedSort() != null && sort.getContainerNamedSort() != null) {
// we test them if they have been explicitly named.
isEqual = this.getContainerNamedSort().getName()
.equalsIgnoreCase(sort.getContainerNamedSort().getName());
}// otherwise, keep the default.
}
return isEqual;
}
} //DotImpl
| lhillah/pnmlframework | pnmlFw-SNNet/src/fr/lip6/move/pnml/symmetricnet/dots/impl/DotImpl.java | Java | epl-1.0 | 6,595 |
/**
*
*/
package com.eclipsesource.gerrit.plugins.fileattachment.api.entities;
/**
* Represents an JSON entity that is passed between the client and the server.
* This is the base interface that should be used for all JSON entities.
*
* @author Florian Zoubek
*
*/
public interface JsonEntity {
}
| theArchonius/gerrit-attachments | src/main/java/com/eclipsesource/gerrit/plugins/fileattachment/api/entities/JsonEntity.java | Java | epl-1.0 | 308 |
/*
* Copyright (c) 2012-2018 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.plugin.debugger.ide.configuration;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import org.eclipse.che.ide.api.action.ActionManager;
import org.eclipse.che.ide.api.action.DefaultActionGroup;
import org.eclipse.che.ide.api.debug.DebugConfiguration;
import org.eclipse.che.ide.api.debug.DebugConfigurationsManager;
import org.eclipse.che.ide.api.debug.DebugConfigurationsManager.ConfigurationChangedListener;
/**
* Group of {@link DebugConfigurationAction}s.
*
* @author Artem Zatsarynnyi
*/
@Singleton
public class DebugConfigurationsGroup extends DefaultActionGroup
implements ConfigurationChangedListener {
private final DebugConfigurationsManager configurationsManager;
private final DebugConfigurationActionFactory debugConfigurationActionFactory;
@Inject
public DebugConfigurationsGroup(
ActionManager actionManager,
DebugConfigurationsManager debugConfigurationsManager,
DebugConfigurationActionFactory debugConfigurationActionFactory) {
super(actionManager);
configurationsManager = debugConfigurationsManager;
this.debugConfigurationActionFactory = debugConfigurationActionFactory;
debugConfigurationsManager.addConfigurationsChangedListener(this);
fillActions();
}
@Override
public void onConfigurationAdded(DebugConfiguration configuration) {
fillActions();
}
@Override
public void onConfigurationRemoved(DebugConfiguration configuration) {
fillActions();
}
private void fillActions() {
removeAll();
for (DebugConfiguration configuration : configurationsManager.getConfigurations()) {
add(debugConfigurationActionFactory.createAction(configuration));
}
}
}
| sleshchenko/che | plugins/plugin-debugger/che-plugin-debugger-ide/src/main/java/org/eclipse/che/plugin/debugger/ide/configuration/DebugConfigurationsGroup.java | Java | epl-1.0 | 2,088 |
/**
* Copyright (c) 2016-2019 by the respective copyright holders.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package com.zsmartsystems.zigbee.console.ember;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import com.zsmartsystems.zigbee.ZigBeeNetworkManager;
import com.zsmartsystems.zigbee.dongle.ember.EmberNcp;
import com.zsmartsystems.zigbee.dongle.ember.ezsp.structure.EzspStatus;
import com.zsmartsystems.zigbee.dongle.ember.ezsp.structure.EzspValueId;
/**
* Reads or writes an NCP {@link EzspValueId}
*
* @author Chris Jackson
*
*/
public class EmberConsoleNcpValueCommand extends EmberConsoleAbstractCommand {
@Override
public String getCommand() {
return "ncpvalue";
}
@Override
public String getDescription() {
return "Read or write an NCP memory value";
}
@Override
public String getSyntax() {
return "[VALUEID] [VALUE]";
}
@Override
public String getHelp() {
return "VALUEID is the Ember NCP value enumeration\n" + "VALUE is the value to write\n"
+ "If VALUE is not defined, then the memory will be read.\n"
+ "If no arguments are supplied then all values will be displayed.";
}
@Override
public void process(ZigBeeNetworkManager networkManager, String[] args, PrintStream out)
throws IllegalArgumentException {
if (args.length > 3) {
throw new IllegalArgumentException("Incorrect number of arguments.");
}
EmberNcp ncp = getEmberNcp(networkManager);
if (args.length == 1) {
Map<EzspValueId, int[]> values = new TreeMap<>();
for (EzspValueId valueId : EzspValueId.values()) {
if (valueId == EzspValueId.UNKNOWN) {
continue;
}
values.put(valueId, ncp.getValue(valueId));
}
for (Entry<EzspValueId, int[]> value : values.entrySet()) {
out.print(String.format("%-50s", value.getKey()));
if (value.getValue() != null) {
out.print(displayValue(value.getKey(), value.getValue()));
}
out.println();
}
return;
}
EzspValueId valueId = EzspValueId.valueOf(args[1].toUpperCase());
if (args.length == 2) {
int[] value = ncp.getValue(valueId);
if (value == null) {
out.println("Error reading Ember NCP value " + valueId.toString());
} else {
out.println("Ember NCP value " + valueId.toString() + " is " + displayValue(valueId, value));
}
} else {
int[] value = parseInput(valueId, Arrays.copyOfRange(args, 2, args.length));
if (value == null) {
throw new IllegalArgumentException("Unable to convert data to value array");
}
EzspStatus response = ncp.setValue(valueId, value);
out.println("Writing Ember NCP value " + valueId.toString() + " was "
+ (response == EzspStatus.EZSP_SUCCESS ? "" : "un") + "successful.");
}
}
private String displayValue(EzspValueId valueId, int[] value) {
StringBuilder builder = new StringBuilder();
switch (valueId) {
default:
boolean first = true;
for (int intVal : value) {
if (!first) {
builder.append(' ');
}
first = false;
builder.append(String.format("%02X", intVal));
}
break;
}
return builder.toString();
}
private int[] parseInput(EzspValueId valueId, String[] args) {
int[] value = null;
switch (valueId) {
case EZSP_VALUE_APS_FRAME_COUNTER:
case EZSP_VALUE_NWK_FRAME_COUNTER:
Long longValue = Long.parseLong(args[0]);
value = new int[4];
value[0] = (int) (longValue & 0x000000FF);
value[1] = (int) (longValue & 0x0000FF00) >> 8;
value[2] = (int) (longValue & 0x00FF0000) >> 16;
value[3] = (int) (longValue & 0xFF000000) >> 24;
break;
default:
break;
}
return value;
}
}
| cschwer/com.zsmartsystems.zigbee | com.zsmartsystems.zigbee.console.ember/src/main/java/com/zsmartsystems/zigbee/console/ember/EmberConsoleNcpValueCommand.java | Java | epl-1.0 | 4,666 |
/*******************************************************************************
* <copyright> Copyright (c) 2014 - 2021 Bauhaus Luftfahrt e.V.. All rights reserved. This program and the accompanying
* materials are made available under the terms of the GNU General Public License v3.0 which accompanies this distribution,
* and is available at https://www.gnu.org/licenses/gpl-3.0.html.en </copyright>
*******************************************************************************/
package com.paxelerate.execution.actions;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.paxelerate.core.simulation.astar.SimulationHandler;
import com.paxelerate.model.Deck;
import com.paxelerate.model.Model;
import com.paxelerate.model.ModelFactory;
import com.paxelerate.model.SimulationResult;
import com.paxelerate.model.agent.Passenger;
import net.bhl.opensource.toolbox.time.TimeHelper;
/**
* @author Michael.Schmidt, Marc.Engelmann
* @since 22.08.2019
*
*/
public class ExportResultsAction {
/**
*
* @param handler
* @param cabin
* @param boardingStatus
* @param time
* @param simulationTime
*/
static void setSimulationData(SimulationHandler handler, Model model, List<ArrayList<Integer>> boardingStatus,
double time, double simulationTime) {
Deck deck = model.getDeck();
SimulationResult result = ModelFactory.eINSTANCE.createSimulationResult();
model.getSimulationResults().add(result);
result.setPassengers(deck.getPassengers().size());
result.setBoardingTime(
handler.getMasterBoardingTime() * model.getSettings().getSimulationSpeedFactor() / 1000.0);
result.setSimulationTime(simulationTime);
result.setId(model.getSimulationResults().size() + 1);
result.setName(new SimpleDateFormat("dd.MM, HH:mm").format(new Date()));
result.setDate(new Date());
result.setBoardingTimeString(TimeHelper.toTimeOfDay(time));
result.setWaymakingCompleted(handler.getPassengersByState(null, true).stream()
.mapToInt(Passenger::getNumberOfMakeWayOperations).sum());
result.setLayoutConceptType(model.getSettings().getSeatType());
// result.setLuggageStorageFillingDegree(deck.getLuggageStorages().stream()
// .mapToDouble(s -> 100 - s.getFreeVolume() * 100 / s.getNetVolume()).average().orElse(0));
// TODO: WRONG!
// r.setTotalLargeBagsStowed(deck.getLuggageStorages().stream().mapToInt(l -> l.getMaximumLargeBags()).sum());
// result.setTotalStorageVolume(
// deck.getLuggageStorages().stream().mapToDouble(LuggageStorage::getNetVolume).sum());
result.setAverageNumberOfActivePassengers(
(int) boardingStatus.stream().mapToDouble(l -> l.get(2)).average().orElse(0));
result.setMaxNumberOfActivePassengers(boardingStatus.stream().mapToInt(l -> l.get(2)).max().orElse(0));
result.setAverageNumberOfBags(
deck.getPassengers().stream().mapToDouble(p -> p.getLuggage().size()).average().orElse(0));
}
}
| BauhausLuftfahrt/PAXelerate | com.paxelerate.execution/src/com/paxelerate/execution/actions/ExportResultsAction.java | Java | epl-1.0 | 2,961 |
/*******************************************************************************
* Copyright (c) 2014 UT-Battelle, LLC.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Initial API and implementation and/or initial documentation - Jay Jay Billings,
* Jordan H. Deyton, Dasha Gorin, Alexander J. McCaskey, Taylor Patterson,
* Claire Saunders, Matthew Wang, Anna Wojtowicz
*******************************************************************************/
package org.eclipse.ice.datastructures.form;
import java.util.ArrayList;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import org.eclipse.ice.datastructures.ICEObject.Component;
import org.eclipse.ice.datastructures.ICEObject.ICEObject;
import org.eclipse.ice.datastructures.componentVisitor.IComponentVisitor;
import org.eclipse.ice.viz.service.datastructures.IVizUpdateable;
import org.eclipse.ice.viz.service.datastructures.IVizUpdateableListener;
import org.eclipse.ice.viz.service.mesh.datastructures.Edge;
import org.eclipse.ice.viz.service.mesh.datastructures.IMeshPart;
import org.eclipse.ice.viz.service.mesh.datastructures.IMeshPartVisitor;
import org.eclipse.ice.viz.service.mesh.datastructures.Polygon;
import org.eclipse.ice.viz.service.mesh.datastructures.Vertex;
import org.eclipse.ice.viz.service.mesh.datastructures.VizMeshComponent;
/**
* <p>
* A wrapper class for a VizMeshComponent. It provides all the functionality of
* a VizMeshComponent, but delegates to a wrapped VizMeshComponent for all
* actual implementations.
* </p>
*
* @author Jordan H. Deyton
* @author Robert Smith
*/
@XmlRootElement(name = "MeshComponent")
@XmlAccessorType(XmlAccessType.FIELD)
public class MeshComponent extends ICEObject implements Component, IMeshPart,
IVizUpdateableListener {
/**
* The wrapped VizMeshComponent.
*/
private VizMeshComponent mesh;
/**
* <p>
* The default constructor for a MeshComponent. Initializes the list of
* polygons and any associated bookkeeping structures.
* </p>
*
*/
public MeshComponent() {
super();
mesh = new VizMeshComponent();
mesh.register(this);
return;
}
/**
* Getter method for the wrapped VizMeshComponent
*
* @return The wrapped VizMeshComponent
*/
public VizMeshComponent getMesh() {
return mesh;
}
/**
* Setter method for the wrapped VizMeshComponent
*
* @param newMesh
* The new mesh to hold
*/
public void setMesh(VizMeshComponent newMesh) {
mesh = newMesh;
}
/**
* <p>
* Adds a polygon to the MeshComponent. The polygon is expected to have a
* unique polygon ID. If the polygon can be added, a notification is sent to
* listeners. If the polygon uses equivalent vertices or edges with
* different references, then a new polygon is created with references to
* the vertices and edges already known by this MeshComponent.
* </p>
*
* @param polygon
* <p>
* The new polygon to add to the existing list.
* </p>
*/
public void addPolygon(Polygon polygon) {
mesh.addPolygon(polygon);
notifyListeners();
return;
}
/**
* <p>
* Removes a polygon from the MeshComponent. This will also remove any
* vertices and edges used only by this polygon. If a polygon was removed, a
* notification is sent to listeners.
* </p>
*
* @param id
* <p>
* The ID of the polygon to remove from the existing list.
* </p>
*/
public void removePolygon(int id) {
mesh.removePolygon(id);
notifyListeners();
return;
}
/**
* <p>
* Removes a list polygons from the MeshComponent. This will also remove any
* vertices and edges used by these polygons. If a polygon was removed, a
* notification is sent to listeners.
* </p>
*
* @param ids
* <p>
* An ArrayList containing the IDs of the polygons to remove from
* the MeshComponent.
* </p>
*/
public void removePolygons(ArrayList<Integer> ids) {
mesh.removePolygons(ids);
notifyListeners();
return;
}
/**
* <p>
* Gets a list of all polygons stored in the MeshComponent ordered by their
* IDs.
* </p>
*
* @return <p>
* A list of polygons contained in this MeshComponent.
* </p>
*/
public ArrayList<Polygon> getPolygons() {
return mesh.getPolygons();
}
/**
* <p>
* Gets a Polygon instance corresponding to an ID.
* </p>
*
* @param id
* <p>
* The ID of the polygon.
* </p>
* @return <p>
* The polygon referred to by the ID, or null if there is no polygon
* with the ID.
* </p>
*/
public Polygon getPolygon(int id) {
return mesh.getPolygon(id);
}
/**
* <p>
* Returns the next available ID for polygons.
* </p>
*
* @return <p>
* The greatest polygon ID (or zero) plus one.
* </p>
*/
public int getNextPolygonId() {
return mesh.getNextPolygonId();
}
/**
* <p>
* Sets the list of all polygons stored in the MeshComponent.
* </p>
*
* @param polygons
* <p>
* The list of polygons to replace the existing list of polygons
* in the MeshComponent.
* </p>
*/
public void setPolygons(ArrayList<Polygon> polygons) {
mesh.setPolygons(polygons);
}
/**
* <p>
* Gets a list of all vertices associated with this MeshComponent.
* </p>
*
* @return <p>
* All vertices managed by this MeshComponent.
* </p>
*/
public ArrayList<Vertex> getVertices() {
return mesh.getVertices();
}
/**
* <p>
* Gets a Vertex instance corresponding to an ID.
* </p>
*
* @param id
* <p>
* The ID of the vertex.
* </p>
* @return <p>
* The vertex referred to by the ID, or null if the ID is invalid.
* </p>
*/
public Vertex getVertex(int id) {
return mesh.getVertex(id);
}
/**
* <p>
* Returns the next available ID for vertices.
* </p>
*
* @return <p>
* The greatest vertex ID (or zero) plus one.
* </p>
*/
public int getNextVertexId() {
return mesh.getNextVertexId();
}
/**
* <p>
* Gets a list of all edges associated with this MeshComponent.
* </p>
*
* @return <p>
* All edges managed by this MeshComponent.
* </p>
*/
public ArrayList<Edge> getEdges() {
return mesh.getEdges();
}
/**
* <p>
* Gets an Edge instance corresponding to an ID.
* </p>
*
* @param id
* <p>
* The ID of the edge.
* </p>
* @return <p>
* The edge referred to by the ID, or null if the ID is invalid.
* </p>
*/
public Edge getEdge(int id) {
return mesh.getEdge(id);
}
/**
* <p>
* Returns the next available ID for edges.
* </p>
*
* @return <p>
* The greatest edge ID (or zero) plus one.
* </p>
*/
public int getNextEdgeId() {
return mesh.getNextEdgeId();
}
/**
* <p>
* Returns a list of Edges attached to the Vertex with the specified ID.
* </p>
*
* @param id
* <p>
* The ID of the vertex.
* </p>
* @return <p>
* An ArrayList of Edges that are attached to the vertex with the
* specified ID. If there are no such edges, e.g., if the vertex ID
* is invalid, the list will be empty.
* </p>
*/
public ArrayList<Edge> getEdgesFromVertex(int id) {
return getEdgesFromVertex(id);
}
/**
* <p>
* Returns a list of Polygons containing the Vertex with the specified ID.
* </p>
*
* @param id
* <p>
* The ID of the vertex.
* </p>
* @return <p>
* An ArrayList of Polygons that contain the vertex with the
* specified ID. If there are no such polygons, e.g., if the vertex
* ID is invalid, the list will be empty.
* </p>
*/
public ArrayList<Polygon> getPolygonsFromVertex(int id) {
return mesh.getPolygonsFromVertex(id);
}
/**
* <p>
* Returns a list of Polygons containing the Edge with the specified ID.
* </p>
*
* @param id
* <p>
* The ID of the edge.
* </p>
* @return <p>
* An ArrayList of Polygons that contain the edge with the specified
* ID. If there are no such polygons, e.g., if the edge ID is
* invalid, the list will be empty.
* </p>
*/
public ArrayList<Polygon> getPolygonsFromEdge(int id) {
return mesh.getPolygonsFromEdge(id);
}
/**
* <p>
* Returns an Edge that connects two specified vertices if one exists.
* </p>
*
* @param firstId
* <p>
* The ID of the first vertex.
* </p>
* @param secondId
* <p>
* The ID of the second vertex.
* </p>
*
* @return <p>
* An Edge instance that connects the first and second vertices, or
* null if no such edge exists.
* </p>
*/
public Edge getEdgeFromVertices(int firstId, int secondId) {
return mesh.getEdgeFromVertices(firstId, secondId);
}
/**
* <p>
* Returns a list containing all Polygons in the MeshComponent whose
* vertices are a subset of the supplied list of vertices.
* </p>
*
* @param vertices
* <p>
* A collection of vertices.
* </p>
* @return <p>
* An ArrayList of all Polygons in the MeshComponent that are
* composed of some subset of the specified vertices.
* </p>
*/
public ArrayList<Polygon> getPolygonsFromVertices(ArrayList<Vertex> vertices) {
return mesh.getPolygonsFromVertices(vertices);
}
/**
* <p>
* This operation returns the hash value of the MeshComponent.
* </p>
*
* @return <p>
* The hashcode of the ICEObject.
* </p>
*/
@Override
public int hashCode() {
return mesh.hashCode();
}
/**
* <p>
* This operation is used to check equality between this MeshComponent and
* another MeshComponent. It returns true if the MeshComponents are equal
* and false if they are not.
* </p>
*
* @param otherObject
* <p>
* The other ICEObject that should be compared with this one.
* </p>
* @return <p>
* True if the ICEObjects are equal, false otherwise.
* </p>
*/
@Override
public boolean equals(Object otherObject) {
// By default, the objects are not equivalent.
boolean equals = false;
// Check the reference.
if (this == otherObject) {
equals = true;
}
// Check the information stored in the other object.
else if (otherObject != null && otherObject instanceof MeshComponent) {
// We can now cast the other object.
MeshComponent component = (MeshComponent) otherObject;
// Compare the values between the two objects.
equals = (super.equals(otherObject) && mesh.equals(component.mesh));
// The polygons are the only defining feature of the MeshComponent
// (aside from the super properties). If the polygon lists are
// equivalent, we can safely expect the other bookkeeping structures
// are identical.
}
return equals;
}
/**
* <p>
* This operation copies the contents of a MeshComponent into the current
* object using a deep copy.
* </p>
*
* @param component
* <p>
* The ICEObject from which the values should be copied
* </p>
*/
public void copy(MeshComponent component) {
// Check the parameters.
if (component != null) {
super.copy(component);
mesh.copy(component.mesh);
notifyListeners();
}
return;
}
/**
* <p>
* This operation returns a clone of the MeshComponent using a deep copy.
* </p>
*
* @return <p>
* The new clone
* </p>
*/
@Override
public Object clone() {
// Initialize a new object.
MeshComponent object = new MeshComponent();
// Copy the contents from this one.
object.copy(this);
// Return the newly instantiated object.
return object;
}
/**
* (non-Javadoc)
*
* @see Component#accept(IComponentVisitor visitor)
*/
@Override
public void accept(IComponentVisitor visitor) {
// Call the visitor's visit(MeshComponent) method.
if (visitor != null) {
visitor.visit(this);
}
return;
}
/**
* <p>
* This method calls the {@link IMeshPartVisitor}'s visit method.
* </p>
*
* @param visitor
* <p>
* The {@link IMeshPartVisitor} that is visiting this
* {@link IMeshPart}.
* </p>
*/
@Override
public void acceptMeshVisitor(IMeshPartVisitor visitor) {
if (visitor != null) {
visitor.visit(this);
}
return;
}
@Override
public void update(IVizUpdateable component) {
notifyListeners();
}
} | gorindn/ice | src/org.eclipse.ice.datastructures/src/org/eclipse/ice/datastructures/form/MeshComponent.java | Java | epl-1.0 | 13,129 |
package org.eclipse.jet.compiled;
import org.eclipse.jet.JET2Context;
import org.eclipse.jet.JET2Template;
import org.eclipse.jet.JET2Writer;
import org.eclipse.jet.taglib.RuntimeTagElement;
import org.eclipse.jet.taglib.TagInfo;
public class _jet_Erroresql_0 implements JET2Template {
private static final String _jetns_c = "org.eclipse.jet.controlTags"; //$NON-NLS-1$
public _jet_Erroresql_0() {
super();
}
private static final String NL = System.getProperty("line.separator"); //$NON-NLS-1$
private static final TagInfo _td_c_if_5_1 = new TagInfo("c:if", //$NON-NLS-1$
5, 1,
new String[] {
"test", //$NON-NLS-1$
},
new String[] {
"boolean($root/brokerSchema)", //$NON-NLS-1$
} );
private static final TagInfo _td_c_if_7_1 = new TagInfo("c:if", //$NON-NLS-1$
7, 1,
new String[] {
"test", //$NON-NLS-1$
},
new String[] {
"string-length($root/brokerSchema) > 0", //$NON-NLS-1$
} );
private static final TagInfo _td_c_get_9_15 = new TagInfo("c:get", //$NON-NLS-1$
9, 15,
new String[] {
"select", //$NON-NLS-1$
},
new String[] {
"$root/brokerSchema", //$NON-NLS-1$
} );
private static final TagInfo _td_c_get_12_18 = new TagInfo("c:get", //$NON-NLS-1$
12, 18,
new String[] {
"select", //$NON-NLS-1$
},
new String[] {
"$root/@patternName", //$NON-NLS-1$
} );
private static final TagInfo _td_c_get_12_63 = new TagInfo("c:get", //$NON-NLS-1$
12, 63,
new String[] {
"select", //$NON-NLS-1$
},
new String[] {
"$root/@patternVersion", //$NON-NLS-1$
} );
private static final TagInfo _td_c_get_13_23 = new TagInfo("c:get", //$NON-NLS-1$
13, 23,
new String[] {
"select", //$NON-NLS-1$
},
new String[] {
"$root/@patternName", //$NON-NLS-1$
} );
private static final TagInfo _td_c_get_14_26 = new TagInfo("c:get", //$NON-NLS-1$
14, 26,
new String[] {
"select", //$NON-NLS-1$
},
new String[] {
"$root/@patternVersion", //$NON-NLS-1$
} );
public void generate(final JET2Context context, final JET2Writer __out) {
JET2Writer out = __out;
com.ibm.etools.mft.pattern.sen.plugin.PatternPlugin pattern = com.ibm.etools.mft.pattern.sen.plugin.PatternPlugin.getInstance();
com.ibm.etools.mft.pattern.sen.sf.onewayackmq.PatternMessages messages = new com.ibm.etools.mft.pattern.sen.sf.onewayackmq.PatternMessages();
RuntimeTagElement _jettag_c_if_5_1 = context.getTagFactory().createRuntimeTag(_jetns_c, "if", "c:if", _td_c_if_5_1); //$NON-NLS-1$ //$NON-NLS-2$
_jettag_c_if_5_1.setRuntimeParent(null);
_jettag_c_if_5_1.setTagInfo(_td_c_if_5_1);
_jettag_c_if_5_1.doStart(context, out);
while (_jettag_c_if_5_1.okToProcessBody()) {
// Tag exists
RuntimeTagElement _jettag_c_if_7_1 = context.getTagFactory().createRuntimeTag(_jetns_c, "if", "c:if", _td_c_if_7_1); //$NON-NLS-1$ //$NON-NLS-2$
_jettag_c_if_7_1.setRuntimeParent(_jettag_c_if_5_1);
_jettag_c_if_7_1.setTagInfo(_td_c_if_7_1);
_jettag_c_if_7_1.doStart(context, out);
while (_jettag_c_if_7_1.okToProcessBody()) {
// and has a value
out.write("BROKER SCHEMA "); //$NON-NLS-1$
RuntimeTagElement _jettag_c_get_9_15 = context.getTagFactory().createRuntimeTag(_jetns_c, "get", "c:get", _td_c_get_9_15); //$NON-NLS-1$ //$NON-NLS-2$
_jettag_c_get_9_15.setRuntimeParent(_jettag_c_if_7_1);
_jettag_c_get_9_15.setTagInfo(_td_c_get_9_15);
_jettag_c_get_9_15.doStart(context, out);
_jettag_c_get_9_15.doEnd();
out.write(NL);
_jettag_c_if_7_1.handleBodyContent(out);
}
_jettag_c_if_7_1.doEnd();
_jettag_c_if_5_1.handleBodyContent(out);
}
_jettag_c_if_5_1.doEnd();
out.write("-- Generated by "); //$NON-NLS-1$
RuntimeTagElement _jettag_c_get_12_18 = context.getTagFactory().createRuntimeTag(_jetns_c, "get", "c:get", _td_c_get_12_18); //$NON-NLS-1$ //$NON-NLS-2$
_jettag_c_get_12_18.setRuntimeParent(null);
_jettag_c_get_12_18.setTagInfo(_td_c_get_12_18);
_jettag_c_get_12_18.doStart(context, out);
_jettag_c_get_12_18.doEnd();
out.write(" Version "); //$NON-NLS-1$
RuntimeTagElement _jettag_c_get_12_63 = context.getTagFactory().createRuntimeTag(_jetns_c, "get", "c:get", _td_c_get_12_63); //$NON-NLS-1$ //$NON-NLS-2$
_jettag_c_get_12_63.setRuntimeParent(null);
_jettag_c_get_12_63.setTagInfo(_td_c_get_12_63);
_jettag_c_get_12_63.doStart(context, out);
_jettag_c_get_12_63.doEnd();
out.write(NL);
out.write("-- $MQSI patternName="); //$NON-NLS-1$
RuntimeTagElement _jettag_c_get_13_23 = context.getTagFactory().createRuntimeTag(_jetns_c, "get", "c:get", _td_c_get_13_23); //$NON-NLS-1$ //$NON-NLS-2$
_jettag_c_get_13_23.setRuntimeParent(null);
_jettag_c_get_13_23.setTagInfo(_td_c_get_13_23);
_jettag_c_get_13_23.doStart(context, out);
_jettag_c_get_13_23.doEnd();
out.write(" MQSI$"); //$NON-NLS-1$
out.write(NL);
out.write("-- $MQSI patternVersion="); //$NON-NLS-1$
RuntimeTagElement _jettag_c_get_14_26 = context.getTagFactory().createRuntimeTag(_jetns_c, "get", "c:get", _td_c_get_14_26); //$NON-NLS-1$ //$NON-NLS-2$
_jettag_c_get_14_26.setRuntimeParent(null);
_jettag_c_get_14_26.setTagInfo(_td_c_get_14_26);
_jettag_c_get_14_26.doStart(context, out);
_jettag_c_get_14_26.doEnd();
out.write(" MQSI$"); //$NON-NLS-1$
out.write(NL);
out.write(NL);
out.write("DECLARE ErrorLoggingOn EXTERNAL BOOLEAN TRUE;"); //$NON-NLS-1$
out.write(NL);
out.write(NL);
out.write("CREATE COMPUTE MODULE SF_Build_Error_Message"); //$NON-NLS-1$
out.write(NL);
out.write("\tCREATE FUNCTION Main() RETURNS BOOLEAN"); //$NON-NLS-1$
out.write(NL);
out.write("\tBEGIN"); //$NON-NLS-1$
out.write(NL);
out.write("\tSET OutputRoot.Properties = NULL;"); //$NON-NLS-1$
out.write(NL);
out.write("\t-- No MQMD header so create domain "); //$NON-NLS-1$
out.write(NL);
out.write("\tCREATE FIRSTCHILD OF OutputRoot DOMAIN ('MQMD') NAME 'MQMD';"); //$NON-NLS-1$
out.write(NL);
out.write("\tDECLARE MQMDRef REFERENCE TO OutputRoot.MQMD;"); //$NON-NLS-1$
out.write(NL);
out.write("\tSET MQMDRef.Version = MQMD_CURRENT_VERSION;"); //$NON-NLS-1$
out.write(NL);
out.write("\tSET MQMDRef.ApplIdentityData = SQL.BrokerName;"); //$NON-NLS-1$
out.write(NL);
out.write("\tSET MQMDRef.CodedCharSetId = InputRoot.Properties.CodedCharSetId;"); //$NON-NLS-1$
out.write(NL);
out.write("\tSET MQMDRef.Encoding = InputRoot.Properties.Encoding;"); //$NON-NLS-1$
out.write(NL);
out.write(NL);
out.write("\tCREATE NEXTSIBLING OF MQMDRef DOMAIN('XMLNSC') NAME 'XMLNSC';"); //$NON-NLS-1$
out.write(NL);
out.write("\tDECLARE OutRef REFERENCE TO OutputRoot.XMLNSC;"); //$NON-NLS-1$
out.write(NL);
out.write("\t-- Create error data\t"); //$NON-NLS-1$
out.write(NL);
out.write("\tSET OutRef.Error.BrokerName = SQL.BrokerName;"); //$NON-NLS-1$
out.write(NL);
out.write("\tMOVE OutRef TO OutputRoot.XMLNSC.Error;"); //$NON-NLS-1$
out.write(NL);
out.write(" SET OutRef.MessageFlowLabel = SQL.MessageFlowLabel; "); //$NON-NLS-1$
out.write(NL);
out.write(" SET OutRef.DTSTAMP = CURRENT_TIMESTAMP; "); //$NON-NLS-1$
out.write(NL);
out.write(NL);
out.write("\t"); //$NON-NLS-1$
out.write(NL);
out.write("\t"); //$NON-NLS-1$
out.write(NL);
out.write("\tCall AddExceptionData();"); //$NON-NLS-1$
out.write(NL);
out.write("\tEND;"); //$NON-NLS-1$
out.write(NL);
out.write(" "); //$NON-NLS-1$
out.write(NL);
out.write("CREATE PROCEDURE AddExceptionData() BEGIN"); //$NON-NLS-1$
out.write(NL);
out.write("\t"); //$NON-NLS-1$
out.write(NL);
out.write("\t\tDECLARE ERef REFERENCE TO OutputRoot.XMLNSC.Error; "); //$NON-NLS-1$
out.write(NL);
out.write("\t -- Add some exception data for error and fault"); //$NON-NLS-1$
out.write(NL);
out.write("\t\tDECLARE Error INTEGER;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\tDECLARE Text CHARACTER;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\tDECLARE Label CHARACTER;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\tDeclare FaultText CHARACTER '"); //$NON-NLS-1$
out.write( pattern.getString("com.ibm.etools.mft.pattern.sen.sf.onewayackmq.esql.1") );
out.write("';"); //$NON-NLS-1$
out.write(NL);
out.write("\t\tDECLARE I INTEGER 1;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\tDECLARE K INTEGER;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\tDECLARE start REFERENCE TO InputExceptionList.*[1];"); //$NON-NLS-1$
out.write(NL);
out.write(NL);
out.write("\t\tWHILE start.Number IS NOT NULL DO "); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\tSET Label = start.Label;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\tSET Error = start.Number;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\tIF Error = 3001 THEN"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\tSET Text = start.Insert.Text;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\tELSE"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\tSET Text = start.Text;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\tEND IF;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t-- Don't include the \"Caught exception and rethrowing message\""); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\tIF Error <> 2230 THEN"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\t-- Process inserts"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\tDECLARE Inserts Character;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\tDECLARE INS Integer;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\tSet Inserts = '';"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\t-- Are there any inserts for this exception"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\tIF EXISTS (start.Insert[]) THEN"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\t\t-- If YES add them to inserts string"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\t \tSET Inserts = Inserts || COALESCE(start.Insert[1].Text,'NULL')|| ' / ';"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\t \tSET K = 1;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\t \tINSERTS: LOOP"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\t\t\tIF CARDINALITY(start.Insert[])> K "); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\t\t\tTHEN "); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\t\t\t\tSET Inserts = Inserts || COALESCE(start.Insert[K+1].Text,'NULL')|| ' / ';"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\t\t\t-- No more inserts to process"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\t\t\tELSE LEAVE INSERTS;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\t\t\tEND IF;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\t\tSET K = K+1;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\t\tEND LOOP INSERTS;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\tEND IF;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\tSET ERef.Exception[I].Label = Label;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\tSET ERef.Exception[I].Error = Error;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\tSET ERef.Exception[I].Text = Text;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\tSet ERef.Exception[I].Inserts = COALESCE(Inserts, '');"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\t"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\tSET FaultText = FaultText || ' "); //$NON-NLS-1$
out.write( pattern.getString("com.ibm.etools.mft.pattern.sen.sf.onewayackmq.esql.2") );
out.write(" ' || COALESCE(Label, ''); "); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\tSET FaultText = FaultText || ' "); //$NON-NLS-1$
out.write( pattern.getString("com.ibm.etools.mft.pattern.sen.sf.onewayackmq.esql.3") );
out.write(" ' || COALESCE(CAST(Error AS CHARACTER), '');"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\tSET FaultText = FaultText || ' "); //$NON-NLS-1$
out.write( pattern.getString("com.ibm.etools.mft.pattern.sen.sf.onewayackmq.esql.4") );
out.write(" ' || COALESCE(Text, '');"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\tSET FaultText = FaultText || ' "); //$NON-NLS-1$
out.write( pattern.getString("com.ibm.etools.mft.pattern.sen.sf.onewayackmq.esql.8") );
out.write(" ' || COALESCE(Inserts, '');"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\tSET I = I+1; "); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\tEND IF;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t-- Move start to the last child of the field to which it currently points"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\tMOVE start LASTCHILD;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\tEND WHILE;"); //$NON-NLS-1$
out.write(NL);
out.write("\t\t\t\tSET Environment.PatternVariables.FaultText = FaultText;"); //$NON-NLS-1$
out.write(NL);
out.write("\tEND; "); //$NON-NLS-1$
out.write(NL);
out.write(" "); //$NON-NLS-1$
out.write(NL);
out.write(" "); //$NON-NLS-1$
out.write(NL);
out.write("END MODULE;"); //$NON-NLS-1$
out.write(NL);
out.write(NL);
out.write("CREATE FILTER MODULE CheckifMessageSent"); //$NON-NLS-1$
out.write(NL);
out.write("\tCREATE FUNCTION Main() RETURNS BOOLEAN"); //$NON-NLS-1$
out.write(NL);
out.write("\tBEGIN"); //$NON-NLS-1$
out.write(NL);
out.write("\t\tRETURN Environment.PatternVariables.Complete = 'Complete';"); //$NON-NLS-1$
out.write(NL);
out.write(NL);
out.write("\tEND;"); //$NON-NLS-1$
out.write(NL);
out.write("\tEND MODULE;"); //$NON-NLS-1$
out.write(NL);
out.write("CREATE FILTER MODULE CheckErrorLogging"); //$NON-NLS-1$
out.write(NL);
out.write("\tCREATE FUNCTION Main() RETURNS BOOLEAN"); //$NON-NLS-1$
out.write(NL);
out.write("\tBEGIN"); //$NON-NLS-1$
out.write(NL);
out.write("\t\tRETURN ErrorLoggingOn;"); //$NON-NLS-1$
out.write(NL);
out.write("\tEND;"); //$NON-NLS-1$
out.write(NL);
out.write("\tEND MODULE;"); //$NON-NLS-1$
out.write(NL);
out.write("\t"); //$NON-NLS-1$
out.write(NL);
out.write("\t"); //$NON-NLS-1$
out.write(NL);
out.write("CREATE DATABASE MODULE Throw"); //$NON-NLS-1$
out.write(NL);
out.write("\tCREATE FUNCTION Main() RETURNS BOOLEAN"); //$NON-NLS-1$
out.write(NL);
out.write("\tBEGIN"); //$NON-NLS-1$
out.write(NL);
out.write("\tTHROW USER EXCEPTION SEVERITY 3 MESSAGE 2372 VALUES(Environment.PatternVariables.FaultText);"); //$NON-NLS-1$
out.write(NL);
out.write("END;"); //$NON-NLS-1$
out.write(NL);
out.write("END MODULE;"); //$NON-NLS-1$
out.write(NL);
out.write(NL);
}
}
| ot4i/service-facade-mq-request-response-pattern | src/com.ibm.etools.mft.pattern.sen/jet2java/org/eclipse/jet/compiled/_jet_Erroresql_0.java | Java | epl-1.0 | 18,882 |
/*
* Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.controller.cluster.raft;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import akka.actor.ActorRef;
import akka.persistence.SnapshotSelectionCriteria;
import akka.testkit.TestActorRef;
import java.util.Arrays;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.opendaylight.controller.cluster.DataPersistenceProvider;
import org.opendaylight.controller.cluster.raft.SnapshotManager.LastAppliedTermInformationReader;
import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot;
import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot;
import org.opendaylight.controller.cluster.raft.base.messages.SnapshotComplete;
import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
import org.slf4j.LoggerFactory;
public class SnapshotManagerTest extends AbstractActorTest {
@Mock
private RaftActorContext mockRaftActorContext;
@Mock
private ConfigParams mockConfigParams;
@Mock
private ReplicatedLog mockReplicatedLog;
@Mock
private DataPersistenceProvider mockDataPersistenceProvider;
@Mock
private RaftActorBehavior mockRaftActorBehavior;
@Mock
private Runnable mockProcedure;
@Mock
private ElectionTerm mockElectionTerm;
private SnapshotManager snapshotManager;
private TestActorFactory factory;
private TestActorRef<MessageCollectorActor> actorRef;
@Before
public void setUp(){
MockitoAnnotations.initMocks(this);
doReturn(false).when(mockRaftActorContext).hasFollowers();
doReturn(mockConfigParams).when(mockRaftActorContext).getConfigParams();
doReturn(10L).when(mockConfigParams).getSnapshotBatchCount();
doReturn(70).when(mockConfigParams).getSnapshotDataThresholdPercentage();
doReturn(mockReplicatedLog).when(mockRaftActorContext).getReplicatedLog();
doReturn("123").when(mockRaftActorContext).getId();
doReturn(mockDataPersistenceProvider).when(mockRaftActorContext).getPersistenceProvider();
doReturn(mockRaftActorBehavior).when(mockRaftActorContext).getCurrentBehavior();
doReturn("123").when(mockRaftActorBehavior).getLeaderId();
doReturn(mockElectionTerm).when(mockRaftActorContext).getTermInformation();
doReturn(5L).when(mockElectionTerm).getCurrentTerm();
doReturn("member5").when(mockElectionTerm).getVotedFor();
snapshotManager = new SnapshotManager(mockRaftActorContext, LoggerFactory.getLogger(this.getClass()));
factory = new TestActorFactory(getSystem());
actorRef = factory.createTestActor(MessageCollectorActor.props(), factory.generateActorId("test-"));
doReturn(actorRef).when(mockRaftActorContext).getActor();
snapshotManager.setCreateSnapshotRunnable(mockProcedure);
}
@After
public void tearDown(){
factory.close();
}
@Test
public void testConstruction(){
assertEquals(false, snapshotManager.isCapturing());
}
@Test
public void testCaptureToInstall() throws Exception {
// Force capturing toInstall = true
snapshotManager.captureToInstall(new MockRaftActorContext.MockReplicatedLogEntry(1, 0,
new MockRaftActorContext.MockPayload()), 0, "follower-1");
assertEquals(true, snapshotManager.isCapturing());
verify(mockProcedure).run();
CaptureSnapshot captureSnapshot = snapshotManager.getCaptureSnapshot();
// LastIndex and LastTerm are picked up from the lastLogEntry
assertEquals(0L, captureSnapshot.getLastIndex());
assertEquals(1L, captureSnapshot.getLastTerm());
// Since the actor does not have any followers (no peer addresses) lastApplied will be from lastLogEntry
assertEquals(0L, captureSnapshot.getLastAppliedIndex());
assertEquals(1L, captureSnapshot.getLastAppliedTerm());
//
assertEquals(-1L, captureSnapshot.getReplicatedToAllIndex());
assertEquals(-1L, captureSnapshot.getReplicatedToAllTerm());
actorRef.underlyingActor().clear();
}
@Test
public void testCapture() throws Exception {
boolean capture = snapshotManager.capture(new MockRaftActorContext.MockReplicatedLogEntry(1,9,
new MockRaftActorContext.MockPayload()), 9);
assertTrue(capture);
assertEquals(true, snapshotManager.isCapturing());
verify(mockProcedure).run();
CaptureSnapshot captureSnapshot = snapshotManager.getCaptureSnapshot();
// LastIndex and LastTerm are picked up from the lastLogEntry
assertEquals(9L, captureSnapshot.getLastIndex());
assertEquals(1L, captureSnapshot.getLastTerm());
// Since the actor does not have any followers (no peer addresses) lastApplied will be from lastLogEntry
assertEquals(9L, captureSnapshot.getLastAppliedIndex());
assertEquals(1L, captureSnapshot.getLastAppliedTerm());
//
assertEquals(-1L, captureSnapshot.getReplicatedToAllIndex());
assertEquals(-1L, captureSnapshot.getReplicatedToAllTerm());
actorRef.underlyingActor().clear();
}
@Test
public void testCaptureWithNullLastLogEntry() throws Exception {
boolean capture = snapshotManager.capture(null, 1);
assertTrue(capture);
assertEquals(true, snapshotManager.isCapturing());
verify(mockProcedure).run();
CaptureSnapshot captureSnapshot = snapshotManager.getCaptureSnapshot();
System.out.println(captureSnapshot);
// LastIndex and LastTerm are picked up from the lastLogEntry
assertEquals(-1L, captureSnapshot.getLastIndex());
assertEquals(-1L, captureSnapshot.getLastTerm());
// Since the actor does not have any followers (no peer addresses) lastApplied will be from lastLogEntry
assertEquals(-1L, captureSnapshot.getLastAppliedIndex());
assertEquals(-1L, captureSnapshot.getLastAppliedTerm());
//
assertEquals(-1L, captureSnapshot.getReplicatedToAllIndex());
assertEquals(-1L, captureSnapshot.getReplicatedToAllTerm());
actorRef.underlyingActor().clear();
}
@Test
public void testCaptureWithCreateProcedureError () throws Exception {
doThrow(new RuntimeException("mock")).when(mockProcedure).run();
boolean capture = snapshotManager.capture(new MockRaftActorContext.MockReplicatedLogEntry(1,9,
new MockRaftActorContext.MockPayload()), 9);
assertFalse(capture);
assertEquals(false, snapshotManager.isCapturing());
verify(mockProcedure).run();
}
@Test
public void testIllegalCapture() throws Exception {
boolean capture = snapshotManager.capture(new MockRaftActorContext.MockReplicatedLogEntry(1,9,
new MockRaftActorContext.MockPayload()), 9);
assertTrue(capture);
verify(mockProcedure).run();
reset(mockProcedure);
// This will not cause snapshot capture to start again
capture = snapshotManager.capture(new MockRaftActorContext.MockReplicatedLogEntry(1,9,
new MockRaftActorContext.MockPayload()), 9);
assertFalse(capture);
verify(mockProcedure, never()).run();
}
@Test
public void testPersistWhenReplicatedToAllIndexMinusOne(){
doReturn(7L).when(mockReplicatedLog).getSnapshotIndex();
doReturn(1L).when(mockReplicatedLog).getSnapshotTerm();
doReturn(true).when(mockRaftActorContext).hasFollowers();
doReturn(8L).when(mockRaftActorContext).getLastApplied();
MockRaftActorContext.MockReplicatedLogEntry lastLogEntry = new MockRaftActorContext.MockReplicatedLogEntry(
3L, 9L, new MockRaftActorContext.MockPayload());
MockRaftActorContext.MockReplicatedLogEntry lastAppliedEntry = new MockRaftActorContext.MockReplicatedLogEntry(
2L, 8L, new MockRaftActorContext.MockPayload());
doReturn(lastAppliedEntry).when(mockReplicatedLog).get(8L);
doReturn(Arrays.asList(lastLogEntry)).when(mockReplicatedLog).getFrom(9L);
// when replicatedToAllIndex = -1
snapshotManager.capture(lastLogEntry, -1);
byte[] bytes = new byte[] {1,2,3,4,5,6,7,8,9,10};
snapshotManager.persist(bytes, Runtime.getRuntime().totalMemory());
ArgumentCaptor<Snapshot> snapshotArgumentCaptor = ArgumentCaptor.forClass(Snapshot.class);
verify(mockDataPersistenceProvider).saveSnapshot(snapshotArgumentCaptor.capture());
Snapshot snapshot = snapshotArgumentCaptor.getValue();
assertEquals("getLastTerm", 3L, snapshot.getLastTerm());
assertEquals("getLastIndex", 9L, snapshot.getLastIndex());
assertEquals("getLastAppliedTerm", 2L, snapshot.getLastAppliedTerm());
assertEquals("getLastAppliedIndex", 8L, snapshot.getLastAppliedIndex());
assertArrayEquals("getState", bytes, snapshot.getState());
assertEquals("getUnAppliedEntries", Arrays.asList(lastLogEntry), snapshot.getUnAppliedEntries());
assertEquals("electionTerm", mockElectionTerm.getCurrentTerm(), snapshot.getElectionTerm());
assertEquals("electionVotedFor", mockElectionTerm.getVotedFor(), snapshot.getElectionVotedFor());
verify(mockReplicatedLog).snapshotPreCommit(7L, 1L);
}
@Test
public void testPersistWhenReplicatedToAllIndexNotMinus(){
doReturn(45L).when(mockReplicatedLog).getSnapshotIndex();
doReturn(6L).when(mockReplicatedLog).getSnapshotTerm();
ReplicatedLogEntry replicatedLogEntry = mock(ReplicatedLogEntry.class);
doReturn(replicatedLogEntry).when(mockReplicatedLog).get(9);
doReturn(6L).when(replicatedLogEntry).getTerm();
doReturn(9L).when(replicatedLogEntry).getIndex();
// when replicatedToAllIndex != -1
snapshotManager.capture(new MockRaftActorContext.MockReplicatedLogEntry(6,9,
new MockRaftActorContext.MockPayload()), 9);
byte[] bytes = new byte[] {1,2,3,4,5,6,7,8,9,10};
snapshotManager.persist(bytes, Runtime.getRuntime().totalMemory());
ArgumentCaptor<Snapshot> snapshotArgumentCaptor = ArgumentCaptor.forClass(Snapshot.class);
verify(mockDataPersistenceProvider).saveSnapshot(snapshotArgumentCaptor.capture());
Snapshot snapshot = snapshotArgumentCaptor.getValue();
assertEquals("getLastTerm", 6L, snapshot.getLastTerm());
assertEquals("getLastIndex", 9L, snapshot.getLastIndex());
assertEquals("getLastAppliedTerm", 6L, snapshot.getLastAppliedTerm());
assertEquals("getLastAppliedIndex", 9L, snapshot.getLastAppliedIndex());
assertArrayEquals("getState", bytes, snapshot.getState());
assertEquals("getUnAppliedEntries size", 0, snapshot.getUnAppliedEntries().size());
verify(mockReplicatedLog).snapshotPreCommit(9L, 6L);
verify(mockRaftActorBehavior).setReplicatedToAllIndex(9);
}
@Test
public void testPersistWhenReplicatedLogDataSizeGreaterThanThreshold(){
doReturn(Integer.MAX_VALUE).when(mockReplicatedLog).dataSize();
// when replicatedToAllIndex = -1
snapshotManager.capture(new MockRaftActorContext.MockReplicatedLogEntry(6,9,
new MockRaftActorContext.MockPayload()), -1);
snapshotManager.persist(new byte[]{}, Runtime.getRuntime().totalMemory());
verify(mockDataPersistenceProvider).saveSnapshot(any(Snapshot.class));
verify(mockReplicatedLog).snapshotPreCommit(9L, 6L);
verify(mockRaftActorBehavior, never()).setReplicatedToAllIndex(anyLong());
}
@Test
public void testPersistWhenReplicatedLogSizeExceedsSnapshotBatchCount() {
doReturn(10L).when(mockReplicatedLog).size(); // matches snapshotBatchCount
doReturn(100).when(mockReplicatedLog).dataSize();
doReturn(5L).when(mockReplicatedLog).getSnapshotIndex();
doReturn(5L).when(mockReplicatedLog).getSnapshotTerm();
long replicatedToAllIndex = 1;
ReplicatedLogEntry replicatedLogEntry = mock(ReplicatedLogEntry.class);
doReturn(replicatedLogEntry).when(mockReplicatedLog).get(replicatedToAllIndex);
doReturn(6L).when(replicatedLogEntry).getTerm();
doReturn(replicatedToAllIndex).when(replicatedLogEntry).getIndex();
snapshotManager.capture(new MockRaftActorContext.MockReplicatedLogEntry(6, 9,
new MockRaftActorContext.MockPayload()), replicatedToAllIndex);
snapshotManager.persist(new byte[]{}, 2000000L);
verify(mockDataPersistenceProvider).saveSnapshot(any(Snapshot.class));
verify(mockReplicatedLog).snapshotPreCommit(9L, 6L);
verify(mockRaftActorBehavior).setReplicatedToAllIndex(replicatedToAllIndex);
}
@Test
public void testPersistSendInstallSnapshot(){
doReturn(Integer.MAX_VALUE).when(mockReplicatedLog).dataSize();
// when replicatedToAllIndex = -1
boolean capture = snapshotManager.captureToInstall(new MockRaftActorContext.MockReplicatedLogEntry(6, 9,
new MockRaftActorContext.MockPayload()), -1, "follower-1");
assertTrue(capture);
byte[] bytes = new byte[] {1,2,3,4,5,6,7,8,9,10};
snapshotManager.persist(bytes, Runtime.getRuntime().totalMemory());
assertEquals(true, snapshotManager.isCapturing());
verify(mockDataPersistenceProvider).saveSnapshot(any(Snapshot.class));
verify(mockReplicatedLog).snapshotPreCommit(9L, 6L);
ArgumentCaptor<SendInstallSnapshot> sendInstallSnapshotArgumentCaptor
= ArgumentCaptor.forClass(SendInstallSnapshot.class);
verify(mockRaftActorBehavior).handleMessage(any(ActorRef.class), sendInstallSnapshotArgumentCaptor.capture());
SendInstallSnapshot sendInstallSnapshot = sendInstallSnapshotArgumentCaptor.getValue();
assertTrue(Arrays.equals(bytes, sendInstallSnapshot.getSnapshot().getState()));
}
@Test
public void testCallingPersistWithoutCaptureWillDoNothing(){
snapshotManager.persist(new byte[]{}, Runtime.getRuntime().totalMemory());
verify(mockDataPersistenceProvider, never()).saveSnapshot(any(Snapshot.class));
verify(mockReplicatedLog, never()).snapshotPreCommit(9L, 6L);
verify(mockRaftActorBehavior, never()).handleMessage(any(ActorRef.class), any(SendInstallSnapshot.class));
}
@Test
public void testCallingPersistTwiceWillDoNoHarm(){
doReturn(Integer.MAX_VALUE).when(mockReplicatedLog).dataSize();
// when replicatedToAllIndex = -1
snapshotManager.captureToInstall(new MockRaftActorContext.MockReplicatedLogEntry(6, 9,
new MockRaftActorContext.MockPayload()), -1, "follower-1");
snapshotManager.persist(new byte[]{}, Runtime.getRuntime().totalMemory());
snapshotManager.persist(new byte[]{}, Runtime.getRuntime().totalMemory());
verify(mockDataPersistenceProvider).saveSnapshot(any(Snapshot.class));
verify(mockReplicatedLog).snapshotPreCommit(9L, 6L);
verify(mockRaftActorBehavior).handleMessage(any(ActorRef.class), any(SendInstallSnapshot.class));
}
@Test
public void testCommit(){
doReturn(50L).when(mockDataPersistenceProvider).getLastSequenceNumber();
// when replicatedToAllIndex = -1
snapshotManager.captureToInstall(new MockRaftActorContext.MockReplicatedLogEntry(6, 9,
new MockRaftActorContext.MockPayload()), -1, "follower-1");
snapshotManager.persist(new byte[]{}, Runtime.getRuntime().totalMemory());
assertEquals(true, snapshotManager.isCapturing());
snapshotManager.commit(100L, 1234L);
assertEquals(false, snapshotManager.isCapturing());
verify(mockReplicatedLog).snapshotCommit();
verify(mockDataPersistenceProvider).deleteMessages(50L);
ArgumentCaptor<SnapshotSelectionCriteria> criteriaCaptor = ArgumentCaptor.forClass(SnapshotSelectionCriteria.class);
verify(mockDataPersistenceProvider).deleteSnapshots(criteriaCaptor.capture());
assertEquals(100L, criteriaCaptor.getValue().maxSequenceNr());
assertEquals(1233L, criteriaCaptor.getValue().maxTimestamp());
MessageCollectorActor.expectFirstMatching(actorRef, SnapshotComplete.class);
}
@Test
public void testCommitBeforePersist(){
// when replicatedToAllIndex = -1
snapshotManager.captureToInstall(new MockRaftActorContext.MockReplicatedLogEntry(6, 9,
new MockRaftActorContext.MockPayload()), -1, "follower-1");
snapshotManager.commit(100L, 0);
verify(mockReplicatedLog, never()).snapshotCommit();
verify(mockDataPersistenceProvider, never()).deleteMessages(100L);
verify(mockDataPersistenceProvider, never()).deleteSnapshots(any(SnapshotSelectionCriteria.class));
}
@Test
public void testCommitBeforeCapture(){
snapshotManager.commit(100L, 0);
verify(mockReplicatedLog, never()).snapshotCommit();
verify(mockDataPersistenceProvider, never()).deleteMessages(anyLong());
verify(mockDataPersistenceProvider, never()).deleteSnapshots(any(SnapshotSelectionCriteria.class));
}
@Test
public void testCallingCommitMultipleTimesCausesNoHarm(){
doReturn(50L).when(mockDataPersistenceProvider).getLastSequenceNumber();
// when replicatedToAllIndex = -1
snapshotManager.captureToInstall(new MockRaftActorContext.MockReplicatedLogEntry(6, 9,
new MockRaftActorContext.MockPayload()), -1, "follower-1");
snapshotManager.persist(new byte[]{}, Runtime.getRuntime().totalMemory());
snapshotManager.commit(100L, 0);
snapshotManager.commit(100L, 0);
verify(mockReplicatedLog, times(1)).snapshotCommit();
verify(mockDataPersistenceProvider, times(1)).deleteMessages(50L);
verify(mockDataPersistenceProvider, times(1)).deleteSnapshots(any(SnapshotSelectionCriteria.class));
}
@Test
public void testRollback(){
// when replicatedToAllIndex = -1
snapshotManager.captureToInstall(new MockRaftActorContext.MockReplicatedLogEntry(6, 9,
new MockRaftActorContext.MockPayload()), -1, "follower-1");
snapshotManager.persist(new byte[]{}, Runtime.getRuntime().totalMemory());
snapshotManager.rollback();
verify(mockReplicatedLog).snapshotRollback();
MessageCollectorActor.expectFirstMatching(actorRef, SnapshotComplete.class);
}
@Test
public void testRollbackBeforePersist(){
// when replicatedToAllIndex = -1
snapshotManager.captureToInstall(new MockRaftActorContext.MockReplicatedLogEntry(6, 9,
new MockRaftActorContext.MockPayload()), -1, "follower-1");
snapshotManager.rollback();
verify(mockReplicatedLog, never()).snapshotRollback();
}
@Test
public void testRollbackBeforeCapture(){
snapshotManager.rollback();
verify(mockReplicatedLog, never()).snapshotRollback();
}
@Test
public void testCallingRollbackMultipleTimesCausesNoHarm(){
// when replicatedToAllIndex = -1
snapshotManager.captureToInstall(new MockRaftActorContext.MockReplicatedLogEntry(6, 9,
new MockRaftActorContext.MockPayload()), -1, "follower-1");
snapshotManager.persist(new byte[]{}, Runtime.getRuntime().totalMemory());
snapshotManager.rollback();
snapshotManager.rollback();
verify(mockReplicatedLog, times(1)).snapshotRollback();
}
@Test
public void testTrimLogWhenTrimIndexLessThanLastApplied() {
doReturn(20L).when(mockRaftActorContext).getLastApplied();
ReplicatedLogEntry replicatedLogEntry = mock(ReplicatedLogEntry.class);
doReturn(true).when(mockReplicatedLog).isPresent(10);
doReturn(replicatedLogEntry).when((mockReplicatedLog)).get(10);
doReturn(5L).when(replicatedLogEntry).getTerm();
long retIndex = snapshotManager.trimLog(10);
assertEquals("return index", 10L, retIndex);
verify(mockReplicatedLog).snapshotPreCommit(10, 5);
verify(mockReplicatedLog).snapshotCommit();
verify(mockRaftActorBehavior, never()).setReplicatedToAllIndex(anyLong());
}
@Test
public void testTrimLogWhenLastAppliedNotSet() {
doReturn(-1L).when(mockRaftActorContext).getLastApplied();
ReplicatedLogEntry replicatedLogEntry = mock(ReplicatedLogEntry.class);
doReturn(true).when(mockReplicatedLog).isPresent(10);
doReturn(replicatedLogEntry).when((mockReplicatedLog)).get(10);
doReturn(5L).when(replicatedLogEntry).getTerm();
long retIndex = snapshotManager.trimLog(10);
assertEquals("return index", -1L, retIndex);
verify(mockReplicatedLog, never()).snapshotPreCommit(anyLong(), anyLong());
verify(mockReplicatedLog, never()).snapshotCommit();
verify(mockRaftActorBehavior, never()).setReplicatedToAllIndex(anyLong());
}
@Test
public void testTrimLogWhenLastAppliedZero() {
doReturn(0L).when(mockRaftActorContext).getLastApplied();
ReplicatedLogEntry replicatedLogEntry = mock(ReplicatedLogEntry.class);
doReturn(true).when(mockReplicatedLog).isPresent(10);
doReturn(replicatedLogEntry).when((mockReplicatedLog)).get(10);
doReturn(5L).when(replicatedLogEntry).getTerm();
long retIndex = snapshotManager.trimLog(10);
assertEquals("return index", -1L, retIndex);
verify(mockReplicatedLog, never()).snapshotPreCommit(anyLong(), anyLong());
verify(mockReplicatedLog, never()).snapshotCommit();
verify(mockRaftActorBehavior, never()).setReplicatedToAllIndex(anyLong());
}
@Test
public void testTrimLogWhenTrimIndexNotPresent() {
doReturn(20L).when(mockRaftActorContext).getLastApplied();
doReturn(false).when(mockReplicatedLog).isPresent(10);
long retIndex = snapshotManager.trimLog(10);
assertEquals("return index", -1L, retIndex);
verify(mockReplicatedLog, never()).snapshotPreCommit(anyLong(), anyLong());
verify(mockReplicatedLog, never()).snapshotCommit();
// Trim index is greater than replicatedToAllIndex so should update it.
verify(mockRaftActorBehavior).setReplicatedToAllIndex(10L);
}
@Test
public void testTrimLogAfterCapture(){
boolean capture = snapshotManager.capture(new MockRaftActorContext.MockReplicatedLogEntry(1,9,
new MockRaftActorContext.MockPayload()), 9);
assertTrue(capture);
assertEquals(true, snapshotManager.isCapturing());
ReplicatedLogEntry replicatedLogEntry = mock(ReplicatedLogEntry.class);
doReturn(20L).when(mockRaftActorContext).getLastApplied();
doReturn(true).when(mockReplicatedLog).isPresent(10);
doReturn(replicatedLogEntry).when((mockReplicatedLog)).get(10);
doReturn(5L).when(replicatedLogEntry).getTerm();
snapshotManager.trimLog(10);
verify(mockReplicatedLog, never()).snapshotPreCommit(anyLong(), anyLong());
verify(mockReplicatedLog, never()).snapshotCommit();
}
@Test
public void testTrimLogAfterCaptureToInstall(){
boolean capture = snapshotManager.captureToInstall(new MockRaftActorContext.MockReplicatedLogEntry(1,9,
new MockRaftActorContext.MockPayload()), 9, "follower-1");
assertTrue(capture);
assertEquals(true, snapshotManager.isCapturing());
ReplicatedLogEntry replicatedLogEntry = mock(ReplicatedLogEntry.class);
doReturn(20L).when(mockRaftActorContext).getLastApplied();
doReturn(true).when(mockReplicatedLog).isPresent(10);
doReturn(replicatedLogEntry).when((mockReplicatedLog)).get(10);
doReturn(5L).when(replicatedLogEntry).getTerm();
snapshotManager.trimLog(10);
verify(mockReplicatedLog, never()).snapshotPreCommit(10, 5);
verify(mockReplicatedLog, never()).snapshotCommit();
}
@Test
public void testLastAppliedTermInformationReader() {
LastAppliedTermInformationReader reader = new LastAppliedTermInformationReader();
doReturn(4L).when(mockReplicatedLog).getSnapshotTerm();
doReturn(7L).when(mockReplicatedLog).getSnapshotIndex();
ReplicatedLogEntry lastLogEntry = new MockRaftActorContext.MockReplicatedLogEntry(6L, 9L,
new MockRaftActorContext.MockPayload());
// No followers and valid lastLogEntry
reader.init(mockReplicatedLog, 1L, lastLogEntry, false);
assertEquals("getTerm", 6L, reader.getTerm());
assertEquals("getIndex", 9L, reader.getIndex());
// No followers and null lastLogEntry
reader.init(mockReplicatedLog, 1L, null, false);
assertEquals("getTerm", -1L, reader.getTerm());
assertEquals("getIndex", -1L, reader.getIndex());
// Followers and valid originalIndex entry
doReturn(new MockRaftActorContext.MockReplicatedLogEntry(5L, 8L,
new MockRaftActorContext.MockPayload())).when(mockReplicatedLog).get(8L);
reader.init(mockReplicatedLog, 8L, lastLogEntry, true);
assertEquals("getTerm", 5L, reader.getTerm());
assertEquals("getIndex", 8L, reader.getIndex());
// Followers and null originalIndex entry and valid snapshot index
reader.init(mockReplicatedLog, 7L, lastLogEntry, true);
assertEquals("getTerm", 4L, reader.getTerm());
assertEquals("getIndex", 7L, reader.getIndex());
// Followers and null originalIndex entry and invalid snapshot index
doReturn(-1L).when(mockReplicatedLog).getSnapshotIndex();
reader.init(mockReplicatedLog, 7L, lastLogEntry, true);
assertEquals("getTerm", -1L, reader.getTerm());
assertEquals("getIndex", -1L, reader.getIndex());
}
}
| qqbbyq/controller | opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/SnapshotManagerTest.java | Java | epl-1.0 | 27,087 |
package org.bitspilani.pearl;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.widget.TextView;
public class TillDeaf extends Activity {
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
getActionBar().hide();
setContentView(R.layout.event1);
TextView tv = (TextView)findViewById(R.id.title);
tv.setText(R.string.tillDeaf);
TextView tv1 = (TextView)findViewById(R.id.description);
tv1.setText(R.string.tilldeaf_ds);
}
}
| kostajaitachi/Pearl-14 | Pearl'14/src/org/bitspilani/pearl/TillDeaf.java | Java | epl-1.0 | 623 |
/*******************************************************************************
* Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.tools.workbench.utility.events;
import java.awt.EventQueue;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.Serializable;
/**
* AWT-aware implementation of ChangeNotifier interface:
* If we are executing on the AWT event-dispatch thread,
* simply forward the change notification directly to the listener.
* If we are executing on some other thread, queue up the
* notification on the AWT event queue so it can be executed
* on the event-dispatch thread (after the pending events have
* been dispatched).
*/
public final class AWTChangeNotifier
implements ChangeNotifier, Serializable
{
// singleton
private static ChangeNotifier INSTANCE;
private static final long serialVersionUID = 1L;
/**
* Return the singleton.
*/
public synchronized static ChangeNotifier instance() {
if (INSTANCE == null) {
INSTANCE = new AWTChangeNotifier();
}
return INSTANCE;
}
/**
* Ensure non-instantiability.
*/
private AWTChangeNotifier() {
super();
}
/**
* @see ChangeNotifier#stateChanged(StateChangeListener, StateChangeEvent)
*/
public void stateChanged(final StateChangeListener listener, final StateChangeEvent event) {
if (EventQueue.isDispatchThread()) {
listener.stateChanged(event);
} else {
this.invoke(
new Runnable() {
public void run() {
listener.stateChanged(event);
}
public String toString() {
return "stateChanged";
}
}
);
}
}
/**
* @see ChangeSupport.Notifier#propertyChange(java.beans.PropertyChangeListener, java.beans.PropertyChangeEvent)
*/
public void propertyChange(final PropertyChangeListener listener, final PropertyChangeEvent event) {
if (EventQueue.isDispatchThread()) {
listener.propertyChange(event);
} else {
this.invoke(
new Runnable() {
public void run() {
listener.propertyChange(event);
}
public String toString() {
return "propertyChange";
}
}
);
}
}
/**
* @see ChangeSupport.Notifier#itemsAdded(CollectionChangeListener, CollectionChangeEvent)
*/
public void itemsAdded(final CollectionChangeListener listener, final CollectionChangeEvent event) {
if (EventQueue.isDispatchThread()) {
listener.itemsAdded(event);
} else {
this.invoke(
new Runnable() {
public void run() {
listener.itemsAdded(event);
}
public String toString() {
return "itemsAdded (Collection)";
}
}
);
}
}
/**
* @see ChangeSupport.Notifier#itemsRemoved(CollectionChangeListener, CollectionChangeEvent)
*/
public void itemsRemoved(final CollectionChangeListener listener, final CollectionChangeEvent event) {
if (EventQueue.isDispatchThread()) {
listener.itemsRemoved(event);
} else {
this.invoke(
new Runnable() {
public void run() {
listener.itemsRemoved(event);
}
public String toString() {
return "itemsRemoved (Collection)";
}
}
);
}
}
/**
* @see ChangeSupport.Notifier#collectionChanged(CollectionChangeListener, CollectionChangeEvent)
*/
public void collectionChanged(final CollectionChangeListener listener, final CollectionChangeEvent event) {
if (EventQueue.isDispatchThread()) {
listener.collectionChanged(event);
} else {
this.invoke(
new Runnable() {
public void run() {
listener.collectionChanged(event);
}
public String toString() {
return "collectionChanged";
}
}
);
}
}
/**
* @see ChangeSupport.Notifier#itemsAdded(ListChangeListener, ListChangeEvent)
*/
public void itemsAdded(final ListChangeListener listener, final ListChangeEvent event) {
if (EventQueue.isDispatchThread()) {
listener.itemsAdded(event);
} else {
this.invoke(
new Runnable() {
public void run() {
listener.itemsAdded(event);
}
public String toString() {
return "itemsAdded (List)";
}
}
);
}
}
/**
* @see ChangeSupport.Notifier#itemsRemoved(ListChangeListener, ListChangeEvent)
*/
public void itemsRemoved(final ListChangeListener listener, final ListChangeEvent event) {
if (EventQueue.isDispatchThread()) {
listener.itemsRemoved(event);
} else {
this.invoke(
new Runnable() {
public void run() {
listener.itemsRemoved(event);
}
public String toString() {
return "itemsRemoved (List)";
}
}
);
}
}
/**
* @see ChangeSupport.Notifier#itemsReplaced(ListChangeListener, ListChangeEvent)
*/
public void itemsReplaced(final ListChangeListener listener, final ListChangeEvent event) {
if (EventQueue.isDispatchThread()) {
listener.itemsReplaced(event);
} else {
this.invoke(
new Runnable() {
public void run() {
listener.itemsReplaced(event);
}
public String toString() {
return "itemsReplaced (List)";
}
}
);
}
}
/**
* @see ChangeSupport.Notifier#listChanged(ListChangeListener, ListChangeEvent)
*/
public void listChanged(final ListChangeListener listener, final ListChangeEvent event) {
if (EventQueue.isDispatchThread()) {
listener.listChanged(event);
} else {
this.invoke(
new Runnable() {
public void run() {
listener.listChanged(event);
}
public String toString() {
return "listChanged";
}
}
);
}
}
/**
* @see ChangeSupport.Notifier#nodeAdded(TreeChangeListener, TreeChangeEvent)
*/
public void nodeAdded(final TreeChangeListener listener, final TreeChangeEvent event) {
if (EventQueue.isDispatchThread()) {
listener.nodeAdded(event);
} else {
this.invoke(
new Runnable() {
public void run() {
listener.nodeAdded(event);
}
public String toString() {
return "nodeAdded";
}
}
);
}
}
/**
* @see ChangeSupport.Notifier#nodeRemoved(TreeChangeListener, TreeChangeEvent)
*/
public void nodeRemoved(final TreeChangeListener listener, final TreeChangeEvent event) {
if (EventQueue.isDispatchThread()) {
listener.nodeRemoved(event);
} else {
this.invoke(
new Runnable() {
public void run() {
listener.nodeRemoved(event);
}
public String toString() {
return "nodeRemoved";
}
}
);
}
}
/**
* @see ChangeSupport.Notifier#treeChanged(TreeChangeListener, TreeChangeEvent)
*/
public void treeChanged(final TreeChangeListener listener, final TreeChangeEvent event) {
if (EventQueue.isDispatchThread()) {
listener.treeChanged(event);
} else {
this.invoke(
new Runnable() {
public void run() {
listener.treeChanged(event);
}
public String toString() {
return "treeChanged";
}
}
);
}
}
/**
* EventQueue.invokeLater(Runnable) seems to work OK;
* but using #invokeAndWait() can somtimes make things
* more predictable when debugging.
*/
private void invoke(Runnable r) {
EventQueue.invokeLater(r);
// try {
// EventQueue.invokeAndWait(r);
// } catch (InterruptedException ex) {
// throw new RuntimeException(ex);
// } catch (java.lang.reflect.InvocationTargetException ex) {
// throw new RuntimeException(ex);
// }
}
/**
* Serializable singleton support
*/
private Object readResolve() {
return instance();
}
}
| bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs | utils/eclipselink.utils.workbench/utility/source/org/eclipse/persistence/tools/workbench/utility/events/AWTChangeNotifier.java | Java | epl-1.0 | 8,323 |
package com.odcgroup.mdf.integration;
import org.osgi.framework.BundleContext;
import com.odcgroup.workbench.core.AbstractActivator;
/**
* The activator class controls the plug-in life cycle
*/
public class Activator extends AbstractActivator {
// The plug-in ID
public static final String PLUGIN_ID = "com.odcgroup.mdf.integration";
// The shared instance
private static Activator plugin;
/**
* The constructor
*/
public Activator() {
plugin = this;
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
*/
public void start(BundleContext context) throws Exception {
super.start(context);
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
@Override
protected String getResourceBundleName() {
return null;
}
}
| debabratahazra/DS | designstudio/components/domain/core/com.odcgroup.mdf.integration/src/main/java/com/odcgroup/mdf/integration/Activator.java | Java | epl-1.0 | 1,113 |
/**
* Copyright (c) 2011 - 2015, Lunifera GmbH (Gross Enzersdorf), Loetz KG (Heidelberg)
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Florian Pirchner - Initial implementation
*/
package org.lunifera.ecview.core.ui.core.editparts.extension;
import org.lunifera.ecview.core.common.editpart.IFieldEditpart;
/**
* An edit part for optionGroup.
*/
public interface IEnumOptionsGroupEditpart extends IFieldEditpart {
}
| lunifera/lunifera-ecview | org.lunifera.ecview.core.extension.editparts/src/org/lunifera/ecview/core/ui/core/editparts/extension/IEnumOptionsGroupEditpart.java | Java | epl-1.0 | 653 |
// Copyright © 2014 John Watson
// Licensed under the terms of the MIT License
var GameState = function(game) {
};
// Load images and sounds
GameState.prototype.preload = function() {
this.game.load.image('ground', 'assets/gfx/ground.png');
this.game.load.image('player', 'assets/gfx/player.png');
};
// Setup the example
GameState.prototype.create = function() {
// Set stage background to something sky colored
this.game.stage.backgroundColor = 0x4488cc;
// Define movement constants
this.MAX_SPEED = 500; // pixels/second
// Create a player sprite
this.player = this.game.add.sprite(this.game.width/2, this.game.height - 64, 'player');
// Enable physics on the player
this.game.physics.enable(this.player, Phaser.Physics.ARCADE);
// Make player collide with world boundaries so he doesn't leave the stage
this.player.body.collideWorldBounds = true;
// Capture certain keys to prevent their default actions in the browser.
// This is only necessary because this is an HTML5 game. Games on other
// platforms may not need code like this.
this.game.input.keyboard.addKeyCapture([
Phaser.Keyboard.LEFT,
Phaser.Keyboard.RIGHT,
Phaser.Keyboard.UP,
Phaser.Keyboard.DOWN
]);
// Create some ground for the player to walk on
this.ground = this.game.add.group();
for(var x = 0; x < this.game.width; x += 32) {
// Add the ground blocks, enable physics on each, make them immovable
var groundBlock = this.game.add.sprite(x, this.game.height - 32, 'ground');
this.game.physics.enable(groundBlock, Phaser.Physics.ARCADE);
groundBlock.body.immovable = true;
groundBlock.body.allowGravity = false;
this.ground.add(groundBlock);
}
};
// The update() method is called every frame
GameState.prototype.update = function() {
// Collide the player with the ground
this.game.physics.arcade.collide(this.player, this.ground);
if (this.leftInputIsActive()) {
// If the LEFT key is down, set the player velocity to move left
this.player.body.velocity.x = -this.MAX_SPEED;
} else if (this.rightInputIsActive()) {
// If the RIGHT key is down, set the player velocity to move right
this.player.body.velocity.x = this.MAX_SPEED;
} else {
// Stop the player from moving horizontally
this.player.body.velocity.x = 0;
}
};
// This function should return true when the player activates the "go left" control
// In this case, either holding the right arrow or tapping or clicking on the left
// side of the screen.
GameState.prototype.leftInputIsActive = function() {
var isActive = false;
isActive = this.input.keyboard.isDown(Phaser.Keyboard.LEFT);
isActive |= (this.game.input.activePointer.isDown &&
this.game.input.activePointer.x < this.game.width/4);
return isActive;
};
// This function should return true when the player activates the "go right" control
// In this case, either holding the right arrow or tapping or clicking on the right
// side of the screen.
GameState.prototype.rightInputIsActive = function() {
var isActive = false;
isActive = this.input.keyboard.isDown(Phaser.Keyboard.RIGHT);
isActive |= (this.game.input.activePointer.isDown &&
this.game.input.activePointer.x > this.game.width/2 + this.game.width/4);
return isActive;
};
var game = new Phaser.Game(640, 320, Phaser.AUTO, 'game');
game.state.add('game', GameState, true);
| boniatillo-com/PhaserEditor | source/phasereditor/phasereditor.resources.templates/templates/Game Mechanic Explorer/01 - Mechanic - Walking and jumping - Basic walking/WebContent/ex-walking-01.js | JavaScript | epl-1.0 | 3,525 |
/**
*/
package com.tocea.codewatch.architecture;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Method</b></em>'.
* <!-- end-user-doc -->
*
*
* @see com.tocea.codewatch.architecture.ArchitecturePackage#getMethod()
* @model
* @generated
*/
public interface Method extends AnalysedElement {
} // Method
| Tocea/Architecture-Designer | com.tocea.scertify.architecture.mm/src/com/tocea/codewatch/architecture/Method.java | Java | epl-1.0 | 343 |
package fmautorepair.mutationoperators.features;
import org.apache.log4j.Logger;
import de.ovgu.featureide.fm.core.Feature;
import de.ovgu.featureide.fm.core.FeatureModel;
import fmautorepair.mutationoperators.FMMutator;
/** transform And to or */
public class AndToOr extends FeatureMutator {
private static Logger logger = Logger.getLogger(AndToOr.class.getName());
public static FMMutator instance = new AndToOr();
@Override
String mutate(FeatureModel fm, Feature tobemutated) {
// if has more than one child or one child but optional
tobemutated.changeToOr();
logger.info("mutating feature " + tobemutated.getName() + " from AND TO OR");
return (tobemutated.getName() + " from AND TO OR");
}
@Override
boolean isMutable(FeatureModel fm, Feature tobemutated) {
int size = tobemutated.getChildren().size();
return (tobemutated.isAnd() && size >0);
}
}
| fmselab/fmautorepair | fmautorepair.mutation/src/fmautorepair/mutationoperators/features/AndToOr.java | Java | epl-1.0 | 883 |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package org.obeonetwork.dsl.east_adl.structure.functional_analysis_architecture.impl;
import java.util.Collection;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.EObjectContainmentWithInverseEList;
import org.eclipse.emf.ecore.util.InternalEList;
import org.obeonetwork.dsl.east_adl.core.impl.EASTADLArtifactImpl;
import org.obeonetwork.dsl.east_adl.structure.common.ConnectorSignal;
import org.obeonetwork.dsl.east_adl.structure.common.DesignDataType;
import org.obeonetwork.dsl.east_adl.structure.common.ImplementationDataType;
import org.obeonetwork.dsl.east_adl.structure.common.OperationCall;
import org.obeonetwork.dsl.east_adl.structure.common.TypeAssociation;
import org.obeonetwork.dsl.east_adl.structure.functional_analysis_architecture.AnalysisFunction;
import org.obeonetwork.dsl.east_adl.structure.functional_analysis_architecture.FunctionalAnalysisArchitecture;
import org.obeonetwork.dsl.east_adl.structure.functional_analysis_architecture.FunctionalDevice;
import org.obeonetwork.dsl.east_adl.structure.functional_analysis_architecture.Functional_analysis_architecturePackage;
import org.obeonetwork.dsl.east_adl.structure.functional_design_architecture.FunctionalDesignArchitecture;
import org.obeonetwork.dsl.east_adl.structure.functional_design_architecture.Functional_design_architecturePackage;
import org.obeonetwork.dsl.east_adl.structure.vehicle_feature_model.VehicleFeatureModel;
import org.obeonetwork.dsl.east_adl.structure.vehicle_feature_model.Vehicle_feature_modelPackage;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Functional Analysis Architecture</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.obeonetwork.dsl.east_adl.structure.functional_analysis_architecture.impl.FunctionalAnalysisArchitectureImpl#getAnalysisFunctions <em>Analysis Functions</em>}</li>
* <li>{@link org.obeonetwork.dsl.east_adl.structure.functional_analysis_architecture.impl.FunctionalAnalysisArchitectureImpl#getFunctionalDevices <em>Functional Devices</em>}</li>
* <li>{@link org.obeonetwork.dsl.east_adl.structure.functional_analysis_architecture.impl.FunctionalAnalysisArchitectureImpl#getVehicleModel <em>Vehicle Model</em>}</li>
* <li>{@link org.obeonetwork.dsl.east_adl.structure.functional_analysis_architecture.impl.FunctionalAnalysisArchitectureImpl#getDesignArchitecture <em>Design Architecture</em>}</li>
* <li>{@link org.obeonetwork.dsl.east_adl.structure.functional_analysis_architecture.impl.FunctionalAnalysisArchitectureImpl#getDesignDataTypes <em>Design Data Types</em>}</li>
* <li>{@link org.obeonetwork.dsl.east_adl.structure.functional_analysis_architecture.impl.FunctionalAnalysisArchitectureImpl#getConnectorSignals <em>Connector Signals</em>}</li>
* <li>{@link org.obeonetwork.dsl.east_adl.structure.functional_analysis_architecture.impl.FunctionalAnalysisArchitectureImpl#getOperationCalls <em>Operation Calls</em>}</li>
* <li>{@link org.obeonetwork.dsl.east_adl.structure.functional_analysis_architecture.impl.FunctionalAnalysisArchitectureImpl#getTypeAssociations <em>Type Associations</em>}</li>
* <li>{@link org.obeonetwork.dsl.east_adl.structure.functional_analysis_architecture.impl.FunctionalAnalysisArchitectureImpl#getImplementationDataTypes <em>Implementation Data Types</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class FunctionalAnalysisArchitectureImpl extends EASTADLArtifactImpl implements FunctionalAnalysisArchitecture {
/**
* The cached value of the '{@link #getAnalysisFunctions() <em>Analysis Functions</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getAnalysisFunctions()
* @generated
* @ordered
*/
protected EList<AnalysisFunction> analysisFunctions;
/**
* The cached value of the '{@link #getFunctionalDevices() <em>Functional Devices</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getFunctionalDevices()
* @generated
* @ordered
*/
protected EList<FunctionalDevice> functionalDevices;
/**
* The cached value of the '{@link #getVehicleModel() <em>Vehicle Model</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getVehicleModel()
* @generated
* @ordered
*/
protected VehicleFeatureModel vehicleModel;
/**
* The cached value of the '{@link #getDesignArchitecture() <em>Design Architecture</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDesignArchitecture()
* @generated
* @ordered
*/
protected FunctionalDesignArchitecture designArchitecture;
/**
* The cached value of the '{@link #getDesignDataTypes() <em>Design Data Types</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDesignDataTypes()
* @generated
* @ordered
*/
protected EList<DesignDataType> designDataTypes;
/**
* The cached value of the '{@link #getConnectorSignals() <em>Connector Signals</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getConnectorSignals()
* @generated
* @ordered
*/
protected EList<ConnectorSignal> connectorSignals;
/**
* The cached value of the '{@link #getOperationCalls() <em>Operation Calls</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getOperationCalls()
* @generated
* @ordered
*/
protected EList<OperationCall> operationCalls;
/**
* The cached value of the '{@link #getTypeAssociations() <em>Type Associations</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getTypeAssociations()
* @generated
* @ordered
*/
protected EList<TypeAssociation> typeAssociations;
/**
* The cached value of the '{@link #getImplementationDataTypes() <em>Implementation Data Types</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getImplementationDataTypes()
* @generated
* @ordered
*/
protected EList<ImplementationDataType> implementationDataTypes;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected FunctionalAnalysisArchitectureImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return Functional_analysis_architecturePackage.Literals.FUNCTIONAL_ANALYSIS_ARCHITECTURE;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<AnalysisFunction> getAnalysisFunctions() {
if (analysisFunctions == null) {
analysisFunctions = new EObjectContainmentEList<AnalysisFunction>(AnalysisFunction.class, this, Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__ANALYSIS_FUNCTIONS);
}
return analysisFunctions;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<FunctionalDevice> getFunctionalDevices() {
if (functionalDevices == null) {
functionalDevices = new EObjectContainmentWithInverseEList<FunctionalDevice>(FunctionalDevice.class, this, Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__FUNCTIONAL_DEVICES, Functional_analysis_architecturePackage.FUNCTIONAL_DEVICE__OWNING_ARTIFACT);
}
return functionalDevices;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public VehicleFeatureModel getVehicleModel() {
if (vehicleModel != null && vehicleModel.eIsProxy()) {
InternalEObject oldVehicleModel = (InternalEObject)vehicleModel;
vehicleModel = (VehicleFeatureModel)eResolveProxy(oldVehicleModel);
if (vehicleModel != oldVehicleModel) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__VEHICLE_MODEL, oldVehicleModel, vehicleModel));
}
}
return vehicleModel;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public VehicleFeatureModel basicGetVehicleModel() {
return vehicleModel;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetVehicleModel(VehicleFeatureModel newVehicleModel, NotificationChain msgs) {
VehicleFeatureModel oldVehicleModel = vehicleModel;
vehicleModel = newVehicleModel;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__VEHICLE_MODEL, oldVehicleModel, newVehicleModel);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setVehicleModel(VehicleFeatureModel newVehicleModel) {
if (newVehicleModel != vehicleModel) {
NotificationChain msgs = null;
if (vehicleModel != null)
msgs = ((InternalEObject)vehicleModel).eInverseRemove(this, Vehicle_feature_modelPackage.VEHICLE_FEATURE_MODEL__ANALYSIS_ARCHITECTURE, VehicleFeatureModel.class, msgs);
if (newVehicleModel != null)
msgs = ((InternalEObject)newVehicleModel).eInverseAdd(this, Vehicle_feature_modelPackage.VEHICLE_FEATURE_MODEL__ANALYSIS_ARCHITECTURE, VehicleFeatureModel.class, msgs);
msgs = basicSetVehicleModel(newVehicleModel, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__VEHICLE_MODEL, newVehicleModel, newVehicleModel));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public FunctionalDesignArchitecture getDesignArchitecture() {
if (designArchitecture != null && designArchitecture.eIsProxy()) {
InternalEObject oldDesignArchitecture = (InternalEObject)designArchitecture;
designArchitecture = (FunctionalDesignArchitecture)eResolveProxy(oldDesignArchitecture);
if (designArchitecture != oldDesignArchitecture) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__DESIGN_ARCHITECTURE, oldDesignArchitecture, designArchitecture));
}
}
return designArchitecture;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public FunctionalDesignArchitecture basicGetDesignArchitecture() {
return designArchitecture;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetDesignArchitecture(FunctionalDesignArchitecture newDesignArchitecture, NotificationChain msgs) {
FunctionalDesignArchitecture oldDesignArchitecture = designArchitecture;
designArchitecture = newDesignArchitecture;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__DESIGN_ARCHITECTURE, oldDesignArchitecture, newDesignArchitecture);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setDesignArchitecture(FunctionalDesignArchitecture newDesignArchitecture) {
if (newDesignArchitecture != designArchitecture) {
NotificationChain msgs = null;
if (designArchitecture != null)
msgs = ((InternalEObject)designArchitecture).eInverseRemove(this, Functional_design_architecturePackage.FUNCTIONAL_DESIGN_ARCHITECTURE__ANALYSIS_ARCHITECTURE, FunctionalDesignArchitecture.class, msgs);
if (newDesignArchitecture != null)
msgs = ((InternalEObject)newDesignArchitecture).eInverseAdd(this, Functional_design_architecturePackage.FUNCTIONAL_DESIGN_ARCHITECTURE__ANALYSIS_ARCHITECTURE, FunctionalDesignArchitecture.class, msgs);
msgs = basicSetDesignArchitecture(newDesignArchitecture, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__DESIGN_ARCHITECTURE, newDesignArchitecture, newDesignArchitecture));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<DesignDataType> getDesignDataTypes() {
if (designDataTypes == null) {
designDataTypes = new EObjectContainmentEList<DesignDataType>(DesignDataType.class, this, Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__DESIGN_DATA_TYPES);
}
return designDataTypes;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<ConnectorSignal> getConnectorSignals() {
if (connectorSignals == null) {
connectorSignals = new EObjectContainmentEList<ConnectorSignal>(ConnectorSignal.class, this, Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__CONNECTOR_SIGNALS);
}
return connectorSignals;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<OperationCall> getOperationCalls() {
if (operationCalls == null) {
operationCalls = new EObjectContainmentEList<OperationCall>(OperationCall.class, this, Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__OPERATION_CALLS);
}
return operationCalls;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<TypeAssociation> getTypeAssociations() {
if (typeAssociations == null) {
typeAssociations = new EObjectContainmentEList<TypeAssociation>(TypeAssociation.class, this, Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__TYPE_ASSOCIATIONS);
}
return typeAssociations;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<ImplementationDataType> getImplementationDataTypes() {
if (implementationDataTypes == null) {
implementationDataTypes = new EObjectContainmentEList<ImplementationDataType>(ImplementationDataType.class, this, Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__IMPLEMENTATION_DATA_TYPES);
}
return implementationDataTypes;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__FUNCTIONAL_DEVICES:
return ((InternalEList<InternalEObject>)(InternalEList<?>)getFunctionalDevices()).basicAdd(otherEnd, msgs);
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__VEHICLE_MODEL:
if (vehicleModel != null)
msgs = ((InternalEObject)vehicleModel).eInverseRemove(this, Vehicle_feature_modelPackage.VEHICLE_FEATURE_MODEL__ANALYSIS_ARCHITECTURE, VehicleFeatureModel.class, msgs);
return basicSetVehicleModel((VehicleFeatureModel)otherEnd, msgs);
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__DESIGN_ARCHITECTURE:
if (designArchitecture != null)
msgs = ((InternalEObject)designArchitecture).eInverseRemove(this, Functional_design_architecturePackage.FUNCTIONAL_DESIGN_ARCHITECTURE__ANALYSIS_ARCHITECTURE, FunctionalDesignArchitecture.class, msgs);
return basicSetDesignArchitecture((FunctionalDesignArchitecture)otherEnd, msgs);
}
return super.eInverseAdd(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__ANALYSIS_FUNCTIONS:
return ((InternalEList<?>)getAnalysisFunctions()).basicRemove(otherEnd, msgs);
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__FUNCTIONAL_DEVICES:
return ((InternalEList<?>)getFunctionalDevices()).basicRemove(otherEnd, msgs);
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__VEHICLE_MODEL:
return basicSetVehicleModel(null, msgs);
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__DESIGN_ARCHITECTURE:
return basicSetDesignArchitecture(null, msgs);
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__DESIGN_DATA_TYPES:
return ((InternalEList<?>)getDesignDataTypes()).basicRemove(otherEnd, msgs);
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__CONNECTOR_SIGNALS:
return ((InternalEList<?>)getConnectorSignals()).basicRemove(otherEnd, msgs);
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__OPERATION_CALLS:
return ((InternalEList<?>)getOperationCalls()).basicRemove(otherEnd, msgs);
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__TYPE_ASSOCIATIONS:
return ((InternalEList<?>)getTypeAssociations()).basicRemove(otherEnd, msgs);
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__IMPLEMENTATION_DATA_TYPES:
return ((InternalEList<?>)getImplementationDataTypes()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__ANALYSIS_FUNCTIONS:
return getAnalysisFunctions();
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__FUNCTIONAL_DEVICES:
return getFunctionalDevices();
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__VEHICLE_MODEL:
if (resolve) return getVehicleModel();
return basicGetVehicleModel();
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__DESIGN_ARCHITECTURE:
if (resolve) return getDesignArchitecture();
return basicGetDesignArchitecture();
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__DESIGN_DATA_TYPES:
return getDesignDataTypes();
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__CONNECTOR_SIGNALS:
return getConnectorSignals();
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__OPERATION_CALLS:
return getOperationCalls();
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__TYPE_ASSOCIATIONS:
return getTypeAssociations();
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__IMPLEMENTATION_DATA_TYPES:
return getImplementationDataTypes();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__ANALYSIS_FUNCTIONS:
getAnalysisFunctions().clear();
getAnalysisFunctions().addAll((Collection<? extends AnalysisFunction>)newValue);
return;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__FUNCTIONAL_DEVICES:
getFunctionalDevices().clear();
getFunctionalDevices().addAll((Collection<? extends FunctionalDevice>)newValue);
return;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__VEHICLE_MODEL:
setVehicleModel((VehicleFeatureModel)newValue);
return;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__DESIGN_ARCHITECTURE:
setDesignArchitecture((FunctionalDesignArchitecture)newValue);
return;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__DESIGN_DATA_TYPES:
getDesignDataTypes().clear();
getDesignDataTypes().addAll((Collection<? extends DesignDataType>)newValue);
return;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__CONNECTOR_SIGNALS:
getConnectorSignals().clear();
getConnectorSignals().addAll((Collection<? extends ConnectorSignal>)newValue);
return;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__OPERATION_CALLS:
getOperationCalls().clear();
getOperationCalls().addAll((Collection<? extends OperationCall>)newValue);
return;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__TYPE_ASSOCIATIONS:
getTypeAssociations().clear();
getTypeAssociations().addAll((Collection<? extends TypeAssociation>)newValue);
return;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__IMPLEMENTATION_DATA_TYPES:
getImplementationDataTypes().clear();
getImplementationDataTypes().addAll((Collection<? extends ImplementationDataType>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__ANALYSIS_FUNCTIONS:
getAnalysisFunctions().clear();
return;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__FUNCTIONAL_DEVICES:
getFunctionalDevices().clear();
return;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__VEHICLE_MODEL:
setVehicleModel((VehicleFeatureModel)null);
return;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__DESIGN_ARCHITECTURE:
setDesignArchitecture((FunctionalDesignArchitecture)null);
return;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__DESIGN_DATA_TYPES:
getDesignDataTypes().clear();
return;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__CONNECTOR_SIGNALS:
getConnectorSignals().clear();
return;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__OPERATION_CALLS:
getOperationCalls().clear();
return;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__TYPE_ASSOCIATIONS:
getTypeAssociations().clear();
return;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__IMPLEMENTATION_DATA_TYPES:
getImplementationDataTypes().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__ANALYSIS_FUNCTIONS:
return analysisFunctions != null && !analysisFunctions.isEmpty();
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__FUNCTIONAL_DEVICES:
return functionalDevices != null && !functionalDevices.isEmpty();
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__VEHICLE_MODEL:
return vehicleModel != null;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__DESIGN_ARCHITECTURE:
return designArchitecture != null;
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__DESIGN_DATA_TYPES:
return designDataTypes != null && !designDataTypes.isEmpty();
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__CONNECTOR_SIGNALS:
return connectorSignals != null && !connectorSignals.isEmpty();
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__OPERATION_CALLS:
return operationCalls != null && !operationCalls.isEmpty();
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__TYPE_ASSOCIATIONS:
return typeAssociations != null && !typeAssociations.isEmpty();
case Functional_analysis_architecturePackage.FUNCTIONAL_ANALYSIS_ARCHITECTURE__IMPLEMENTATION_DATA_TYPES:
return implementationDataTypes != null && !implementationDataTypes.isEmpty();
}
return super.eIsSet(featureID);
}
} //FunctionalAnalysisArchitectureImpl
| ObeoNetwork/EAST-ADL-Designer | plugins/org.obeonetwork.dsl.eastadl/src/org/obeonetwork/dsl/east_adl/structure/functional_analysis_architecture/impl/FunctionalAnalysisArchitectureImpl.java | Java | epl-1.0 | 25,068 |
/**
* Copyright (c) 2016-2017 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package com.zsmartsystems.zwave.commandclass.impl;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Class to implement the Z-Wave command class <b>COMMAND_CLASS_HUMIDITY_CONTROL_SETPOINT</b> version <b>1</b>.
* <p>
* Command Class Humidity Control Setpoint
* <p>
* This class provides static methods for processing received messages (message handler) and
* methods to get a message to send on the Z-Wave network.
* <p>
* Command class key is 0x64.
* <p>
* Note that this code is autogenerated. Manual changes may be overwritten.
*
* @author Chris Jackson - Initial contribution of Java code generator
*/
public class CommandClassHumidityControlSetpointV1 {
private static final Logger logger = LoggerFactory.getLogger(CommandClassHumidityControlSetpointV1.class);
/**
* Integer command class key for COMMAND_CLASS_HUMIDITY_CONTROL_SETPOINT
*/
public final static int COMMAND_CLASS_KEY = 0x64;
/**
* Humidity Control Setpoint Set Command Constant
*/
public final static int HUMIDITY_CONTROL_SETPOINT_SET = 0x01;
/**
* Humidity Control Setpoint Get Command Constant
*/
public final static int HUMIDITY_CONTROL_SETPOINT_GET = 0x02;
/**
* Humidity Control Setpoint Report Command Constant
*/
public final static int HUMIDITY_CONTROL_SETPOINT_REPORT = 0x03;
/**
* Humidity Control Setpoint Supported Get Command Constant
*/
public final static int HUMIDITY_CONTROL_SETPOINT_SUPPORTED_GET = 0x04;
/**
* Humidity Control Setpoint Supported Report Command Constant
*/
public final static int HUMIDITY_CONTROL_SETPOINT_SUPPORTED_REPORT = 0x05;
/**
* Humidity Control Setpoint Scale Supported Get Command Constant
*/
public final static int HUMIDITY_CONTROL_SETPOINT_SCALE_SUPPORTED_GET = 0x06;
/**
* Humidity Control Setpoint Scale Supported Report Command Constant
*/
public final static int HUMIDITY_CONTROL_SETPOINT_SCALE_SUPPORTED_REPORT = 0x07;
/**
* Humidity Control Setpoint Capabilities Get Command Constant
*/
public final static int HUMIDITY_CONTROL_SETPOINT_CAPABILITIES_GET = 0x08;
/**
* Humidity Control Setpoint Capabilities Report Command Constant
*/
public final static int HUMIDITY_CONTROL_SETPOINT_CAPABILITIES_REPORT = 0x09;
/**
* Map holding constants for HumidityControlSetpointGetSetpointType
*/
private static Map<Integer, String> constantHumidityControlSetpointGetSetpointType = new HashMap<Integer, String>();
/**
* Map holding constants for HumidityControlSetpointCapabilitiesGetSetpointType
*/
private static Map<Integer, String> constantHumidityControlSetpointCapabilitiesGetSetpointType = new HashMap<Integer, String>();
/**
* Map holding constants for HumidityControlSetpointSupportedReportBitMask
*/
private static Map<Integer, String> constantHumidityControlSetpointSupportedReportBitMask = new HashMap<Integer, String>();
/**
* Map holding constants for HumidityControlSetpointScaleSupportedGetSetpointType
*/
private static Map<Integer, String> constantHumidityControlSetpointScaleSupportedGetSetpointType = new HashMap<Integer, String>();
/**
* Map holding constants for HumidityControlSetpointSetSetpointType
*/
private static Map<Integer, String> constantHumidityControlSetpointSetSetpointType = new HashMap<Integer, String>();
/**
* Map holding constants for HumidityControlSetpointReportScale
*/
private static Map<Integer, String> constantHumidityControlSetpointReportScale = new HashMap<Integer, String>();
/**
* Map holding constants for HumidityControlSetpointCapabilitiesReportSetpointType
*/
private static Map<Integer, String> constantHumidityControlSetpointCapabilitiesReportSetpointType = new HashMap<Integer, String>();
/**
* Map holding constants for HumidityControlSetpointReportSetpointType
*/
private static Map<Integer, String> constantHumidityControlSetpointReportSetpointType = new HashMap<Integer, String>();
/**
* Map holding constants for HumidityControlSetpointCapabilitiesReportScale2
*/
private static Map<Integer, String> constantHumidityControlSetpointCapabilitiesReportScale2 = new HashMap<Integer, String>();
/**
* Map holding constants for HumidityControlSetpointCapabilitiesReportScale1
*/
private static Map<Integer, String> constantHumidityControlSetpointCapabilitiesReportScale1 = new HashMap<Integer, String>();
/**
* Map holding constants for HumidityControlSetpointScaleSupportedReportScaleBitMask
*/
private static Map<Integer, String> constantHumidityControlSetpointScaleSupportedReportScaleBitMask = new HashMap<Integer, String>();
/**
* Map holding constants for HumidityControlSetpointSetScale
*/
private static Map<Integer, String> constantHumidityControlSetpointSetScale = new HashMap<Integer, String>();
static {
// Constants for HumidityControlSetpointGetSetpointType
constantHumidityControlSetpointGetSetpointType.put(0x00, "HUMIDIFIER");
constantHumidityControlSetpointGetSetpointType.put(0x01, "DEHUMIDIFIER");
// Constants for HumidityControlSetpointCapabilitiesGetSetpointType
constantHumidityControlSetpointCapabilitiesGetSetpointType.put(0x00, "HUMIDIFIER");
constantHumidityControlSetpointCapabilitiesGetSetpointType.put(0x01, "DEHUMIDIFIER");
// Constants for HumidityControlSetpointSupportedReportBitMask
constantHumidityControlSetpointSupportedReportBitMask.put(0x01, "HUMIDIFIER");
constantHumidityControlSetpointSupportedReportBitMask.put(0x02, "DEHUMIDIFIER");
// Constants for HumidityControlSetpointScaleSupportedGetSetpointType
constantHumidityControlSetpointScaleSupportedGetSetpointType.put(0x00, "HUMIDIFIER");
constantHumidityControlSetpointScaleSupportedGetSetpointType.put(0x01, "DEHUMIDIFIER");
// Constants for HumidityControlSetpointSetSetpointType
constantHumidityControlSetpointSetSetpointType.put(0x00, "HUMIDIFIER");
constantHumidityControlSetpointSetSetpointType.put(0x01, "DEHUMIDIFIER");
// Constants for HumidityControlSetpointReportScale
constantHumidityControlSetpointReportScale.put(0x00, "PERCENTAGE");
constantHumidityControlSetpointReportScale.put(0x01, "ABSOLUTE");
// Constants for HumidityControlSetpointCapabilitiesReportSetpointType
constantHumidityControlSetpointCapabilitiesReportSetpointType.put(0x00, "HUMIDIFIER");
constantHumidityControlSetpointCapabilitiesReportSetpointType.put(0x01, "DEHUMIDIFIER");
// Constants for HumidityControlSetpointReportSetpointType
constantHumidityControlSetpointReportSetpointType.put(0x00, "HUMIDIFIER");
constantHumidityControlSetpointReportSetpointType.put(0x01, "DEHUMIDIFIER");
// Constants for HumidityControlSetpointCapabilitiesReportScale2
constantHumidityControlSetpointCapabilitiesReportScale2.put(0x00, "PERCENTAGE");
constantHumidityControlSetpointCapabilitiesReportScale2.put(0x01, "ABSOLUTE");
// Constants for HumidityControlSetpointCapabilitiesReportScale1
constantHumidityControlSetpointCapabilitiesReportScale1.put(0x00, "PERCENTAGE");
constantHumidityControlSetpointCapabilitiesReportScale1.put(0x01, "ABSOLUTE");
// Constants for HumidityControlSetpointScaleSupportedReportScaleBitMask
constantHumidityControlSetpointScaleSupportedReportScaleBitMask.put(0x00, "PERCENTAGE");
constantHumidityControlSetpointScaleSupportedReportScaleBitMask.put(0x01, "ABSOLUTE");
// Constants for HumidityControlSetpointSetScale
constantHumidityControlSetpointSetScale.put(0x00, "PERCENTAGE");
constantHumidityControlSetpointSetScale.put(0x01, "ABSOLUTE");
}
/**
* Creates a new message with the HUMIDITY_CONTROL_SETPOINT_SET command.
* <p>
* Humidity Control Setpoint Set
*
* @param setpointType {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>HUMIDIFIER
* <li>DEHUMIDIFIER
* </ul>
* @param scale {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>PERCENTAGE
* <li>ABSOLUTE
* </ul>
* @param precision {@link Integer}
* @param value {@link byte[]}
* @return the {@link byte[]} array with the command to send
*/
static public byte[] getHumidityControlSetpointSet(String setpointType, String scale, Integer precision,
byte[] value) {
logger.debug("Creating command message HUMIDITY_CONTROL_SETPOINT_SET version 1");
ByteArrayOutputStream outputData = new ByteArrayOutputStream();
outputData.write(COMMAND_CLASS_KEY);
outputData.write(HUMIDITY_CONTROL_SETPOINT_SET);
// Process 'Properties1'
int varSetpointType = Integer.MAX_VALUE;
for (Integer entry : constantHumidityControlSetpointSetSetpointType.keySet()) {
if (constantHumidityControlSetpointSetSetpointType.get(entry).equals(setpointType)) {
varSetpointType = entry;
break;
}
}
if (varSetpointType == Integer.MAX_VALUE) {
throw new IllegalArgumentException("Unknown constant value '" + setpointType + "' for setpointType");
}
outputData.write(varSetpointType & 0x0F);
// Process 'Properties2'
// Size is used by 'Value'
int size = value.length;
int valProperties2 = 0;
valProperties2 |= size & 0x07;
int varScale = Integer.MAX_VALUE;
for (Integer entry : constantHumidityControlSetpointSetScale.keySet()) {
if (constantHumidityControlSetpointSetScale.get(entry).equals(scale)) {
varScale = entry;
break;
}
}
if (varScale == Integer.MAX_VALUE) {
throw new IllegalArgumentException("Unknown constant value '" + scale + "' for scale");
}
valProperties2 |= varScale << 3 & 0x18;
valProperties2 |= ((precision << 5) & 0xE0);
outputData.write(valProperties2);
// Process 'Value'
if (value != null) {
try {
outputData.write(value);
} catch (IOException e) {
}
}
return outputData.toByteArray();
}
/**
* Processes a received frame with the HUMIDITY_CONTROL_SETPOINT_SET command.
* <p>
* Humidity Control Setpoint Set
* <p>
* The output data {@link Map} has the following properties -:
*
* <ul>
* <li>SETPOINT_TYPE {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>HUMIDIFIER
* <li>DEHUMIDIFIER
* </ul>
* <li>SCALE {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>PERCENTAGE
* <li>ABSOLUTE
* </ul>
* <li>PRECISION {@link Integer}
* <li>VALUE {@link byte[]}
* </ul>
*
* @param payload the {@link byte[]} payload data to process
* @return a {@link Map} of processed response data
*/
public static Map<String, Object> handleHumidityControlSetpointSet(byte[] payload) {
// Create our response map
Map<String, Object> response = new HashMap<String, Object>();
// We're using variable length fields, so track the offset
int msgOffset = 2;
// Process 'Properties1'
response.put("SETPOINT_TYPE", constantHumidityControlSetpointSetSetpointType.get(payload[msgOffset] & 0x0F));
msgOffset += 1;
// Process 'Properties2'
// Size is used by 'Value'
int varSize = payload[msgOffset] & 0x07;
response.put("SCALE", constantHumidityControlSetpointSetScale.get((payload[msgOffset] & 0x18) >> 3));
response.put("PRECISION", Integer.valueOf(payload[msgOffset] & 0xE0 >> 5));
msgOffset += 1;
// Process 'Value'
ByteArrayOutputStream valValue = new ByteArrayOutputStream();
for (int cntValue = 0; cntValue < varSize; cntValue++) {
valValue.write(payload[msgOffset + cntValue]);
}
response.put("VALUE", valValue.toByteArray());
msgOffset += varSize;
// Return the map of processed response data;
return response;
}
/**
* Creates a new message with the HUMIDITY_CONTROL_SETPOINT_GET command.
* <p>
* Humidity Control Setpoint Get
*
* @param setpointType {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>HUMIDIFIER
* <li>DEHUMIDIFIER
* </ul>
* @return the {@link byte[]} array with the command to send
*/
static public byte[] getHumidityControlSetpointGet(String setpointType) {
logger.debug("Creating command message HUMIDITY_CONTROL_SETPOINT_GET version 1");
ByteArrayOutputStream outputData = new ByteArrayOutputStream();
outputData.write(COMMAND_CLASS_KEY);
outputData.write(HUMIDITY_CONTROL_SETPOINT_GET);
// Process 'Properties1'
int varSetpointType = Integer.MAX_VALUE;
for (Integer entry : constantHumidityControlSetpointGetSetpointType.keySet()) {
if (constantHumidityControlSetpointGetSetpointType.get(entry).equals(setpointType)) {
varSetpointType = entry;
break;
}
}
if (varSetpointType == Integer.MAX_VALUE) {
throw new IllegalArgumentException("Unknown constant value '" + setpointType + "' for setpointType");
}
outputData.write(varSetpointType & 0x0F);
return outputData.toByteArray();
}
/**
* Processes a received frame with the HUMIDITY_CONTROL_SETPOINT_GET command.
* <p>
* Humidity Control Setpoint Get
* <p>
* The output data {@link Map} has the following properties -:
*
* <ul>
* <li>SETPOINT_TYPE {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>HUMIDIFIER
* <li>DEHUMIDIFIER
* </ul>
* </ul>
*
* @param payload the {@link byte[]} payload data to process
* @return a {@link Map} of processed response data
*/
public static Map<String, Object> handleHumidityControlSetpointGet(byte[] payload) {
// Create our response map
Map<String, Object> response = new HashMap<String, Object>();
// Process 'Properties1'
response.put("SETPOINT_TYPE", constantHumidityControlSetpointGetSetpointType.get(payload[2] & 0x0F));
// Return the map of processed response data;
return response;
}
/**
* Creates a new message with the HUMIDITY_CONTROL_SETPOINT_REPORT command.
* <p>
* Humidity Control Setpoint Report
*
* @param setpointType {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>HUMIDIFIER
* <li>DEHUMIDIFIER
* </ul>
* @param scale {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>PERCENTAGE
* <li>ABSOLUTE
* </ul>
* @param precision {@link Integer}
* @param value {@link byte[]}
* @return the {@link byte[]} array with the command to send
*/
static public byte[] getHumidityControlSetpointReport(String setpointType, String scale, Integer precision,
byte[] value) {
logger.debug("Creating command message HUMIDITY_CONTROL_SETPOINT_REPORT version 1");
ByteArrayOutputStream outputData = new ByteArrayOutputStream();
outputData.write(COMMAND_CLASS_KEY);
outputData.write(HUMIDITY_CONTROL_SETPOINT_REPORT);
// Process 'Properties1'
int varSetpointType = Integer.MAX_VALUE;
for (Integer entry : constantHumidityControlSetpointReportSetpointType.keySet()) {
if (constantHumidityControlSetpointReportSetpointType.get(entry).equals(setpointType)) {
varSetpointType = entry;
break;
}
}
if (varSetpointType == Integer.MAX_VALUE) {
throw new IllegalArgumentException("Unknown constant value '" + setpointType + "' for setpointType");
}
outputData.write(varSetpointType & 0x0F);
// Process 'Properties2'
// Size is used by 'Value'
int size = value.length;
int valProperties2 = 0;
valProperties2 |= size & 0x07;
int varScale = Integer.MAX_VALUE;
for (Integer entry : constantHumidityControlSetpointReportScale.keySet()) {
if (constantHumidityControlSetpointReportScale.get(entry).equals(scale)) {
varScale = entry;
break;
}
}
if (varScale == Integer.MAX_VALUE) {
throw new IllegalArgumentException("Unknown constant value '" + scale + "' for scale");
}
valProperties2 |= varScale << 3 & 0x18;
valProperties2 |= ((precision << 5) & 0xE0);
outputData.write(valProperties2);
// Process 'Value'
if (value != null) {
try {
outputData.write(value);
} catch (IOException e) {
}
}
return outputData.toByteArray();
}
/**
* Processes a received frame with the HUMIDITY_CONTROL_SETPOINT_REPORT command.
* <p>
* Humidity Control Setpoint Report
* <p>
* The output data {@link Map} has the following properties -:
*
* <ul>
* <li>SETPOINT_TYPE {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>HUMIDIFIER
* <li>DEHUMIDIFIER
* </ul>
* <li>SCALE {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>PERCENTAGE
* <li>ABSOLUTE
* </ul>
* <li>PRECISION {@link Integer}
* <li>VALUE {@link byte[]}
* </ul>
*
* @param payload the {@link byte[]} payload data to process
* @return a {@link Map} of processed response data
*/
public static Map<String, Object> handleHumidityControlSetpointReport(byte[] payload) {
// Create our response map
Map<String, Object> response = new HashMap<String, Object>();
// We're using variable length fields, so track the offset
int msgOffset = 2;
// Process 'Properties1'
response.put("SETPOINT_TYPE", constantHumidityControlSetpointReportSetpointType.get(payload[msgOffset] & 0x0F));
msgOffset += 1;
// Process 'Properties2'
// Size is used by 'Value'
int varSize = payload[msgOffset] & 0x07;
response.put("SCALE", constantHumidityControlSetpointReportScale.get((payload[msgOffset] & 0x18) >> 3));
response.put("PRECISION", Integer.valueOf(payload[msgOffset] & 0xE0 >> 5));
msgOffset += 1;
// Process 'Value'
ByteArrayOutputStream valValue = new ByteArrayOutputStream();
for (int cntValue = 0; cntValue < varSize; cntValue++) {
valValue.write(payload[msgOffset + cntValue]);
}
response.put("VALUE", valValue.toByteArray());
msgOffset += varSize;
// Return the map of processed response data;
return response;
}
/**
* Creates a new message with the HUMIDITY_CONTROL_SETPOINT_SUPPORTED_GET command.
* <p>
* Humidity Control Setpoint Supported Get
*
* @return the {@link byte[]} array with the command to send
*/
static public byte[] getHumidityControlSetpointSupportedGet() {
logger.debug("Creating command message HUMIDITY_CONTROL_SETPOINT_SUPPORTED_GET version 1");
ByteArrayOutputStream outputData = new ByteArrayOutputStream();
outputData.write(COMMAND_CLASS_KEY);
outputData.write(HUMIDITY_CONTROL_SETPOINT_SUPPORTED_GET);
return outputData.toByteArray();
}
/**
* Processes a received frame with the HUMIDITY_CONTROL_SETPOINT_SUPPORTED_GET command.
* <p>
* Humidity Control Setpoint Supported Get
*
* @param payload the {@link byte[]} payload data to process
* @return a {@link Map} of processed response data
*/
public static Map<String, Object> handleHumidityControlSetpointSupportedGet(byte[] payload) {
// Create our response map
Map<String, Object> response = new HashMap<String, Object>();
// Return the map of processed response data;
return response;
}
/**
* Creates a new message with the HUMIDITY_CONTROL_SETPOINT_SUPPORTED_REPORT command.
* <p>
* Humidity Control Setpoint Supported Report
*
* @param bitMask {@link List<String>}
* Can be one of the following -:
* <p>
* <ul>
* <li>HUMIDIFIER
* <li>DEHUMIDIFIER
* </ul>
* @return the {@link byte[]} array with the command to send
*/
static public byte[] getHumidityControlSetpointSupportedReport(List<String> bitMask) {
logger.debug("Creating command message HUMIDITY_CONTROL_SETPOINT_SUPPORTED_REPORT version 1");
ByteArrayOutputStream outputData = new ByteArrayOutputStream();
outputData.write(COMMAND_CLASS_KEY);
outputData.write(HUMIDITY_CONTROL_SETPOINT_SUPPORTED_REPORT);
// Process 'Bit Mask'
int valBitMask = 0;
for (String value : bitMask) {
boolean foundBitMask = false;
for (Integer entry : constantHumidityControlSetpointSupportedReportBitMask.keySet()) {
if (constantHumidityControlSetpointSupportedReportBitMask.get(entry).equals(value)) {
foundBitMask = true;
valBitMask += entry;
break;
}
}
if (!foundBitMask) {
throw new IllegalArgumentException("Unknown constant value '" + bitMask + "' for bitMask");
}
}
outputData.write(valBitMask);
return outputData.toByteArray();
}
/**
* Processes a received frame with the HUMIDITY_CONTROL_SETPOINT_SUPPORTED_REPORT command.
* <p>
* Humidity Control Setpoint Supported Report
* <p>
* The output data {@link Map} has the following properties -:
*
* <ul>
* <li>BIT_MASK {@link List}<{@link String}>
* Can be one of the following -:
* <p>
* <ul>
* <li>HUMIDIFIER
* <li>DEHUMIDIFIER
* </ul>
* </ul>
*
* @param payload the {@link byte[]} payload data to process
* @return a {@link Map} of processed response data
*/
public static Map<String, Object> handleHumidityControlSetpointSupportedReport(byte[] payload) {
// Create our response map
Map<String, Object> response = new HashMap<String, Object>();
// Process 'Bit Mask'
List<String> responseBitMask = new ArrayList<String>();
int lenBitMask = 1;
for (int cntBitMask = 0; cntBitMask < lenBitMask; cntBitMask++) {
if ((payload[2 + (cntBitMask / 8)] & (1 << cntBitMask % 8)) == 0) {
continue;
}
responseBitMask.add(constantHumidityControlSetpointSupportedReportBitMask.get(cntBitMask));
}
response.put("BIT_MASK", responseBitMask);
// Return the map of processed response data;
return response;
}
/**
* Creates a new message with the HUMIDITY_CONTROL_SETPOINT_SCALE_SUPPORTED_GET command.
* <p>
* Humidity Control Setpoint Scale Supported Get
*
* @param setpointType {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>HUMIDIFIER
* <li>DEHUMIDIFIER
* </ul>
* @return the {@link byte[]} array with the command to send
*/
static public byte[] getHumidityControlSetpointScaleSupportedGet(String setpointType) {
logger.debug("Creating command message HUMIDITY_CONTROL_SETPOINT_SCALE_SUPPORTED_GET version 1");
ByteArrayOutputStream outputData = new ByteArrayOutputStream();
outputData.write(COMMAND_CLASS_KEY);
outputData.write(HUMIDITY_CONTROL_SETPOINT_SCALE_SUPPORTED_GET);
// Process 'Properties1'
int varSetpointType = Integer.MAX_VALUE;
for (Integer entry : constantHumidityControlSetpointScaleSupportedGetSetpointType.keySet()) {
if (constantHumidityControlSetpointScaleSupportedGetSetpointType.get(entry).equals(setpointType)) {
varSetpointType = entry;
break;
}
}
if (varSetpointType == Integer.MAX_VALUE) {
throw new IllegalArgumentException("Unknown constant value '" + setpointType + "' for setpointType");
}
outputData.write(varSetpointType & 0x0F);
return outputData.toByteArray();
}
/**
* Processes a received frame with the HUMIDITY_CONTROL_SETPOINT_SCALE_SUPPORTED_GET command.
* <p>
* Humidity Control Setpoint Scale Supported Get
* <p>
* The output data {@link Map} has the following properties -:
*
* <ul>
* <li>SETPOINT_TYPE {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>HUMIDIFIER
* <li>DEHUMIDIFIER
* </ul>
* </ul>
*
* @param payload the {@link byte[]} payload data to process
* @return a {@link Map} of processed response data
*/
public static Map<String, Object> handleHumidityControlSetpointScaleSupportedGet(byte[] payload) {
// Create our response map
Map<String, Object> response = new HashMap<String, Object>();
// Process 'Properties1'
response.put("SETPOINT_TYPE", constantHumidityControlSetpointScaleSupportedGetSetpointType.get(payload[2] & 0x0F));
// Return the map of processed response data;
return response;
}
/**
* Creates a new message with the HUMIDITY_CONTROL_SETPOINT_SCALE_SUPPORTED_REPORT command.
* <p>
* Humidity Control Setpoint Scale Supported Report
*
* @param scaleBitMask {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>PERCENTAGE
* <li>ABSOLUTE
* </ul>
* @return the {@link byte[]} array with the command to send
*/
static public byte[] getHumidityControlSetpointScaleSupportedReport(String scaleBitMask) {
logger.debug("Creating command message HUMIDITY_CONTROL_SETPOINT_SCALE_SUPPORTED_REPORT version 1");
ByteArrayOutputStream outputData = new ByteArrayOutputStream();
outputData.write(COMMAND_CLASS_KEY);
outputData.write(HUMIDITY_CONTROL_SETPOINT_SCALE_SUPPORTED_REPORT);
// Process 'Properties1'
int varScaleBitMask = Integer.MAX_VALUE;
for (Integer entry : constantHumidityControlSetpointScaleSupportedReportScaleBitMask.keySet()) {
if (constantHumidityControlSetpointScaleSupportedReportScaleBitMask.get(entry).equals(scaleBitMask)) {
varScaleBitMask = entry;
break;
}
}
if (varScaleBitMask == Integer.MAX_VALUE) {
throw new IllegalArgumentException("Unknown constant value '" + scaleBitMask + "' for scaleBitMask");
}
outputData.write(varScaleBitMask & 0x0F);
return outputData.toByteArray();
}
/**
* Processes a received frame with the HUMIDITY_CONTROL_SETPOINT_SCALE_SUPPORTED_REPORT command.
* <p>
* Humidity Control Setpoint Scale Supported Report
* <p>
* The output data {@link Map} has the following properties -:
*
* <ul>
* <li>SCALE_BIT_MASK {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>PERCENTAGE
* <li>ABSOLUTE
* </ul>
* </ul>
*
* @param payload the {@link byte[]} payload data to process
* @return a {@link Map} of processed response data
*/
public static Map<String, Object> handleHumidityControlSetpointScaleSupportedReport(byte[] payload) {
// Create our response map
Map<String, Object> response = new HashMap<String, Object>();
// Process 'Properties1'
response.put("SCALE_BIT_MASK", constantHumidityControlSetpointScaleSupportedReportScaleBitMask.get(payload[2] & 0x0F));
// Return the map of processed response data;
return response;
}
/**
* Creates a new message with the HUMIDITY_CONTROL_SETPOINT_CAPABILITIES_GET command.
* <p>
* Humidity Control Setpoint Capabilities Get
*
* @param setpointType {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>HUMIDIFIER
* <li>DEHUMIDIFIER
* </ul>
* @return the {@link byte[]} array with the command to send
*/
static public byte[] getHumidityControlSetpointCapabilitiesGet(String setpointType) {
logger.debug("Creating command message HUMIDITY_CONTROL_SETPOINT_CAPABILITIES_GET version 1");
ByteArrayOutputStream outputData = new ByteArrayOutputStream();
outputData.write(COMMAND_CLASS_KEY);
outputData.write(HUMIDITY_CONTROL_SETPOINT_CAPABILITIES_GET);
// Process 'Properties1'
int varSetpointType = Integer.MAX_VALUE;
for (Integer entry : constantHumidityControlSetpointCapabilitiesGetSetpointType.keySet()) {
if (constantHumidityControlSetpointCapabilitiesGetSetpointType.get(entry).equals(setpointType)) {
varSetpointType = entry;
break;
}
}
if (varSetpointType == Integer.MAX_VALUE) {
throw new IllegalArgumentException("Unknown constant value '" + setpointType + "' for setpointType");
}
outputData.write(varSetpointType & 0x0F);
return outputData.toByteArray();
}
/**
* Processes a received frame with the HUMIDITY_CONTROL_SETPOINT_CAPABILITIES_GET command.
* <p>
* Humidity Control Setpoint Capabilities Get
* <p>
* The output data {@link Map} has the following properties -:
*
* <ul>
* <li>SETPOINT_TYPE {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>HUMIDIFIER
* <li>DEHUMIDIFIER
* </ul>
* </ul>
*
* @param payload the {@link byte[]} payload data to process
* @return a {@link Map} of processed response data
*/
public static Map<String, Object> handleHumidityControlSetpointCapabilitiesGet(byte[] payload) {
// Create our response map
Map<String, Object> response = new HashMap<String, Object>();
// Process 'Properties1'
response.put("SETPOINT_TYPE", constantHumidityControlSetpointCapabilitiesGetSetpointType.get(payload[2] & 0x0F));
// Return the map of processed response data;
return response;
}
/**
* Creates a new message with the HUMIDITY_CONTROL_SETPOINT_CAPABILITIES_REPORT command.
* <p>
* Humidity Control Setpoint Capabilities Report
*
* @param setpointType {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>HUMIDIFIER
* <li>DEHUMIDIFIER
* </ul>
* @param scale1 {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>PERCENTAGE
* <li>ABSOLUTE
* </ul>
* @param precision1 {@link Integer}
* @param minimumValue {@link byte[]}
* @param scale2 {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>PERCENTAGE
* <li>ABSOLUTE
* </ul>
* @param precision2 {@link Integer}
* @param maximumValue {@link byte[]}
* @return the {@link byte[]} array with the command to send
*/
static public byte[] getHumidityControlSetpointCapabilitiesReport(String setpointType, String scale1,
Integer precision1, byte[] minimumValue, String scale2, Integer precision2, byte[] maximumValue) {
logger.debug("Creating command message HUMIDITY_CONTROL_SETPOINT_CAPABILITIES_REPORT version 1");
ByteArrayOutputStream outputData = new ByteArrayOutputStream();
outputData.write(COMMAND_CLASS_KEY);
outputData.write(HUMIDITY_CONTROL_SETPOINT_CAPABILITIES_REPORT);
// Process 'Properties1'
int varSetpointType = Integer.MAX_VALUE;
for (Integer entry : constantHumidityControlSetpointCapabilitiesReportSetpointType.keySet()) {
if (constantHumidityControlSetpointCapabilitiesReportSetpointType.get(entry).equals(setpointType)) {
varSetpointType = entry;
break;
}
}
if (varSetpointType == Integer.MAX_VALUE) {
throw new IllegalArgumentException("Unknown constant value '" + setpointType + "' for setpointType");
}
outputData.write(varSetpointType & 0x0F);
// Process 'Properties2'
// Size1 is used by 'Minimum Value'
int size1 = minimumValue.length;
int valProperties2 = 0;
valProperties2 |= size1 & 0x07;
int varScale1 = Integer.MAX_VALUE;
for (Integer entry : constantHumidityControlSetpointCapabilitiesReportScale1.keySet()) {
if (constantHumidityControlSetpointCapabilitiesReportScale1.get(entry).equals(scale1)) {
varScale1 = entry;
break;
}
}
if (varScale1 == Integer.MAX_VALUE) {
throw new IllegalArgumentException("Unknown constant value '" + scale1 + "' for scale1");
}
valProperties2 |= varScale1 << 3 & 0x18;
valProperties2 |= ((precision1 << 5) & 0xE0);
outputData.write(valProperties2);
// Process 'Minimum Value'
if (minimumValue != null) {
try {
outputData.write(minimumValue);
} catch (IOException e) {
}
}
// Process 'Properties3'
// Size2 is used by 'Maximum Value'
int size2 = maximumValue.length;
int valProperties3 = 0;
valProperties3 |= size2 & 0x07;
int varScale2 = Integer.MAX_VALUE;
for (Integer entry : constantHumidityControlSetpointCapabilitiesReportScale2.keySet()) {
if (constantHumidityControlSetpointCapabilitiesReportScale2.get(entry).equals(scale2)) {
varScale2 = entry;
break;
}
}
if (varScale2 == Integer.MAX_VALUE) {
throw new IllegalArgumentException("Unknown constant value '" + scale2 + "' for scale2");
}
valProperties3 |= varScale2 << 3 & 0x18;
valProperties3 |= ((precision2 << 5) & 0xE0);
outputData.write(valProperties3);
// Process 'Maximum Value'
if (maximumValue != null) {
try {
outputData.write(maximumValue);
} catch (IOException e) {
}
}
return outputData.toByteArray();
}
/**
* Processes a received frame with the HUMIDITY_CONTROL_SETPOINT_CAPABILITIES_REPORT command.
* <p>
* Humidity Control Setpoint Capabilities Report
* <p>
* The output data {@link Map} has the following properties -:
*
* <ul>
* <li>SETPOINT_TYPE {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>HUMIDIFIER
* <li>DEHUMIDIFIER
* </ul>
* <li>SCALE1 {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>PERCENTAGE
* <li>ABSOLUTE
* </ul>
* <li>PRECISION1 {@link Integer}
* <li>MINIMUM_VALUE {@link byte[]}
* <li>SCALE2 {@link String}
* Can be one of the following -:
* <p>
* <ul>
* <li>PERCENTAGE
* <li>ABSOLUTE
* </ul>
* <li>PRECISION2 {@link Integer}
* <li>MAXIMUM_VALUE {@link byte[]}
* </ul>
*
* @param payload the {@link byte[]} payload data to process
* @return a {@link Map} of processed response data
*/
public static Map<String, Object> handleHumidityControlSetpointCapabilitiesReport(byte[] payload) {
// Create our response map
Map<String, Object> response = new HashMap<String, Object>();
// We're using variable length fields, so track the offset
int msgOffset = 2;
// Process 'Properties1'
response.put("SETPOINT_TYPE", constantHumidityControlSetpointCapabilitiesReportSetpointType.get(payload[msgOffset] & 0x0F));
msgOffset += 1;
// Process 'Properties2'
// Size1 is used by 'Minimum Value'
int varSize1 = payload[msgOffset] & 0x07;
response.put("SCALE1", constantHumidityControlSetpointCapabilitiesReportScale1.get((payload[msgOffset] & 0x18) >> 3));
response.put("PRECISION1", Integer.valueOf(payload[msgOffset] & 0xE0 >> 5));
msgOffset += 1;
// Process 'Minimum Value'
ByteArrayOutputStream valMinimumValue = new ByteArrayOutputStream();
for (int cntMinimumValue = 0; cntMinimumValue < varSize1; cntMinimumValue++) {
valMinimumValue.write(payload[msgOffset + cntMinimumValue]);
}
response.put("MINIMUM_VALUE", valMinimumValue.toByteArray());
msgOffset += varSize1;
// Process 'Properties3'
// Size2 is used by 'Maximum Value'
int varSize2 = payload[msgOffset] & 0x07;
response.put("SCALE2", constantHumidityControlSetpointCapabilitiesReportScale2.get((payload[msgOffset] & 0x18) >> 3));
response.put("PRECISION2", Integer.valueOf(payload[msgOffset] & 0xE0 >> 5));
msgOffset += 1;
// Process 'Maximum Value'
ByteArrayOutputStream valMaximumValue = new ByteArrayOutputStream();
for (int cntMaximumValue = 0; cntMaximumValue < varSize2; cntMaximumValue++) {
valMaximumValue.write(payload[msgOffset + cntMaximumValue]);
}
response.put("MAXIMUM_VALUE", valMaximumValue.toByteArray());
msgOffset += varSize2;
// Return the map of processed response data;
return response;
}
}
| zsmartsystems/com.zsmartsystems.zwave | com.zsmartsystems.zwave/src/main/java/com/zsmartsystems/zwave/commandclass/impl/CommandClassHumidityControlSetpointV1.java | Java | epl-1.0 | 39,425 |
/*******************************************************************************
* Copyright 2009 Regents of the University of Minnesota. All rights
* reserved.
* Copyright 2009 Mayo Foundation for Medical Education and Research.
* All rights reserved.
*
* This program is made available under the terms of the Eclipse
* Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* 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 INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS
* OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A
* PARTICULAR PURPOSE. See the License for the specific language
* governing permissions and limitations under the License.
*
* Contributors:
* Minnesota Supercomputing Institute - initial API and implementation
******************************************************************************/
package edu.umn.msi.tropix.storage.core;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import edu.umn.msi.tropix.common.io.HasStreamInputContext;
public interface StorageManager {
static interface UploadCallback {
void onUpload(InputStream inputStream);
}
static class FileMetadata {
private final long dateModified;
private final long length;
public FileMetadata(final long dateModified, final long length) {
this.dateModified = dateModified;
this.length = length;
}
public long getDateModified() {
return dateModified;
}
public long getLength() {
return length;
}
}
@Deprecated
long getDateModified(final String id, final String gridId);
boolean setDateModified(final String id, final String gridId, final long dataModified);
@Deprecated
long getLength(final String id, final String gridId);
FileMetadata getFileMetadata(final String id, final String gridId);
List<FileMetadata> getFileMetadata(final List<String> ids, final String gridId);
HasStreamInputContext download(String id, String gridId);
// Allow batch pre-checking to avoid extra database hits
HasStreamInputContext download(final String id, final String gridId, final boolean checkAccess);
UploadCallback upload(String id, String gridId);
OutputStream prepareUploadStream(final String id, final String gridId);
boolean delete(String id, String gridId);
boolean exists(String id);
boolean canDelete(String id, String callerIdentity);
boolean canDownload(String id, String callerIdentity);
boolean canUpload(String id, String callerIdentity);
}
| jmchilton/TINT | projects/TropixStorageCore/src/api/edu/umn/msi/tropix/storage/core/StorageManager.java | Java | epl-1.0 | 2,764 |
/*******************************************************************************
* Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.tools.workbench.mappingsmodel.handles;
import org.eclipse.persistence.tools.workbench.mappingsmodel.MWModel;
import org.eclipse.persistence.tools.workbench.mappingsmodel.meta.MWClass;
import org.eclipse.persistence.tools.workbench.mappingsmodel.meta.MWClassAttribute;
import org.eclipse.persistence.tools.workbench.utility.node.Node;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.mappings.OneToOneMapping;
import org.eclipse.persistence.oxm.XMLDescriptor;
/**
* MWAttributeHandle is used to isolate the painful bits of code
* necessary to correctly handle references to MWClassAttributes.
*
* Since a MWClassAttribute is nested within the XML file
* for a MWClass, we need to store a reference to a particular
* attribute as a pair of instance variables:
* - the name of the declaring MWClass
* - the name of the attribute
*
* This causes no end of pain when dealing with TopLink, property
* change listeners, backward-compatibility, etc.
*/
public final class MWAttributeHandle extends MWHandle {
/**
* This is the actual attribute.
* It is built from the declaring type and attribute names, below.
*/
private volatile MWClassAttribute attribute;
/**
* The declaring type and attribute names are transient. They
* are used only to hold their values until postProjectBuild()
* is called and we can resolve the actual attribute.
* We do not keep these in synch with the attribute itself because
* we cannot know when the attribute has been renamed etc.
*/
private volatile String attributeDeclaringTypeName;
private volatile String attributeName;
// ********** constructors **********
/**
* default constructor - for TopLink use only
*/
private MWAttributeHandle() {
super();
}
public MWAttributeHandle(MWModel parent, NodeReferenceScrubber scrubber) {
super(parent, scrubber);
}
public MWAttributeHandle(MWModel parent, MWClassAttribute attribute, NodeReferenceScrubber scrubber) {
super(parent, scrubber);
this.attribute = attribute;
}
// ********** instance methods **********
public MWClassAttribute getAttribute() {
return this.attribute;
}
public void setAttribute(MWClassAttribute attribute) {
this.attribute = attribute;
}
protected Node node() {
return getAttribute();
}
public MWAttributeHandle setScrubber(NodeReferenceScrubber scrubber) {
this.setScrubberInternal(scrubber);
return this;
}
public void postProjectBuild() {
super.postProjectBuild();
if (this.attributeDeclaringTypeName != null && this.attributeName != null) {
// the type will never be null - the repository will auto-generate one if necessary
this.attribute = this.typeNamed(this.attributeDeclaringTypeName).attributeNamedFromCombinedAll(this.attributeName);
}
// Ensure attributeDeclaringTypeName and attributeName are not
// used by setting them to null....
// If the XML is corrupt and only one of these attributes is populated,
// this will cause the populated attribute to be cleared out if the
// objects are rewritten.
this.attributeDeclaringTypeName = null;
this.attributeName = null;
}
/**
* Override to delegate comparison to the attribute itself.
* If the handles being compared are in a collection that is being sorted,
* NEITHER attribute should be null.
*/
public int compareTo(Object o) {
return this.attribute.compareTo(((MWAttributeHandle) o).attribute);
}
public void toString(StringBuffer sb) {
if (this.attribute == null) {
sb.append("null");
} else {
this.attribute.toString(sb);
}
}
// ********** TopLink methods **********
public static XMLDescriptor buildDescriptor(){
XMLDescriptor descriptor = new XMLDescriptor();
descriptor.setJavaClass(MWAttributeHandle.class);
descriptor.addDirectMapping("attributeDeclaringTypeName", "getAttributeDeclaringTypeNameForTopLink", "setAttributeDeclaringTypeNameForTopLink", "attribute-declaring-type-name/text()");
descriptor.addDirectMapping("attributeName", "getAttributeNameForTopLink", "setAttributeNameForTopLink", "attribute-name/text()");
return descriptor;
}
private String getAttributeDeclaringTypeNameForTopLink(){
return (this.attribute == null) ? null : this.attribute.getDeclaringType().getName();
}
private void setAttributeDeclaringTypeNameForTopLink(String attributeDeclaringTypeName){
this.attributeDeclaringTypeName = attributeDeclaringTypeName;
}
private String getAttributeNameForTopLink() {
return (this.attribute == null) ? null : attribute.getName();
}
private void setAttributeNameForTopLink(String attributeName) {
this.attributeName = attributeName;
}
}
| bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs | utils/eclipselink.utils.workbench/mappingsmodel/source/org/eclipse/persistence/tools/workbench/mappingsmodel/handles/MWAttributeHandle.java | Java | epl-1.0 | 5,578 |
<!DOCTYPE html>
<html lang="{{App::getLocale()}}">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{ config('app.name') }} - Authorization</title>
<!-- Styles -->
<link href="/css/app.css" rel="stylesheet">
<style>
.passport-authorize .container {
margin-top: 30px;
}
.passport-authorize .scopes {
margin-top: 20px;
}
.passport-authorize .buttons {
margin-top: 25px;
text-align: center;
}
.passport-authorize .btn {
width: 125px;
}
.passport-authorize .btn-approve {
margin-right: 15px;
}
.passport-authorize form {
display: inline;
}
</style>
</head>
<body class="passport-authorize">
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-default">
<div class="panel-heading">
Authorization Request
</div>
<div class="panel-body">
<!-- Introduction -->
<p><strong>{{ $client->name }}</strong> is requesting permission to access your account.</p>
<!-- Scope List -->
@if (count($scopes) > 0)
<div class="scopes">
<p><strong>This application will be able to:</strong></p>
<ul>
@foreach ($scopes as $scope)
<li>{{ $scope->description }}</li>
@endforeach
</ul>
</div>
@endif
<div class="buttons">
<!-- Authorize Button -->
<form method="post" action="/oauth/authorize">
{{ csrf_field() }}
<input type="hidden" name="state" value="{{ $request->state }}">
<input type="hidden" name="client_id" value="{{ $client->id }}">
<button type="submit" class="btn btn-success btn-approve">Authorize</button>
</form>
<!-- Cancel Button -->
<form method="post" action="/oauth/authorize">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<input type="hidden" name="state" value="{{ $request->state }}">
<input type="hidden" name="client_id" value="{{ $client->id }}">
<button class="btn btn-danger">Cancel</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
| wcadena/inventarioFinalApp | resources/views/vendor/passport/authorize.blade.php | PHP | epl-1.0 | 3,248 |
var config = {
type: Phaser.CANVAS,
width: 800,
height: 600,
parent: 'phaser-example',
backgroundColor: '#2d2d2d',
useTicker: true,
scene: {
preload: preload,
create: create,
update: update
}
};
var image;
var time;
var delta;
var speed = (600 / 2) / 1000;
var game = new Phaser.Game(config);
function preload ()
{
this.load.image('bunny', 'assets/sprites/bunny.png');
this.load.atlas('gems', 'assets/tests/columns/gems.png', 'assets/tests/columns/gems.json');
}
function create ()
{
delta = this.add.text(32, 32);
time = this.add.text(500, 400);
image = this.add.image(0, 200, 'bunny');
this.anims.create({ key: 'diamond', frames: this.anims.generateFrameNames('gems', { prefix: 'diamond_', end: 15, zeroPad: 4 }), repeat: -1 });
this.anims.create({ key: 'prism', frames: this.anims.generateFrameNames('gems', { prefix: 'prism_', end: 6, zeroPad: 4 }), repeat: -1 });
this.anims.create({ key: 'ruby', frames: this.anims.generateFrameNames('gems', { prefix: 'ruby_', end: 6, zeroPad: 4 }), repeat: -1 });
this.anims.create({ key: 'square', frames: this.anims.generateFrameNames('gems', { prefix: 'square_', end: 14, zeroPad: 4 }), repeat: -1 });
this.add.sprite(400, 100, 'gems').play('diamond');
this.add.sprite(400, 200, 'gems').play('prism');
this.add.sprite(400, 300, 'gems').play('ruby');
this.add.sprite(400, 400, 'gems').play('square');
}
function update (timestep, dt)
{
image.x += speed * dt;
if (image.x > 1000)
{
image.x = 0;
}
time.setText('time: ' + this.sys.game.loop.time.toString());
delta.setText(this.sys.game.loop.deltaHistory);
}
| boniatillo-com/PhaserEditor | source/v2/phasereditor/phasereditor.resources.phaser.examples/phaser3-examples/public/src/timestep/delta history.js | JavaScript | epl-1.0 | 1,701 |
/*******************************************************************************
* Copyright (c) 2014 Bruno Medeiros and other Contributors.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Bruno Medeiros - initial API and implementation
*******************************************************************************/
package melnorme.util.swt.components.fields;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Spinner;
import melnorme.util.swt.SWTLayoutUtil;
import melnorme.util.swt.SWTUtil;
import melnorme.util.swt.components.FieldComponent;
import melnorme.util.swt.components.LabelledFieldComponent;
public class SpinnerNumberField extends LabelledFieldComponent<Integer> {
protected Spinner spinner;
public SpinnerNumberField(String labelText) {
super(labelText, Option_AllowNull.NO, 0);
}
@Override
public int getPreferredLayoutColumns() {
return 2;
}
@Override
protected void createContents_all(Composite topControl) {
createContents_Label(topControl);
createContents_Spinner(topControl);
}
@Override
protected void createContents_layout() {
SWTLayoutUtil.layout2Controls_spanLast(label, spinner);
}
protected void createContents_Spinner(Composite parent) {
spinner = createFieldSpinner(this, parent, SWT.BORDER);
}
public Spinner getSpinner() {
return spinner;
}
@Override
public Spinner getFieldControl() {
return spinner;
}
@Override
protected void doUpdateComponentFromValue() {
spinner.setSelection(getFieldValue());
}
public SpinnerNumberField setValueMinimum(int minimum) {
spinner.setMinimum(minimum);
return this;
}
public SpinnerNumberField setValueMaximum(int maximum) {
spinner.setMaximum(maximum);
return this;
}
public SpinnerNumberField setValueIncrement(int increment) {
spinner.setIncrement(increment);
return this;
}
@Override
public void setEnabled(boolean enabled) {
SWTUtil.setEnabledIfOk(label, enabled);
SWTUtil.setEnabledIfOk(spinner, enabled);
}
/* ----------------- ----------------- */
public static Spinner createFieldSpinner(FieldComponent<Integer> field, Composite parent, int style) {
final Spinner spinner = new Spinner(parent, style);
spinner.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
field.setFieldValueFromControl(spinner.getSelection());
}
});
return spinner;
}
} | happyspace/goclipse | plugin_ide.ui/src-lang/melnorme/util/swt/components/fields/SpinnerNumberField.java | Java | epl-1.0 | 2,850 |
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package ucm.map;
import core.COREModel;
import org.eclipse.emf.common.util.EList;
import urncore.IURNDiagram;
import urncore.UCMmodelElement;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>UC Mmap</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link ucm.map.UCMmap#isSingleton <em>Singleton</em>}</li>
* <li>{@link ucm.map.UCMmap#getParentStub <em>Parent Stub</em>}</li>
* </ul>
* </p>
*
* @see ucm.map.MapPackage#getUCMmap()
* @model
* @generated
*/
public interface UCMmap extends UCMmodelElement, IURNDiagram, COREModel {
/**
* Returns the value of the '<em><b>Singleton</b></em>' attribute.
* The default value is <code>"true"</code>.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Singleton</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Singleton</em>' attribute.
* @see #setSingleton(boolean)
* @see ucm.map.MapPackage#getUCMmap_Singleton()
* @model default="true"
* @generated
*/
boolean isSingleton();
/**
* Sets the value of the '{@link ucm.map.UCMmap#isSingleton <em>Singleton</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Singleton</em>' attribute.
* @see #isSingleton()
* @generated
*/
void setSingleton(boolean value);
/**
* Returns the value of the '<em><b>Parent Stub</b></em>' reference list.
* The list contents are of type {@link ucm.map.PluginBinding}.
* It is bidirectional and its opposite is '{@link ucm.map.PluginBinding#getPlugin <em>Plugin</em>}'.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Parent Stub</em>' reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Parent Stub</em>' reference list.
* @see ucm.map.MapPackage#getUCMmap_ParentStub()
* @see ucm.map.PluginBinding#getPlugin
* @model type="ucm.map.PluginBinding" opposite="plugin"
* @generated
*/
EList getParentStub();
} // UCMmap
| gmussbacher/seg.jUCMNav | src/ucm/map/UCMmap.java | Java | epl-1.0 | 2,263 |
/**
*
*/
package com.eclipsesource.gerrit.plugins.fileattachment.api.test.converter;
import java.util.ArrayList;
import java.util.List;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Test;
import com.eclipsesource.gerrit.plugins.fileattachment.api.AttachmentTarget;
import com.eclipsesource.gerrit.plugins.fileattachment.api.AttachmentTargetDescription;
import com.eclipsesource.gerrit.plugins.fileattachment.api.FileDescription;
import com.eclipsesource.gerrit.plugins.fileattachment.api.entities.AttachmentTargetEntity;
import com.eclipsesource.gerrit.plugins.fileattachment.api.entities.AttachmentTargetEntity.TargetType;
import com.eclipsesource.gerrit.plugins.fileattachment.api.entities.AttachmentTargetResponseEntity;
import com.eclipsesource.gerrit.plugins.fileattachment.api.entities.FileDescriptionEntity;
import com.eclipsesource.gerrit.plugins.fileattachment.api.entities.OperationResultEntity;
import com.eclipsesource.gerrit.plugins.fileattachment.api.entities.OperationResultEntity.ResultStatus;
import com.eclipsesource.gerrit.plugins.fileattachment.api.entities.converter.BaseAttachmentTargetResponseEntityReader;
import com.eclipsesource.gerrit.plugins.fileattachment.api.impl.ChangeTargetDescription;
import com.eclipsesource.gerrit.plugins.fileattachment.api.impl.GenericFileDescription;
import com.eclipsesource.gerrit.plugins.fileattachment.api.impl.PatchSetTargetDescription;
import com.eclipsesource.gerrit.plugins.fileattachment.api.impl.PatchTarget;
import com.eclipsesource.gerrit.plugins.fileattachment.api.impl.PatchTargetDescription;
/**
* @author Florian Zoubek
*
*/
public class BaseAttachmentTargetResponseEntityReaderTest {
/**
* tests if the method
* {@link BaseAttachmentTargetResponseEntityReader#toObject(AttachmentTargetResponseEntity, com.eclipsesource.gerrit.plugins.fileattachment.api.AttachmentTargetDescription)}
* correctly handles Success responses with file descriptions.
*/
@Test
public void testSuccessConversionWithFiles() {
BaseAttachmentTargetResponseEntityReader entityReader =
new BaseAttachmentTargetResponseEntityReader();
// build expected result
PatchTargetDescription patchTargetDescription =
new PatchTargetDescription(new PatchSetTargetDescription(
new ChangeTargetDescription("I0000000000000000"), 0),
"/project/README");
List<FileDescription> expectedFileDescriptions =
new ArrayList<FileDescription>(2);
expectedFileDescriptions.add(new GenericFileDescription("/subdir/",
"file1.txt"));
expectedFileDescriptions.add(new GenericFileDescription("/subdir/",
"file2.txt"));
AttachmentTarget expectedAttachmentTarget =
new PatchTarget(patchTargetDescription, expectedFileDescriptions);
OperationResultEntity operationResultEntity =
new OperationResultEntity(ResultStatus.SUCCESS, "");
// build input parameters
FileDescriptionEntity[] fileDescriptionEntities =
new FileDescriptionEntity[2];
fileDescriptionEntities[0] =
new FileDescriptionEntity("/subdir/", "file1.txt");
fileDescriptionEntities[1] =
new FileDescriptionEntity("/subdir/", "file2.txt");
AttachmentTargetEntity attachmentTargetEntity =
new AttachmentTargetEntity(TargetType.PATCH, fileDescriptionEntities);
AttachmentTargetResponseEntity jsonEntity =
new AttachmentTargetResponseEntity(attachmentTargetEntity,
operationResultEntity);
// begin testing
AttachmentTarget attachmentTarget =
entityReader.toObject(jsonEntity, patchTargetDescription);
Assert.assertThat(attachmentTarget,
CoreMatchers.is(expectedAttachmentTarget));
}
/**
* tests if the method
* {@link BaseAttachmentTargetResponseEntityReader#toObject(AttachmentTargetResponseEntity, com.eclipsesource.gerrit.plugins.fileattachment.api.AttachmentTargetDescription)}
* correctly handles Success responses without file descriptions.
*/
@Test
public void testSuccessConversionWithoutFiles() {
BaseAttachmentTargetResponseEntityReader entityReader =
new BaseAttachmentTargetResponseEntityReader();
// build expected result
PatchTargetDescription patchTargetDescription =
new PatchTargetDescription(new PatchSetTargetDescription(
new ChangeTargetDescription("I0000000000000000"), 0),
"/project/README");
List<FileDescription> expectedFileDescriptions =
new ArrayList<FileDescription>(0);
AttachmentTarget expectedAttachmentTarget =
new PatchTarget(patchTargetDescription, expectedFileDescriptions);
OperationResultEntity operationResultEntity =
new OperationResultEntity(ResultStatus.SUCCESS, "");
// build input parameters
FileDescriptionEntity[] fileDescriptionEntities =
new FileDescriptionEntity[0];
AttachmentTargetEntity attachmentTargetEntity =
new AttachmentTargetEntity(TargetType.PATCH, fileDescriptionEntities);
AttachmentTargetResponseEntity jsonEntity =
new AttachmentTargetResponseEntity(attachmentTargetEntity,
operationResultEntity);
// begin testing
AttachmentTarget attachmentTarget =
entityReader.toObject(jsonEntity, patchTargetDescription);
Assert.assertThat(attachmentTarget,
CoreMatchers.is(expectedAttachmentTarget));
}
/**
* tests if the method
* {@link BaseAttachmentTargetResponseEntityReader#toObject(AttachmentTargetResponseEntity, com.eclipsesource.gerrit.plugins.fileattachment.api.AttachmentTargetDescription)}
* correctly handles unsupported attachment targets correctly.
*/
@Test
public void testInvalidAttachmentTargetConversion() {
BaseAttachmentTargetResponseEntityReader entityReader =
new BaseAttachmentTargetResponseEntityReader();
// build input parameters
OperationResultEntity operationResultEntity =
new OperationResultEntity(ResultStatus.SUCCESS, "");
FileDescriptionEntity[] fileDescriptionEntities =
new FileDescriptionEntity[0];
AttachmentTargetEntity attachmentTargetEntity =
new AttachmentTargetEntity(TargetType.PATCH, fileDescriptionEntities);
AttachmentTargetResponseEntity jsonEntity =
new AttachmentTargetResponseEntity(attachmentTargetEntity,
operationResultEntity);
// begin testing
// PatchSetTargetDescription
AttachmentTargetDescription attachmentTargetDescription =
new PatchSetTargetDescription(new ChangeTargetDescription(
"I0000000000000000"), 0);
AttachmentTarget attachmentTarget =
entityReader.toObject(jsonEntity, attachmentTargetDescription);
Assert.assertThat(attachmentTarget,
CoreMatchers.is(CoreMatchers.nullValue()));
// ChangeTargetDescription
attachmentTargetDescription =
new ChangeTargetDescription("I0000000000000000");
Assert.assertThat(attachmentTarget,
CoreMatchers.is(CoreMatchers.nullValue()));
}
/**
* tests if the method
* {@link BaseAttachmentTargetResponseEntityReader#toObject(AttachmentTargetResponseEntity, com.eclipsesource.gerrit.plugins.fileattachment.api.AttachmentTargetDescription)}
* correctly handles responses containing a failed operation result.
*/
@Test
public void testFailedOperationConversion() {
BaseAttachmentTargetResponseEntityReader entityReader =
new BaseAttachmentTargetResponseEntityReader();
OperationResultEntity operationResultEntity =
new OperationResultEntity(ResultStatus.FAILED, "Some error occured");
FileDescriptionEntity[] fileDescriptionEntities =
new FileDescriptionEntity[2];
fileDescriptionEntities[0] =
new FileDescriptionEntity("/subdir/", "file1.txt");
fileDescriptionEntities[1] =
new FileDescriptionEntity("/subdir/", "file2.txt");
for (TargetType targetType : TargetType.values()) {
// build input parameters
AttachmentTargetEntity attachmentTargetEntityWithFiles =
new AttachmentTargetEntity(targetType, new FileDescriptionEntity[0]);
AttachmentTargetResponseEntity jsonEntityWithFiles =
new AttachmentTargetResponseEntity(attachmentTargetEntityWithFiles,
operationResultEntity);
AttachmentTargetEntity attachmentTargetEntityWithoutFiles =
new AttachmentTargetEntity(targetType, new FileDescriptionEntity[0]);
AttachmentTargetResponseEntity jsonEntityWithoutFiles =
new AttachmentTargetResponseEntity(
attachmentTargetEntityWithoutFiles, operationResultEntity);
AttachmentTargetDescription attachmentTargetDescription =
new PatchTargetDescription(new PatchSetTargetDescription(
new ChangeTargetDescription("I0000000000000000"), 0),
"/project/README");
// begin testing
// without files
AttachmentTarget attachmentTarget =
entityReader.toObject(jsonEntityWithoutFiles,
attachmentTargetDescription);
Assert.assertThat("Unexpected result for failed operation with entity: "
+ jsonEntityWithoutFiles.toString(), attachmentTarget,
CoreMatchers.is(CoreMatchers.nullValue()));
// with files
attachmentTarget =
entityReader.toObject(jsonEntityWithFiles,
attachmentTargetDescription);
Assert.assertThat("Unexpected result for failed operation with entity: "
+ jsonEntityWithFiles.toString(), attachmentTarget,
CoreMatchers.is(CoreMatchers.nullValue()));
}
}
/**
* tests if the method
* {@link BaseAttachmentTargetResponseEntityReader#toObject(AttachmentTargetResponseEntity, com.eclipsesource.gerrit.plugins.fileattachment.api.AttachmentTargetDescription)}
* correctly handles responses containing a "not permitted" operation result.
*/
@Test
public void testNotPermittedOperationConversion() {
BaseAttachmentTargetResponseEntityReader entityReader =
new BaseAttachmentTargetResponseEntityReader();
OperationResultEntity operationResultEntity =
new OperationResultEntity(ResultStatus.NOTPERMITTED, "Some error occured");
FileDescriptionEntity[] fileDescriptionEntities =
new FileDescriptionEntity[2];
fileDescriptionEntities[0] =
new FileDescriptionEntity("/subdir/", "file1.txt");
fileDescriptionEntities[1] =
new FileDescriptionEntity("/subdir/", "file2.txt");
for (TargetType targetType : TargetType.values()) {
// build input parameters
AttachmentTargetEntity attachmentTargetEntityWithFiles =
new AttachmentTargetEntity(targetType, new FileDescriptionEntity[0]);
AttachmentTargetResponseEntity jsonEntityWithFiles =
new AttachmentTargetResponseEntity(attachmentTargetEntityWithFiles,
operationResultEntity);
AttachmentTargetEntity attachmentTargetEntityWithoutFiles =
new AttachmentTargetEntity(targetType, new FileDescriptionEntity[0]);
AttachmentTargetResponseEntity jsonEntityWithoutFiles =
new AttachmentTargetResponseEntity(
attachmentTargetEntityWithoutFiles, operationResultEntity);
AttachmentTargetDescription attachmentTargetDescription =
new PatchTargetDescription(new PatchSetTargetDescription(
new ChangeTargetDescription("I0000000000000000"), 0),
"/project/README");
// begin testing
// without files
AttachmentTarget attachmentTarget =
entityReader.toObject(jsonEntityWithoutFiles,
attachmentTargetDescription);
Assert.assertThat("Unexpected result for failed operation with entity: "
+ jsonEntityWithoutFiles.toString(), attachmentTarget,
CoreMatchers.is(CoreMatchers.nullValue()));
// with files
attachmentTarget =
entityReader.toObject(jsonEntityWithFiles,
attachmentTargetDescription);
Assert.assertThat("Unexpected result for failed operation with entity: "
+ jsonEntityWithFiles.toString(), attachmentTarget,
CoreMatchers.is(CoreMatchers.nullValue()));
}
}
}
| theArchonius/gerrit-attachments | src/test/java/com/eclipsesource/gerrit/plugins/fileattachment/api/test/converter/BaseAttachmentTargetResponseEntityReaderTest.java | Java | epl-1.0 | 12,234 |
/*
* $Id$
*
* Copyright (c) 2004-2005 by the TeXlapse Team.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package net.sourceforge.texlipse.properties;
import net.sourceforge.texlipse.TexlipsePlugin;
import net.sourceforge.texlipse.bibeditor.BibColorProvider;
import org.eclipse.jface.preference.ColorFieldEditor;
import org.eclipse.jface.preference.FieldEditorPreferencePage;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
/**
* The page to set syntax highlighting colors.
*
* @author kimmo
*/
public class BibColoringPreferencePage
extends FieldEditorPreferencePage
implements IWorkbenchPreferencePage {
/**
* Creates an instance of the "syntax highlighting colors" -preference page.
*/
public BibColoringPreferencePage() {
super(GRID);
setPreferenceStore(TexlipsePlugin.getDefault().getPreferenceStore());
setDescription(TexlipsePlugin.getResourceString("preferenceBibColorPageDescription"));
}
/**
* Creates the property editing UI components of this page.
*/
protected void createFieldEditors() {
addField(new ColorFieldEditor(BibColorProvider.DEFAULT, TexlipsePlugin.getResourceString("preferenceBibColorTextLabel"), getFieldEditorParent()));
addField(new ColorFieldEditor(BibColorProvider.TYPE, TexlipsePlugin.getResourceString("preferenceBibColorTypeLabel"), getFieldEditorParent()));
addField(new ColorFieldEditor(BibColorProvider.KEYWORD, TexlipsePlugin.getResourceString("preferenceBibColorKeywordLabel"), getFieldEditorParent()));
addField(new ColorFieldEditor(BibColorProvider.STRING, TexlipsePlugin.getResourceString("preferenceBibColorStringLabel"), getFieldEditorParent()));
// addField(new ColorFieldEditor(BibColorProvider.MULTI_LINE_COMMENT, TexlipsePlugin.getResourceString("preferenceBibColorMLCommentLabel"), getFieldEditorParent()));
addField(new ColorFieldEditor(BibColorProvider.SINGLE_LINE_COMMENT, TexlipsePlugin.getResourceString("preferenceBibColorCommentLabel"), getFieldEditorParent()));
}
/**
* Nothing to do.
*/
public void init(IWorkbench workbench) {
}
}
| rondiplomatico/texlipse | source/net/sourceforge/texlipse/properties/BibColoringPreferencePage.java | Java | epl-1.0 | 2,392 |
/*******************************************************************************
* Copyright (c) 1998, 2013 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
* dminsky - added countOccurrencesOf(Object, List) API
* 08/23/2010-2.2 Michael O'Brien
* - 323043: application.xml module ordering may cause weaving not to occur causing an NPE.
* warn if expected "_persistence_*_vh" method not found
* instead of throwing NPE during deploy validation.
******************************************************************************/
package org.eclipse.persistence.internal.helper;
import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.Vector;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.eclipse.persistence.config.SystemProperties;
import org.eclipse.persistence.exceptions.ConversionException;
import org.eclipse.persistence.exceptions.EclipseLinkException;
import org.eclipse.persistence.exceptions.ValidationException;
import org.eclipse.persistence.internal.core.helper.CoreHelper;
import org.eclipse.persistence.internal.security.PrivilegedAccessHelper;
import org.eclipse.persistence.internal.security.PrivilegedClassForName;
import org.eclipse.persistence.internal.security.PrivilegedGetField;
import org.eclipse.persistence.internal.security.PrivilegedGetMethod;
import org.eclipse.persistence.internal.security.PrivilegedNewInstanceFromClass;
import org.eclipse.persistence.logging.AbstractSessionLog;
import org.eclipse.persistence.logging.SessionLog;
/**
* INTERNAL:
* <p>
* <b>Purpose</b>: Define any useful methods that are missing from the base Java.
*/
public class Helper extends CoreHelper implements Serializable {
/** Used to configure JDBC level date optimization. */
public static boolean shouldOptimizeDates = false;
/** Used to store null values in hashtables, is helper because need to be serializable. */
public static final Object NULL_VALUE = new Helper();
/** PERF: Used to cache a set of calendars for conversion/printing purposes. */
protected static Queue<Calendar> calendarCache = initCalendarCache();
/** PERF: Cache default timezone for calendar conversion. */
protected static TimeZone defaultTimeZone = TimeZone.getDefault();
// Changed static initialization to lazy initialization for bug 2756643
/** Store CR string, for some reason \n is not platform independent. */
protected static String CR = null;
/** formatting strings for indenting */
public static String SPACE = " ";
public static String INDENT = " ";
/** Store newline string */
public static String NL = "\n";
/** Prime the platform-dependent path separator */
protected static String PATH_SEPARATOR = null;
/** Prime the platform-dependent file separator */
protected static String FILE_SEPARATOR = null;
/** Prime the platform-dependent current working directory */
protected static String CURRENT_WORKING_DIRECTORY = null;
/** Prime the platform-dependent temporary directory */
protected static String TEMP_DIRECTORY = null;
/** Backdoor to allow 0 to be used in primary keys.
* @deprecated
* Instead of setting the flag to true use:
* session.getProject().setDefaultIdValidation(IdValidation.NULL)
**/
public static boolean isZeroValidPrimaryKey = false;
// settings to allow ascertaining attribute names from method names
public static final String IS_PROPERTY_METHOD_PREFIX = "is";
public static final String GET_PROPERTY_METHOD_PREFIX = "get";
public static final String SET_PROPERTY_METHOD_PREFIX = "set";
public static final String SET_IS_PROPERTY_METHOD_PREFIX = "setIs";
public static final int POSITION_AFTER_IS_PREFIX = IS_PROPERTY_METHOD_PREFIX.length();
public static final int POSITION_AFTER_GET_PREFIX = GET_PROPERTY_METHOD_PREFIX.length();
public static final String DEFAULT_DATABASE_DELIMITER = "\"";
public static final String PERSISTENCE_SET = "_persistence_set_";
public static final String PERSISTENCE_GET = "_persistence_get_";
// 323403: These constants are used to search for missing weaved functions - this is a copy is of the jpa project under ClassWeaver
public static final String PERSISTENCE_FIELDNAME_PREFIX = "_persistence_";
public static final String PERSISTENCE_FIELDNAME_POSTFIX = "_vh";
private static String defaultStartDatabaseDelimiter = null;
private static String defaultEndDatabaseDelimiter = null;
/**
* Return if JDBC date access should be optimized.
*/
public static boolean shouldOptimizeDates() {
return shouldOptimizeDates;
}
/**
* Return if JDBC date access should be optimized.
*/
public static void setShouldOptimizeDates(boolean value) {
shouldOptimizeDates = value;
}
/**
* PERF:
* Return the calendar cache use to avoid calendar creation for processing java.sql/util.Date/Time/Timestamp objects.
*/
public static Queue<Calendar> getCalendarCache() {
return calendarCache;
}
/**
* PERF:
* Init the calendar cache use to avoid calendar creation for processing java.sql/util.Date/Time/Timestamp objects.
*/
public static Queue initCalendarCache() {
Queue calendarCache = new ConcurrentLinkedQueue();
for (int index = 0; index < 10; index++) {
calendarCache.add(Calendar.getInstance());
}
return calendarCache;
}
/**
* PERF: This is used to optimize Calendar conversion/printing.
* This should only be used when a calendar is temporarily required,
* when finished it must be released back.
*/
public static Calendar allocateCalendar() {
Calendar calendar = getCalendarCache().poll();
if (calendar == null) {
calendar = Calendar.getInstance();
}
return calendar;
}
/**
* PERF: Return the cached default platform.
* Used for ensuring Calendar are in the local timezone.
* The JDK method clones the timezone, so cache it locally.
*/
public static TimeZone getDefaultTimeZone() {
return defaultTimeZone;
}
/**
* PERF: This is used to optimize Calendar conversion/printing.
* This should only be used when a calendar is temporarily required,
* when finished it must be released back.
*/
public static void releaseCalendar(Calendar calendar) {
getCalendarCache().offer(calendar);
}
public static void addAllToVector(Vector theVector, Vector elementsToAdd) {
for (Enumeration stream = elementsToAdd.elements(); stream.hasMoreElements();) {
theVector.addElement(stream.nextElement());
}
}
public static Vector addAllUniqueToVector(Vector objects, List objectsToAdd) {
if (objectsToAdd == null) {
return objects;
}
int size = objectsToAdd.size();
for (int index = 0; index < size; index++) {
Object element = objectsToAdd.get(index);
if (!objects.contains(element)) {
objects.add(element);
}
}
return objects;
}
public static List addAllUniqueToList(List objects, List objectsToAdd) {
if (objectsToAdd == null) {
return objects;
}
int size = objectsToAdd.size();
for (int index = 0; index < size; index++) {
Object element = objectsToAdd.get(index);
if (!objects.contains(element)) {
objects.add(element);
}
}
return objects;
}
/**
* Convert the specified vector into an array.
*/
public static Object[] arrayFromVector(Vector vector) {
Object[] result = new Object[vector.size()];
for (int i = 0; i < vector.size(); i++) {
result[i] = vector.elementAt(i);
}
return result;
}
/**
* Convert the HEX string to a byte array.
* HEX allows for binary data to be printed.
*/
public static byte[] buildBytesFromHexString(String hex) {
String tmpString = hex;
if ((tmpString.length() % 2) != 0) {
throw ConversionException.couldNotConvertToByteArray(hex);
}
byte[] bytes = new byte[tmpString.length() / 2];
int byteIndex;
int strIndex;
byte digit1;
byte digit2;
for (byteIndex = bytes.length - 1, strIndex = tmpString.length() - 2; byteIndex >= 0;
byteIndex--, strIndex -= 2) {
digit1 = (byte)Character.digit(tmpString.charAt(strIndex), 16);
digit2 = (byte)Character.digit(tmpString.charAt(strIndex + 1), 16);
if ((digit1 == -1) || (digit2 == -1)) {
throw ConversionException.couldNotBeConverted(hex, ClassConstants.APBYTE);
}
bytes[byteIndex] = (byte)((digit1 * 16) + digit2);
}
return bytes;
}
/**
* Convert the byte array to a HEX string.
* HEX allows for binary data to be printed.
*/
public static String buildHexStringFromBytes(byte[] bytes) {
char[] hexArray = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
StringBuffer stringBuffer = new StringBuffer();
int tempByte;
for (int byteIndex = 0; byteIndex < (bytes).length; byteIndex++) {
tempByte = (bytes)[byteIndex];
if (tempByte < 0) {
tempByte = tempByte + 256;//compensate for the fact that byte is signed in Java
}
tempByte = (byte)(tempByte / 16);//get the first digit
if (tempByte > 16) {
throw ConversionException.couldNotBeConverted(bytes, ClassConstants.STRING);
}
stringBuffer.append(hexArray[tempByte]);
tempByte = (bytes)[byteIndex];
if (tempByte < 0) {
tempByte = tempByte + 256;
}
tempByte = (byte)(tempByte % 16);//get the second digit
if (tempByte > 16) {
throw ConversionException.couldNotBeConverted(bytes, ClassConstants.STRING);
}
stringBuffer.append(hexArray[tempByte]);
}
return stringBuffer.toString();
}
/**
* Create a new Vector containing all of the map elements.
*/
public static Vector buildVectorFromMapElements(Map map) {
Vector vector = new Vector(map.size());
Iterator iterator = map.values().iterator();
while (iterator.hasNext()) {
vector.addElement(iterator.next());
}
return vector;
}
/**
* Answer a Calendar from a date.
*/
public static Calendar calendarFromUtilDate(java.util.Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
//In jdk1.3, millisecond is missing
if (date instanceof Timestamp) {
calendar.set(Calendar.MILLISECOND, ((Timestamp)date).getNanos() / 1000000);
}
return calendar;
}
/**
* INTERNAL:
* Return whether a Class implements a specific interface, either directly or indirectly
* (through interface or implementation inheritance).
* @return boolean
*/
public static boolean classImplementsInterface(Class aClass, Class anInterface) {
// quick check
if (aClass == anInterface) {
return true;
}
Class[] interfaces = aClass.getInterfaces();
// loop through the "directly declared" interfaces
for (int i = 0; i < interfaces.length; i++) {
if (interfaces[i] == anInterface) {
return true;
}
}
// recurse through the interfaces
for (int i = 0; i < interfaces.length; i++) {
if (classImplementsInterface(interfaces[i], anInterface)) {
return true;
}
}
// finally, recurse up through the superclasses to Object
Class superClass = aClass.getSuperclass();
if (superClass == null) {
return false;
}
return classImplementsInterface(superClass, anInterface);
}
/**
* INTERNAL:
* Return whether a Class is a subclass of, or the same as, another Class.
* @return boolean
*/
public static boolean classIsSubclass(Class subClass, Class superClass) {
Class temp = subClass;
if (superClass == null) {
return false;
}
while (temp != null) {
if (temp == superClass) {
return true;
}
temp = temp.getSuperclass();
}
return false;
}
/**
* INTERNAL:
* Compares two version in num.num.num.num.num*** format.
* -1, 0, 1 means the version1 is less than, equal, greater than version2.
* Example: compareVersions("11.1.0.6.0-Production", "11.1.0.7") == -1
* Example: compareVersions("WebLogic Server 10.3.4", "10.3.3.0") == 1
*/
public static int compareVersions(String version1, String version2) {
return compareVersions(version(version1), version(version2));
}
/**
* INTERNAL:
* Expects version in ***num.num.num.num.num*** format, converts it to a List of Integers.
* Example: "11.1.0.6.0_Production" -> {11, 1, 0, 6, 0}
* Example: "WebLogic Server 10.3.3.0" -> {10, 3, 3, 0}
*/
static protected List<Integer> version(String version) {
ArrayList<Integer> list = new ArrayList<Integer>(5);
// first char - a digit - in the string corresponding to the current list index
int iBegin = -1;
// used to remove a non-digital prefix
boolean isPrefix = true;
for(int i=0; i<version.length(); i++) {
char ch = version.charAt(i);
if('0' <= ch && ch <= '9') {
isPrefix = false;
// it's a digit
if(iBegin == -1) {
iBegin = i;
}
} else {
// it's not a digit - try to create a number ending on the previous char - unless it's still part of the non-digital prefix.
if(iBegin == -1) {
if(!isPrefix) {
break;
}
} else {
isPrefix = false;
String strNum = version.substring(iBegin, i);
int num = Integer.parseInt(strNum, 10);
list.add(num);
iBegin = -1;
if(ch != '.') {
break;
}
}
}
}
if(iBegin >= 0) {
String strNum = version.substring(iBegin, version.length());
int num = Integer.parseInt(strNum, 10);
list.add(num);
}
return list;
}
/**
* INTERNAL:
* Compares two lists of Integers
* -1, 0, 1 means the first list is less than, equal, greater than the second list.
* Example: {11, 1, 0, 6, 0} < {11, 1, 0, 7}
*/
static protected int compareVersions(List<Integer> list1, List<Integer>list2) {
int n = Math.max(list1.size(), list2.size());
int res = 0;
for(int i=0; i<n; i++) {
int l1 = 0;
if(i < list1.size()) {
l1 = list1.get(i);
}
int l2 = 0;
if(i < list2.size()) {
l2 = list2.get(i);
}
if(l1 < l2) {
res =-1;
break;
} else if(l1 > l2) {
res = 1;
break;
}
}
return res;
}
public static Class getClassFromClasseName(String className, ClassLoader classLoader){
Class convertedClass = null;
if(className==null){
return null;
}
try{
if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()){
try {
convertedClass = (Class)AccessController.doPrivileged(new PrivilegedClassForName(className, true, classLoader));
} catch (PrivilegedActionException exception) {
throw ValidationException.classNotFoundWhileConvertingClassNames(className, exception.getException());
}
} else {
convertedClass = org.eclipse.persistence.internal.security.PrivilegedAccessHelper.getClassForName(className, true, classLoader);
}
return convertedClass;
} catch (ClassNotFoundException exc){
throw ValidationException.classNotFoundWhileConvertingClassNames(className, exc);
}
}
public static String getComponentTypeNameFromArrayString(String aString) {
if (aString == null || aString.length() == 0) {
return null;
}
// complex array component type case
if (aString.length() > 3 && (aString.startsWith("[L") & aString.endsWith(";"))) {
return aString.substring(2, aString.length() - 1);
} else if (aString.startsWith("[")){
Class primitiveClass = null;
try {
primitiveClass = Class.forName(aString);
} catch (ClassNotFoundException cnf) {
// invalid name specified - do not rethrow exception
primitiveClass = null;
}
if (primitiveClass != null) {
return primitiveClass.getComponentType().getName();
}
}
return null;
}
public static boolean compareArrays(Object[] array1, Object[] array2) {
if (array1.length != array2.length) {
return false;
}
for (int index = 0; index < array1.length; index++) {
//Related to Bug#3128838 fix. ! is added to correct the logic.
if(array1[index] != null) {
if (!array1[index].equals(array2[index])) {
return false;
}
} else {
if(array2[index] != null) {
return false;
}
}
}
return true;
}
/**
* Compare two BigDecimals.
* This is required because the .equals method of java.math.BigDecimal ensures that
* the scale of the two numbers are equal. Therefore 0.0 != 0.00.
* @see java.math.BigDecimal#equals(Object)
*/
public static boolean compareBigDecimals(java.math.BigDecimal one, java.math.BigDecimal two) {
if (one.scale() != two.scale()) {
double doubleOne = (one).doubleValue();
double doubleTwo = (two).doubleValue();
if ((doubleOne != Double.POSITIVE_INFINITY) && (doubleOne != Double.NEGATIVE_INFINITY) && (doubleTwo != Double.POSITIVE_INFINITY) && (doubleTwo != Double.NEGATIVE_INFINITY)) {
return doubleOne == doubleTwo;
}
}
return one.equals(two);
}
public static boolean compareByteArrays(byte[] array1, byte[] array2) {
if (array1.length != array2.length) {
return false;
}
for (int index = 0; index < array1.length; index++) {
if (array1[index] != array2[index]) {
return false;
}
}
return true;
}
public static boolean compareCharArrays(char[] array1, char[] array2) {
if (array1.length != array2.length) {
return false;
}
for (int index = 0; index < array1.length; index++) {
if (array1[index] != array2[index]) {
return false;
}
}
return true;
}
/**
* PUBLIC:
*
* Compare two vectors of types. Return true if the size of the vectors is the
* same and each of the types in the first Vector are assignable from the types
* in the corresponding objects in the second Vector.
*/
public static boolean areTypesAssignable(List types1, List types2) {
if ((types1 == null) || (types2 == null)) {
return false;
}
if (types1.size() == types2.size()) {
for (int i = 0; i < types1.size(); i++) {
Class type1 = (Class)types1.get(i);
Class type2 = (Class)types2.get(i);
// if either are null then we assume assignability.
if ((type1 != null) && (type2 != null)) {
if (!type1.isAssignableFrom(type2)) {
return false;
}
}
}
return true;
}
return false;
}
/**
* PUBLIC:
* Compare the elements in 2 hashtables to see if they are equal
*
* Added Nov 9, 2000 JED Patch 2.5.1.8
*/
public static boolean compareHashtables(Hashtable hashtable1, Hashtable hashtable2) {
Enumeration enumtr;
Object element;
Hashtable clonedHashtable;
if (hashtable1.size() != hashtable2.size()) {
return false;
}
clonedHashtable = (Hashtable)hashtable2.clone();
enumtr = hashtable1.elements();
while (enumtr.hasMoreElements()) {
element = enumtr.nextElement();
if (clonedHashtable.remove(element) == null) {
return false;
}
}
return clonedHashtable.isEmpty();
}
/**
* Compare two potential arrays and return true if they are the same. Will
* check for BigDecimals as well.
*/
public static boolean comparePotentialArrays(Object firstValue, Object secondValue) {
Class firstClass = firstValue.getClass();
Class secondClass = secondValue.getClass();
// Arrays must be checked for equality because default does identity
if ((firstClass == ClassConstants.APBYTE) && (secondClass == ClassConstants.APBYTE)) {
return compareByteArrays((byte[])firstValue, (byte[])secondValue);
} else if ((firstClass == ClassConstants.APCHAR) && (secondClass == ClassConstants.APCHAR)) {
return compareCharArrays((char[])firstValue, (char[])secondValue);
} else if ((firstClass.isArray()) && (secondClass.isArray())) {
return compareArrays((Object[])firstValue, (Object[])secondValue);
} else if (firstValue instanceof java.math.BigDecimal && secondValue instanceof java.math.BigDecimal) {
// BigDecimals equals does not consider the precision correctly
return compareBigDecimals((java.math.BigDecimal)firstValue, (java.math.BigDecimal)secondValue);
}
return false;
}
/**
* Merge the two Maps into a new HashMap.
*/
public static Map concatenateMaps(Map first, Map second) {
Map concatenation = new HashMap(first.size() + second.size() + 4);
for (Iterator keys = first.keySet().iterator(); keys.hasNext();) {
Object key = keys.next();
Object value = first.get(key);
concatenation.put(key, value);
}
for (Iterator keys = second.keySet().iterator(); keys.hasNext();) {
Object key = keys.next();
Object value = second.get(key);
concatenation.put(key, value);
}
return concatenation;
}
/**
* Return a new vector with no duplicated values.
*/
public static Vector concatenateUniqueVectors(Vector first, Vector second) {
Vector concatenation;
Object element;
concatenation = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance();
for (Enumeration stream = first.elements(); stream.hasMoreElements();) {
concatenation.addElement(stream.nextElement());
}
for (Enumeration stream = second.elements(); stream.hasMoreElements();) {
element = stream.nextElement();
if (!concatenation.contains(element)) {
concatenation.addElement(element);
}
}
return concatenation;
}
/**
* Return a new List with no duplicated values.
*/
public static List concatenateUniqueLists(List first, List second) {
List concatenation = new ArrayList(first.size() + second.size());
concatenation.addAll(first);
for (Object element : second) {
if (!concatenation.contains(element)) {
concatenation.add(element);
}
}
return concatenation;
}
public static Vector concatenateVectors(Vector first, Vector second) {
Vector concatenation;
concatenation = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance();
for (Enumeration stream = first.elements(); stream.hasMoreElements();) {
concatenation.addElement(stream.nextElement());
}
for (Enumeration stream = second.elements(); stream.hasMoreElements();) {
concatenation.addElement(stream.nextElement());
}
return concatenation;
}
/** Return a copy of the vector containing a subset starting at startIndex
* and ending at stopIndex.
* @param vector - original vector
* @param startIndex - starting position in vector
* @param stopIndex - ending position in vector
* @exception EclipseLinkException
*/
public static Vector copyVector(List originalVector, int startIndex, int stopIndex) throws ValidationException {
Vector newVector;
if (stopIndex < startIndex) {
return NonSynchronizedVector.newInstance();
}
newVector = NonSynchronizedVector.newInstance(stopIndex - startIndex);
for (int index = startIndex; index < stopIndex; index++) {
newVector.add(originalVector.get(index));
}
return newVector;
}
/**
* Copy an array of strings to a new array
* avoids the use of Arrays.copy() because it is not supported in JDK 1.5
* @param original
* @return
*/
public static String[] copyStringArray(String[] original){
if (original == null){
return null;
}
String[] copy = new String[original.length];
for (int i=0;i<original.length;i++){
copy[i] = original[i];
}
return copy;
}
/**
* Copy an array of int to a new array
* avoids the use of Arrays.copy() because it is not supported in JDK 1.5
* @param original
* @return
*/
public static int[] copyIntArray(int[] original){
if (original == null){
return null;
}
int[] copy = new int[original.length];
for (int i=0;i<original.length;i++){
copy[i] = original[i];
}
return copy;
}
/**
* Return a string containing the platform-appropriate
* characters for carriage return.
*/
public static String cr() {
// bug 2756643
if (CR == null) {
CR = System.getProperty("line.separator");
}
return CR;
}
/**
* Return the name of the "current working directory".
*/
public static String currentWorkingDirectory() {
// bug 2756643
if (CURRENT_WORKING_DIRECTORY == null) {
CURRENT_WORKING_DIRECTORY = System.getProperty("user.dir");
}
return CURRENT_WORKING_DIRECTORY;
}
/**
* Return the name of the "temporary directory".
*/
public static String tempDirectory() {
// Bug 2756643
if (TEMP_DIRECTORY == null) {
TEMP_DIRECTORY = System.getProperty("java.io.tmpdir");
}
return TEMP_DIRECTORY;
}
/**
* Answer a Date from a long
*
* This implementation is based on the java.sql.Date class, not java.util.Date.
* @param longObject - milliseconds from the epoch (00:00:00 GMT
* Jan 1, 1970). Negative values represent dates prior to the epoch.
*/
public static java.sql.Date dateFromLong(Long longObject) {
return new java.sql.Date(longObject.longValue());
}
/**
* Answer a Date with the year, month, date.
* This builds a date avoiding the deprecated, inefficient and concurrency bottleneck date constructors.
* This implementation is based on the java.sql.Date class, not java.util.Date.
* The year, month, day are the values calendar uses,
* i.e. year is from 0, month is 0-11, date is 1-31.
*/
public static java.sql.Date dateFromYearMonthDate(int year, int month, int day) {
// Use a calendar to compute the correct millis for the date.
Calendar localCalendar = allocateCalendar();
localCalendar.clear();
localCalendar.set(year, month, day, 0, 0, 0);
long millis = localCalendar.getTimeInMillis();
java.sql.Date date = new java.sql.Date(millis);
releaseCalendar(localCalendar);
return date;
}
/**
* Answer a Date from a string representation.
* The string MUST be a valid date and in one of the following
* formats: YYYY/MM/DD, YYYY-MM-DD, YY/MM/DD, YY-MM-DD.
*
* This implementation is based on the java.sql.Date class, not java.util.Date.
*
* The Date class contains some minor gotchas that you have to watch out for.
* @param dateString - string representation of date
* @return - date representation of string
*/
public static java.sql.Date dateFromString(String dateString) throws ConversionException {
int year;
int month;
int day;
StringTokenizer dateStringTokenizer;
if (dateString.indexOf('/') != -1) {
dateStringTokenizer = new StringTokenizer(dateString, "/");
} else if (dateString.indexOf('-') != -1) {
dateStringTokenizer = new StringTokenizer(dateString, "- ");
} else {
throw ConversionException.incorrectDateFormat(dateString);
}
try {
year = Integer.parseInt(dateStringTokenizer.nextToken());
month = Integer.parseInt(dateStringTokenizer.nextToken());
day = Integer.parseInt(dateStringTokenizer.nextToken());
} catch (NumberFormatException exception) {
throw ConversionException.incorrectDateFormat(dateString);
}
// Java returns the month in terms of 0 - 11 instead of 1 - 12.
month = month - 1;
return dateFromYearMonthDate(year, month, day);
}
/**
* Answer a Date from a timestamp
*
* This implementation is based on the java.sql.Date class, not java.util.Date.
* @param timestampObject - timestamp representation of date
* @return - date representation of timestampObject
*/
public static java.sql.Date dateFromTimestamp(java.sql.Timestamp timestamp) {
return sqlDateFromUtilDate(timestamp);
}
/**
* Returns true if the file of this name does indeed exist
*/
public static boolean doesFileExist(String fileName) {
FileReader reader = null;
try {
reader = new FileReader(fileName);
} catch (FileNotFoundException fnfException) {
return false;
} finally {
Helper.close(reader);
}
return true;
}
/**
* Double up \ to allow printing of directories for source code generation.
*/
public static String doubleSlashes(String path) {
StringBuffer buffer = new StringBuffer(path.length() + 5);
for (int index = 0; index < path.length(); index++) {
char charater = path.charAt(index);
buffer.append(charater);
if (charater == '\\') {
buffer.append('\\');
}
}
return buffer.toString();
}
/**
* Extracts the actual path to the jar file.
*/
public static String extractJarNameFromURL(java.net.URL url) {
String tempName = url.getFile();
int start = tempName.indexOf("file:") + 5;
int end = tempName.indexOf("!/");
return tempName.substring(start, end);
}
/**
* Return a string containing the platform-appropriate
* characters for separating directory and file names.
*/
public static String fileSeparator() {
//Bug 2756643
if (FILE_SEPARATOR == null) {
FILE_SEPARATOR = System.getProperty("file.separator");
}
return FILE_SEPARATOR;
}
/**
* INTERNAL:
* Returns a Field for the specified Class and field name.
* Uses Class.getDeclaredField(String) to find the field.
* If the field is not found on the specified class
* the superclass is checked, and so on, recursively.
* Set accessible to true, so we can access private/package/protected fields.
*/
public static Field getField(Class javaClass, String fieldName) throws NoSuchFieldException {
if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()){
try {
return (Field)AccessController.doPrivileged(new PrivilegedGetField(javaClass, fieldName, true));
} catch (PrivilegedActionException exception) {
throw (NoSuchFieldException)exception.getException();
}
} else {
return PrivilegedAccessHelper.getField(javaClass, fieldName, true);
}
}
/**
* INTERNAL:
* Returns a Method for the specified Class, method name, and that has no
* parameters. Uses Class.getDeclaredMethod(String Class[]) to find the
* method. If the method is not found on the specified class the superclass
* is checked, and so on, recursively. Set accessible to true, so we can
* access private/package/protected methods.
*/
public static Method getDeclaredMethod(Class javaClass, String methodName) throws NoSuchMethodException {
return getDeclaredMethod(javaClass, methodName, (Class[]) null);
}
/**
* INTERNAL:
* Returns a Method for the specified Class, method name, and formal
* parameter types. Uses Class.getDeclaredMethod(String Class[]) to find
* the method. If the method is not found on the specified class the
* superclass is checked, and so on, recursively. Set accessible to true,
* so we can access private/package/protected methods.
*/
public static Method getDeclaredMethod(Class javaClass, String methodName, Class[] methodParameterTypes) throws NoSuchMethodException {
if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()){
try {
return AccessController.doPrivileged(
new PrivilegedGetMethod(javaClass, methodName, methodParameterTypes, true));
}
catch (PrivilegedActionException pae){
if (pae.getCause() instanceof NoSuchMethodException){
throw (NoSuchMethodException)pae.getCause();
}
else {
// really shouldn't happen
throw (RuntimeException)pae.getCause();
}
}
} else {
return PrivilegedAccessHelper.getMethod(javaClass, methodName, methodParameterTypes, true);
}
}
/**
* Return the class instance from the class
*/
public static Object getInstanceFromClass(Class classFullName) {
if (classFullName == null) {
return null;
}
try {
if (PrivilegedAccessHelper.shouldUsePrivilegedAccess()){
try {
return AccessController.doPrivileged(new PrivilegedNewInstanceFromClass(classFullName));
} catch (PrivilegedActionException exception) {
Exception throwableException = exception.getException();
if (throwableException instanceof InstantiationException) {
ValidationException exc = new ValidationException();
exc.setInternalException(throwableException);
throw exc;
} else {
ValidationException exc = new ValidationException();
exc.setInternalException(throwableException);
throw exc;
}
}
} else {
return PrivilegedAccessHelper.newInstanceFromClass(classFullName);
}
} catch (InstantiationException notInstantiatedException) {
ValidationException exception = new ValidationException();
exception.setInternalException(notInstantiatedException);
throw exception;
} catch (IllegalAccessException notAccessedException) {
ValidationException exception = new ValidationException();
exception.setInternalException(notAccessedException);
throw exception;
}
}
/**
* Returns the object class. If a class is primitive return its non primitive class
*/
public static Class getObjectClass(Class javaClass) {
return ConversionManager.getObjectClass(javaClass);
}
/**
* Answers the unqualified class name for the provided class.
*/
public static String getShortClassName(Class javaClass) {
return getShortClassName(javaClass.getName());
}
/**
* Answers the unqualified class name from the specified String.
*/
public static String getShortClassName(String javaClassName) {
return javaClassName.substring(javaClassName.lastIndexOf('.') + 1);
}
/**
* Answers the unqualified class name for the specified object.
*/
public static String getShortClassName(Object object) {
return getShortClassName(object.getClass());
}
/**
* return a package name for the specified class.
*/
public static String getPackageName(Class javaClass) {
String className = Helper.getShortClassName(javaClass);
return javaClass.getName().substring(0, (javaClass.getName().length() - (className.length() + 1)));
}
/**
* Return a string containing the specified number of tabs.
*/
public static String getTabs(int noOfTabs) {
StringWriter writer = new StringWriter();
for (int index = 0; index < noOfTabs; index++) {
writer.write("\t");
}
return writer.toString();
}
/**
* Returns the index of the the first <code>null</code> element found in the specified
* <code>Vector</code> starting the search at the starting index specified.
* Return an int >= 0 and less than size if a <code>null</code> element was found.
* Return -1 if a <code>null</code> element was not found.
* This is needed in jdk1.1, where <code>Vector.contains(Object)</code>
* for a <code>null</code> element will result in a <code>NullPointerException</code>....
*/
public static int indexOfNullElement(Vector v, int index) {
int size = v.size();
for (int i = index; i < size; i++) {
if (v.elementAt(i) == null) {
return i;
}
}
return -1;
}
/**
* ADVANCED
* returns true if the class in question is a primitive wrapper
*/
public static boolean isPrimitiveWrapper(Class classInQuestion) {
return classInQuestion.equals(Character.class) || classInQuestion.equals(Boolean.class) || classInQuestion.equals(Byte.class) || classInQuestion.equals(Short.class) || classInQuestion.equals(Integer.class) || classInQuestion.equals(Long.class) || classInQuestion.equals(Float.class) || classInQuestion.equals(Double.class);
}
/**
* Returns true if the string given is an all upper case string
*/
public static boolean isUpperCaseString(String s) {
char[] c = s.toCharArray();
for (int i = 0; i < s.length(); i++) {
if (Character.isLowerCase(c[i])) {
return false;
}
}
return true;
}
/**
* Returns true if the character given is a vowel. I.e. one of a,e,i,o,u,A,E,I,O,U.
*/
public static boolean isVowel(char c) {
return (c == 'A') || (c == 'a') || (c == 'e') || (c == 'E') || (c == 'i') || (c == 'I') || (c == 'o') || (c == 'O') || (c == 'u') || (c == 'U');
}
/**
* Return an array of the files in the specified directory.
* This allows us to simplify jdk1.1 code a bit.
*/
public static File[] listFilesIn(File directory) {
if (directory.isDirectory()) {
return directory.listFiles();
} else {
return new File[0];
}
}
/**
* Make a Vector from the passed object.
* If it's a Collection, iterate over the collection and add each item to the Vector.
* If it's not a collection create a Vector and add the object to it.
*/
public static Vector makeVectorFromObject(Object theObject) {
if (theObject instanceof Vector) {
return ((Vector)theObject);
}
if (theObject instanceof Collection) {
Vector returnVector = new Vector(((Collection)theObject).size());
Iterator iterator = ((Collection)theObject).iterator();
while (iterator.hasNext()) {
returnVector.add(iterator.next());
}
return returnVector;
}
Vector returnVector = new Vector();
returnVector.addElement(theObject);
return returnVector;
}
/**
* Used by our byte code weaving to enable users who are debugging to output
* the generated class to a file
*
* @param className
* @param classBytes
* @param outputPath
*/
public static void outputClassFile(String className, byte[] classBytes,
String outputPath) {
StringBuffer directoryName = new StringBuffer();
StringTokenizer tokenizer = new StringTokenizer(className, "\n\\/");
String token = null;
while (tokenizer.hasMoreTokens()) {
token = tokenizer.nextToken();
if (tokenizer.hasMoreTokens()) {
directoryName.append(token + File.separator);
}
}
FileOutputStream fos = null;
try {
String usedOutputPath = outputPath;
if (!outputPath.endsWith(File.separator)) {
usedOutputPath = outputPath + File.separator;
}
File file = new File(usedOutputPath + directoryName);
file.mkdirs();
file = new File(file, token + ".class");
if (!file.exists()) {
file.createNewFile();
} else {
if (!System.getProperty(
SystemProperties.WEAVING_SHOULD_OVERWRITE, "false")
.equalsIgnoreCase("true")) {
AbstractSessionLog.getLog().log(SessionLog.WARNING,
SessionLog.WEAVER, "weaver_not_overwriting",
className);
return;
}
}
fos = new FileOutputStream(file);
fos.write(classBytes);
} catch (Exception e) {
AbstractSessionLog.getLog().log(SessionLog.WARNING,
SessionLog.WEAVER, "weaver_could_not_write", className, e);
AbstractSessionLog.getLog().logThrowable(SessionLog.FINEST,
SessionLog.WEAVER, e);
} finally {
Helper.close(fos);
}
}
/**
* Return a string containing the platform-appropriate
* characters for separating entries in a path (e.g. the classpath)
*/
public static String pathSeparator() {
// Bug 2756643
if (PATH_SEPARATOR == null) {
PATH_SEPARATOR = System.getProperty("path.separator");
}
return PATH_SEPARATOR;
}
/**
* Return a String containing the printed stacktrace of an exception.
*/
public static String printStackTraceToString(Throwable aThrowable) {
StringWriter swriter = new StringWriter();
PrintWriter writer = new PrintWriter(swriter, true);
aThrowable.printStackTrace(writer);
writer.close();
return swriter.toString();
}
/* Return a string representation of a number of milliseconds in terms of seconds, minutes, or
* milliseconds, whichever is most appropriate.
*/
public static String printTimeFromMilliseconds(long milliseconds) {
if ((milliseconds > 1000) && (milliseconds < 60000)) {
return (milliseconds / 1000) + "s";
}
if (milliseconds > 60000) {
return (milliseconds / 60000) + "min " + printTimeFromMilliseconds(milliseconds % 60000);
}
return milliseconds + "ms";
}
/**
* Given a Vector, print it, even if there is a null in it
*/
public static String printVector(Vector vector) {
StringWriter stringWriter = new StringWriter();
stringWriter.write("[");
Enumeration enumtr = vector.elements();
stringWriter.write(String.valueOf(enumtr.nextElement()));
while (enumtr.hasMoreElements()) {
stringWriter.write(" ");
stringWriter.write(String.valueOf(enumtr.nextElement()));
}
stringWriter.write("]");
return stringWriter.toString();
}
public static Hashtable rehashHashtable(Hashtable table) {
Hashtable rehashedTable = new Hashtable(table.size() + 2);
Enumeration values = table.elements();
for (Enumeration keys = table.keys(); keys.hasMoreElements();) {
Object key = keys.nextElement();
Object value = values.nextElement();
rehashedTable.put(key, value);
}
return rehashedTable;
}
public static Map rehashMap(Map table) {
HashMap rehashedTable = new HashMap(table.size() + 2);
Iterator values = table.values().iterator();
for (Iterator keys = table.keySet().iterator(); keys.hasNext();) {
Object key = keys.next();
Object value = values.next();
rehashedTable.put(key, value);
}
return rehashedTable;
}
/**
* Returns a String which has had enough non-alphanumeric characters removed to be equal to
* the maximumStringLength.
*/
public static String removeAllButAlphaNumericToFit(String s1, int maximumStringLength) {
int s1Size = s1.length();
if (s1Size <= maximumStringLength) {
return s1;
}
// Remove the necessary number of characters
StringBuffer buf = new StringBuffer();
int numberOfCharsToBeRemoved = s1.length() - maximumStringLength;
int s1Index = 0;
while ((numberOfCharsToBeRemoved > 0) && (s1Index < s1Size)) {
char currentChar = s1.charAt(s1Index);
if (Character.isLetterOrDigit(currentChar)) {
buf.append(currentChar);
} else {
numberOfCharsToBeRemoved--;
}
s1Index++;
}
// Append the rest of the character that were not parsed through.
// Is it quicker to build a substring and append that?
while (s1Index < s1Size) {
buf.append(s1.charAt(s1Index));
s1Index++;
}
//
return buf.toString();
}
/**
* Returns a String which has had enough of the specified character removed to be equal to
* the maximumStringLength.
*/
public static String removeCharacterToFit(String s1, char aChar, int maximumStringLength) {
int s1Size = s1.length();
if (s1Size <= maximumStringLength) {
return s1;
}
// Remove the necessary number of characters
StringBuffer buf = new StringBuffer();
int numberOfCharsToBeRemoved = s1.length() - maximumStringLength;
int s1Index = 0;
while ((numberOfCharsToBeRemoved > 0) && (s1Index < s1Size)) {
char currentChar = s1.charAt(s1Index);
if (currentChar == aChar) {
numberOfCharsToBeRemoved--;
} else {
buf.append(currentChar);
}
s1Index++;
}
// Append the rest of the character that were not parsed through.
// Is it quicker to build a substring and append that?
while (s1Index < s1Size) {
buf.append(s1.charAt(s1Index));
s1Index++;
}
//
return buf.toString();
}
/**
* Returns a String which has had enough of the specified character removed to be equal to
* the maximumStringLength.
*/
public static String removeVowels(String s1) {
// Remove the vowels
StringBuffer buf = new StringBuffer();
int s1Size = s1.length();
int s1Index = 0;
while (s1Index < s1Size) {
char currentChar = s1.charAt(s1Index);
if (!isVowel(currentChar)) {
buf.append(currentChar);
}
s1Index++;
}
//
return buf.toString();
}
/**
* Replaces the first subString of the source with the replacement.
*/
public static String replaceFirstSubString(String source, String subString, String replacement) {
int index = source.indexOf(subString);
if (index >= 0) {
return source.substring(0, index) + replacement + source.substring(index + subString.length());
}
return null;
}
public static Vector reverseVector(Vector theVector) {
Vector tempVector = new Vector(theVector.size());
Object currentElement;
for (int i = theVector.size() - 1; i > -1; i--) {
currentElement = theVector.elementAt(i);
tempVector.addElement(currentElement);
}
return tempVector;
}
/**
* Returns a new string with all space characters removed from the right
*
* @param originalString - timestamp representation of date
* @return - String
*/
public static String rightTrimString(String originalString) {
int len = originalString.length();
while ((len > 0) && (originalString.charAt(len - 1) <= ' ')) {
len--;
}
return originalString.substring(0, len);
}
/**
* Returns a String which is a concatenation of two string which have had enough
* vowels removed from them so that the sum of the sized of the two strings is less than
* or equal to the specified size.
*/
public static String shortenStringsByRemovingVowelsToFit(String s1, String s2, int maximumStringLength) {
int size = s1.length() + s2.length();
if (size <= maximumStringLength) {
return s1 + s2;
}
// Remove the necessary number of characters
int s1Size = s1.length();
int s2Size = s2.length();
StringBuffer buf1 = new StringBuffer();
StringBuffer buf2 = new StringBuffer();
int numberOfCharsToBeRemoved = size - maximumStringLength;
int s1Index = 0;
int s2Index = 0;
int modulo2 = 0;
// While we still want to remove characters, and not both string are done.
while ((numberOfCharsToBeRemoved > 0) && !((s1Index >= s1Size) && (s2Index >= s2Size))) {
if ((modulo2 % 2) == 0) {
// Remove from s1
if (s1Index < s1Size) {
if (isVowel(s1.charAt(s1Index))) {
numberOfCharsToBeRemoved--;
} else {
buf1.append(s1.charAt(s1Index));
}
s1Index++;
}
} else {
// Remove from s2
if (s2Index < s2Size) {
if (isVowel(s2.charAt(s2Index))) {
numberOfCharsToBeRemoved--;
} else {
buf2.append(s2.charAt(s2Index));
}
s2Index++;
}
}
modulo2++;
}
// Append the rest of the character that were not parsed through.
// Is it quicker to build a substring and append that?
while (s1Index < s1Size) {
buf1.append(s1.charAt(s1Index));
s1Index++;
}
while (s2Index < s2Size) {
buf2.append(s2.charAt(s2Index));
s2Index++;
}
//
return buf1.toString() + buf2.toString();
}
/**
* Answer a sql.Date from a timestamp.
*/
public static java.sql.Date sqlDateFromUtilDate(java.util.Date utilDate) {
// PERF: Avoid deprecated get methods, that are now very inefficient.
Calendar calendar = allocateCalendar();
calendar.setTime(utilDate);
java.sql.Date date = dateFromCalendar(calendar);
releaseCalendar(calendar);
return date;
}
/**
* Print the sql.Date.
*/
public static String printDate(java.sql.Date date) {
// PERF: Avoid deprecated get methods, that are now very inefficient and used from toString.
Calendar calendar = allocateCalendar();
calendar.setTime(date);
String string = printDate(calendar);
releaseCalendar(calendar);
return string;
}
/**
* Print the date part of the calendar.
*/
public static String printDate(Calendar calendar) {
return printDate(calendar, true);
}
/**
* Print the date part of the calendar.
* Normally the calendar must be printed in the local time, but if the timezone is printed,
* it must be printing in its timezone.
*/
public static String printDate(Calendar calendar, boolean useLocalTime) {
int year;
int month;
int day;
if (useLocalTime && (!defaultTimeZone.equals(calendar.getTimeZone()))) {
// Must convert the calendar to the local timezone if different, as dates have no timezone (always local).
Calendar localCalendar = allocateCalendar();
localCalendar.setTimeInMillis(calendar.getTimeInMillis());
year = localCalendar.get(Calendar.YEAR);
month = localCalendar.get(Calendar.MONTH) + 1;
day = localCalendar.get(Calendar.DATE);
releaseCalendar(localCalendar);
} else {
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH) + 1;
day = calendar.get(Calendar.DATE);
}
char[] buf = "2000-00-00".toCharArray();
buf[0] = Character.forDigit(year / 1000, 10);
buf[1] = Character.forDigit((year / 100) % 10, 10);
buf[2] = Character.forDigit((year / 10) % 10, 10);
buf[3] = Character.forDigit(year % 10, 10);
buf[5] = Character.forDigit(month / 10, 10);
buf[6] = Character.forDigit(month % 10, 10);
buf[8] = Character.forDigit(day / 10, 10);
buf[9] = Character.forDigit(day % 10, 10);
return new String(buf);
}
/**
* Print the sql.Time.
*/
public static String printTime(java.sql.Time time) {
// PERF: Avoid deprecated get methods, that are now very inefficient and used from toString.
Calendar calendar = allocateCalendar();
calendar.setTime(time);
String string = printTime(calendar);
releaseCalendar(calendar);
return string;
}
/**
* Print the time part of the calendar.
*/
public static String printTime(Calendar calendar) {
return printTime(calendar, true);
}
/**
* Print the time part of the calendar.
* Normally the calendar must be printed in the local time, but if the timezone is printed,
* it must be printing in its timezone.
*/
public static String printTime(Calendar calendar, boolean useLocalTime) {
int hour;
int minute;
int second;
if (useLocalTime && (!defaultTimeZone.equals(calendar.getTimeZone()))) {
// Must convert the calendar to the local timezone if different, as dates have no timezone (always local).
Calendar localCalendar = allocateCalendar();
localCalendar.setTimeInMillis(calendar.getTimeInMillis());
hour = localCalendar.get(Calendar.HOUR_OF_DAY);
minute = localCalendar.get(Calendar.MINUTE);
second = localCalendar.get(Calendar.SECOND);
releaseCalendar(localCalendar);
} else {
hour = calendar.get(Calendar.HOUR_OF_DAY);
minute = calendar.get(Calendar.MINUTE);
second = calendar.get(Calendar.SECOND);
}
String hourString;
String minuteString;
String secondString;
if (hour < 10) {
hourString = "0" + hour;
} else {
hourString = Integer.toString(hour);
}
if (minute < 10) {
minuteString = "0" + minute;
} else {
minuteString = Integer.toString(minute);
}
if (second < 10) {
secondString = "0" + second;
} else {
secondString = Integer.toString(second);
}
return (hourString + ":" + minuteString + ":" + secondString);
}
/**
* Print the Calendar.
*/
public static String printCalendar(Calendar calendar) {
return printCalendar(calendar, true);
}
/**
* Print the Calendar.
* Normally the calendar must be printed in the local time, but if the timezone is printed,
* it must be printing in its timezone.
*/
public static String printCalendar(Calendar calendar, boolean useLocalTime) {
String millisString;
// String zeros = "000000000";
if (calendar.get(Calendar.MILLISECOND) == 0) {
millisString = "0";
} else {
millisString = buildZeroPrefixAndTruncTrailZeros(calendar.get(Calendar.MILLISECOND), 3);
}
StringBuffer timestampBuf = new StringBuffer();
timestampBuf.append(printDate(calendar, useLocalTime));
timestampBuf.append(" ");
timestampBuf.append(printTime(calendar, useLocalTime));
timestampBuf.append(".");
timestampBuf.append(millisString);
return timestampBuf.toString();
}
/**
* Print the sql.Timestamp.
*/
public static String printTimestamp(java.sql.Timestamp timestamp) {
// PERF: Avoid deprecated get methods, that are now very inefficient and used from toString.
Calendar calendar = allocateCalendar();
calendar.setTime(timestamp);
String nanosString;
if (timestamp.getNanos() == 0) {
nanosString = "0";
} else {
nanosString = buildZeroPrefixAndTruncTrailZeros(timestamp.getNanos(), 9);
}
StringBuffer timestampBuf = new StringBuffer();
timestampBuf.append(printDate(calendar));
timestampBuf.append(" ");
timestampBuf.append(printTime(calendar));
timestampBuf.append(".");
timestampBuf.append(nanosString);
releaseCalendar(calendar);
return (timestampBuf.toString());
}
/**
* Build a numerical string with leading 0s. number is an existing number that
* the new string will be built on. totalDigits is the number of the required
* digits of the string.
*/
public static String buildZeroPrefix(int number, int totalDigits) {
String numbString = buildZeroPrefixWithoutSign(number, totalDigits);
if (number < 0) {
numbString = "-" + numbString;
} else {
numbString = "+" + numbString;
}
return numbString;
}
/**
* Build a numerical string with leading 0s. number is an existing number that
* the new string will be built on. totalDigits is the number of the required
* digits of the string.
*/
public static String buildZeroPrefixWithoutSign(int number, int totalDigits) {
String zeros = "000000000";
int absValue = (number < 0) ? (-number) : number;
String numbString = Integer.toString(absValue);
// Add leading zeros
numbString = zeros.substring(0, (totalDigits - numbString.length())) + numbString;
return numbString;
}
/**
* Build a numerical string with leading 0s and truncate trailing zeros. number is
* an existing number that the new string will be built on. totalDigits is the number
* of the required digits of the string.
*/
public static String buildZeroPrefixAndTruncTrailZeros(int number, int totalDigits) {
String zeros = "000000000";
String numbString = Integer.toString(number);
// Add leading zeros
numbString = zeros.substring(0, (totalDigits - numbString.length())) + numbString;
// Truncate trailing zeros
char[] numbChar = new char[numbString.length()];
numbString.getChars(0, numbString.length(), numbChar, 0);
int truncIndex = totalDigits - 1;
while (numbChar[truncIndex] == '0') {
truncIndex--;
}
return new String(numbChar, 0, truncIndex + 1);
}
/**
* Print the sql.Timestamp without the nanos portion.
*/
public static String printTimestampWithoutNanos(java.sql.Timestamp timestamp) {
// PERF: Avoid deprecated get methods, that are now very inefficient and used from toString.
Calendar calendar = allocateCalendar();
calendar.setTime(timestamp);
String string = printCalendarWithoutNanos(calendar);
releaseCalendar(calendar);
return string;
}
/**
* Print the Calendar without the nanos portion.
*/
public static String printCalendarWithoutNanos(Calendar calendar) {
StringBuffer timestampBuf = new StringBuffer();
timestampBuf.append(printDate(calendar));
timestampBuf.append(" ");
timestampBuf.append(printTime(calendar));
return timestampBuf.toString();
}
/**
* Answer a sql.Date from a Calendar.
*/
public static java.sql.Date dateFromCalendar(Calendar calendar) {
if (!defaultTimeZone.equals(calendar.getTimeZone())) {
// Must convert the calendar to the local timezone if different, as dates have no timezone (always local).
Calendar localCalendar = allocateCalendar();
localCalendar.setTimeInMillis(calendar.getTimeInMillis());
java.sql.Date date = dateFromYearMonthDate(localCalendar.get(Calendar.YEAR), localCalendar.get(Calendar.MONTH), localCalendar.get(Calendar.DATE));
releaseCalendar(localCalendar);
return date;
} else if ((calendar.get(Calendar.HOUR_OF_DAY) == 0)
&& (calendar.get(Calendar.MINUTE) == 0)
&& (calendar.get(Calendar.SECOND) == 0)
&& (calendar.get(Calendar.MILLISECOND) == 0)) {
// PERF: If just a date set in the Calendar, then just use its millis.
return new java.sql.Date(calendar.getTimeInMillis());
}
return dateFromYearMonthDate(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE));
}
/**
* Return a sql.Date with time component zeroed out.
* Starting with version 12.1 Oracle jdbc Statement.setDate method no longer zeroes out the time component.
*/
public static java.sql.Date truncateDate(java.sql.Date date) {
// PERF: Avoid deprecated get methods, that are now very inefficient.
Calendar calendar = allocateCalendar();
calendar.setTime(date);
if ((calendar.get(Calendar.HOUR_OF_DAY) != 0)
|| (calendar.get(Calendar.MINUTE) != 0)
|| (calendar.get(Calendar.SECOND) != 0)
|| (calendar.get(Calendar.MILLISECOND) != 0)) {
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DATE);
calendar.clear();
calendar.set(year, month, day, 0, 0, 0);
long millis = calendar.getTimeInMillis();
date = new java.sql.Date(millis);
}
releaseCalendar(calendar);
return date;
}
/**
* Return a sql.Date with time component zeroed out (with possible exception of milliseconds).
* Starting with version 12.1 Oracle jdbc Statement.setDate method no longer zeroes out the whole time component,
* yet it still zeroes out milliseconds.
*/
public static java.sql.Date truncateDateIgnoreMilliseconds(java.sql.Date date) {
// PERF: Avoid deprecated get methods, that are now very inefficient.
Calendar calendar = allocateCalendar();
calendar.setTime(date);
if ((calendar.get(Calendar.HOUR_OF_DAY) != 0)
|| (calendar.get(Calendar.MINUTE) != 0)
|| (calendar.get(Calendar.SECOND) != 0)) {
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DATE);
calendar.clear();
calendar.set(year, month, day, 0, 0, 0);
long millis = calendar.getTimeInMillis();
date = new java.sql.Date(millis);
}
releaseCalendar(calendar);
return date;
}
/**
* Can be used to mark code if a workaround is added for a JDBC driver or other bug.
*/
public static void systemBug(String description) {
// Use sender to find what is needy.
}
/**
* Answer a Time from a Date
*
* This implementation is based on the java.sql.Date class, not java.util.Date.
* @param timestampObject - time representation of date
* @return - time representation of dateObject
*/
public static java.sql.Time timeFromDate(java.util.Date date) {
// PERF: Avoid deprecated get methods, that are now very inefficient.
Calendar calendar = allocateCalendar();
calendar.setTime(date);
java.sql.Time time = timeFromCalendar(calendar);
releaseCalendar(calendar);
return time;
}
/**
* Answer a Time from a long
*
* @param longObject - milliseconds from the epoch (00:00:00 GMT
* Jan 1, 1970). Negative values represent dates prior to the epoch.
*/
public static java.sql.Time timeFromLong(Long longObject) {
return new java.sql.Time(longObject.longValue());
}
/**
* Answer a Time with the hour, minute, second.
* This builds a time avoiding the deprecated, inefficient and concurrency bottleneck date constructors.
* The hour, minute, second are the values calendar uses,
* i.e. year is from 0, month is 0-11, date is 1-31.
*/
public static java.sql.Time timeFromHourMinuteSecond(int hour, int minute, int second) {
// Use a calendar to compute the correct millis for the date.
Calendar localCalendar = allocateCalendar();
localCalendar.clear();
localCalendar.set(1970, 0, 1, hour, minute, second);
long millis = localCalendar.getTimeInMillis();
java.sql.Time time = new java.sql.Time(millis);
releaseCalendar(localCalendar);
return time;
}
/**
* Answer a Time from a string representation.
* This method will accept times in the following
* formats: HH-MM-SS, HH:MM:SS
*
* @param timeString - string representation of time
* @return - time representation of string
*/
public static java.sql.Time timeFromString(String timeString) throws ConversionException {
int hour;
int minute;
int second;
String timePortion = timeString;
if (timeString.length() > 12) {
// Longer strings are Timestamp format (ie. Sybase & Oracle)
timePortion = timeString.substring(11, 19);
}
if ((timePortion.indexOf('-') == -1) && (timePortion.indexOf('/') == -1) && (timePortion.indexOf('.') == -1) && (timePortion.indexOf(':') == -1)) {
throw ConversionException.incorrectTimeFormat(timePortion);
}
StringTokenizer timeStringTokenizer = new StringTokenizer(timePortion, " /:.-");
try {
hour = Integer.parseInt(timeStringTokenizer.nextToken());
minute = Integer.parseInt(timeStringTokenizer.nextToken());
second = Integer.parseInt(timeStringTokenizer.nextToken());
} catch (NumberFormatException exception) {
throw ConversionException.incorrectTimeFormat(timeString);
}
return timeFromHourMinuteSecond(hour, minute, second);
}
/**
* Answer a Time from a Timestamp
* Usus the Hours, Minutes, Seconds instead of getTime() ms value.
*/
public static java.sql.Time timeFromTimestamp(java.sql.Timestamp timestamp) {
return timeFromDate(timestamp);
}
/**
* Answer a sql.Time from a Calendar.
*/
public static java.sql.Time timeFromCalendar(Calendar calendar) {
if (!defaultTimeZone.equals(calendar.getTimeZone())) {
// Must convert the calendar to the local timezone if different, as dates have no timezone (always local).
Calendar localCalendar = allocateCalendar();
localCalendar.setTimeInMillis(calendar.getTimeInMillis());
java.sql.Time date = timeFromHourMinuteSecond(localCalendar.get(Calendar.HOUR_OF_DAY), localCalendar.get(Calendar.MINUTE), localCalendar.get(Calendar.SECOND));
releaseCalendar(localCalendar);
return date;
}
return timeFromHourMinuteSecond(calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND));
}
/**
* Answer a Timestamp from a Calendar.
*/
public static java.sql.Timestamp timestampFromCalendar(Calendar calendar) {
return timestampFromLong(calendar.getTimeInMillis());
}
/**
* Answer a Timestamp from a java.util.Date.
*/
public static java.sql.Timestamp timestampFromDate(java.util.Date date) {
return timestampFromLong(date.getTime());
}
/**
* Answer a Time from a long
*
* @param longObject - milliseconds from the epoch (00:00:00 GMT
* Jan 1, 1970). Negative values represent dates prior to the epoch.
*/
public static java.sql.Timestamp timestampFromLong(Long millis) {
return timestampFromLong(millis.longValue());
}
/**
* Answer a Time from a long
*
* @param longObject - milliseconds from the epoch (00:00:00 GMT
* Jan 1, 1970). Negative values represent dates prior to the epoch.
*/
public static java.sql.Timestamp timestampFromLong(long millis) {
java.sql.Timestamp timestamp = new java.sql.Timestamp(millis);
// P2.0.1.3: Didn't account for negative millis < 1970
// Must account for the jdk millis bug where it does not set the nanos.
if ((millis % 1000) > 0) {
timestamp.setNanos((int)(millis % 1000) * 1000000);
} else if ((millis % 1000) < 0) {
timestamp.setNanos((int)(1000000000 - (Math.abs((millis % 1000) * 1000000))));
}
return timestamp;
}
/**
* Answer a Timestamp from a string representation.
* This method will accept strings in the following
* formats: YYYY/MM/DD HH:MM:SS, YY/MM/DD HH:MM:SS, YYYY-MM-DD HH:MM:SS, YY-MM-DD HH:MM:SS
*
* @param timestampString - string representation of timestamp
* @return - timestamp representation of string
*/
@SuppressWarnings("deprecation")
public static java.sql.Timestamp timestampFromString(String timestampString) throws ConversionException {
if ((timestampString.indexOf('-') == -1) && (timestampString.indexOf('/') == -1) && (timestampString.indexOf('.') == -1) && (timestampString.indexOf(':') == -1)) {
throw ConversionException.incorrectTimestampFormat(timestampString);
}
StringTokenizer timestampStringTokenizer = new StringTokenizer(timestampString, " /:.-");
int year;
int month;
int day;
int hour;
int minute;
int second;
int nanos;
try {
year = Integer.parseInt(timestampStringTokenizer.nextToken());
month = Integer.parseInt(timestampStringTokenizer.nextToken());
day = Integer.parseInt(timestampStringTokenizer.nextToken());
try {
hour = Integer.parseInt(timestampStringTokenizer.nextToken());
minute = Integer.parseInt(timestampStringTokenizer.nextToken());
second = Integer.parseInt(timestampStringTokenizer.nextToken());
} catch (java.util.NoSuchElementException endOfStringException) {
// May be only a date string desired to be used as a timestamp.
hour = 0;
minute = 0;
second = 0;
}
} catch (NumberFormatException exception) {
throw ConversionException.incorrectTimestampFormat(timestampString);
}
try {
String nanoToken = timestampStringTokenizer.nextToken();
nanos = Integer.parseInt(nanoToken);
for (int times = 0; times < (9 - nanoToken.length()); times++) {
nanos = nanos * 10;
}
} catch (java.util.NoSuchElementException endOfStringException) {
nanos = 0;
} catch (NumberFormatException exception) {
throw ConversionException.incorrectTimestampFormat(timestampString);
}
// Java dates are based on year after 1900 so I need to delete it.
year = year - 1900;
// Java returns the month in terms of 0 - 11 instead of 1 - 12.
month = month - 1;
java.sql.Timestamp timestamp;
// TODO: This was not converted to use Calendar for the conversion because calendars do not take nanos.
// but it should be, and then just call setNanos.
timestamp = new java.sql.Timestamp(year, month, day, hour, minute, second, nanos);
return timestamp;
}
/**
* Answer a Timestamp with the year, month, day, hour, minute, second.
* The hour, minute, second are the values calendar uses,
* i.e. year is from 0, month is 0-11, date is 1-31, time is 0-23/59.
*/
@SuppressWarnings("deprecation")
public static java.sql.Timestamp timestampFromYearMonthDateHourMinuteSecondNanos(int year, int month, int date, int hour, int minute, int second, int nanos) {
// This was not converted to use Calendar for the conversion because calendars do not take nanos.
// but it should be, and then just call setNanos.
return new java.sql.Timestamp(year - 1900, month, date, hour, minute, second, nanos);
}
/**
* Can be used to mark code as need if something strange is seen.
*/
public static void toDo(String description) {
// Use sender to find what is needy.
}
/**
* Convert dotted format class name to slashed format class name.
* @param dottedClassName
* @return String
*/
public static String toSlashedClassName(String dottedClassName){
if(dottedClassName==null){
return null;
}else if(dottedClassName.indexOf('.')>=0){
return dottedClassName.replace('.', '/');
}else{
return dottedClassName;
}
}
/**
* If the size of the original string is larger than the passed in size,
* this method will remove the vowels from the original string.
*
* The removal starts backward from the end of original string, and stops if the
* resulting string size is equal to the passed in size.
*
* If the resulting string is still larger than the passed in size after
* removing all vowels, the end of the resulting string will be truncated.
*/
public static String truncate(String originalString, int size) {
if (originalString.length() <= size) {
//no removal and truncation needed
return originalString;
}
String vowels = "AaEeIiOoUu";
StringBuffer newStringBufferTmp = new StringBuffer(originalString.length());
//need to remove the extra characters
int counter = originalString.length() - size;
for (int index = (originalString.length() - 1); index >= 0; index--) {
//search from the back to the front, if vowel found, do not append it to the resulting (temp) string!
//i.e. if vowel not found, append the chararcter to the new string buffer.
if (vowels.indexOf(originalString.charAt(index)) == -1) {
newStringBufferTmp.append(originalString.charAt(index));
} else {
//vowel found! do NOT append it to the temp buffer, and decrease the counter
counter--;
if (counter == 0) {
//if the exceeded characters (counter) of vowel haven been removed, the total
//string size should be equal to the limits, so append the reversed remaining string
//to the new string, break the loop and return the shrunk string.
StringBuffer newStringBuffer = new StringBuffer(size);
newStringBuffer.append(originalString.substring(0, index));
//need to reverse the string
//bug fix: 3016423. append(BunfferString) is jdk1.4 version api. Use append(String) instead
//in order to support jdk1.3.
newStringBuffer.append(newStringBufferTmp.reverse().toString());
return newStringBuffer.toString();
}
}
}
//the shrunk string still too long, revrese the order back and truncate it!
return newStringBufferTmp.reverse().toString().substring(0, size);
}
/**
* Answer a Date from a long
*
* This implementation is based on the java.sql.Date class, not java.util.Date.
* @param longObject - milliseconds from the epoch (00:00:00 GMT
* Jan 1, 1970). Negative values represent dates prior to the epoch.
*/
public static java.util.Date utilDateFromLong(Long longObject) {
return new java.util.Date(longObject.longValue());
}
/**
* Answer a java.util.Date from a sql.date
*
* @param sqlDate - sql.date representation of date
* @return - java.util.Date representation of the sql.date
*/
public static java.util.Date utilDateFromSQLDate(java.sql.Date sqlDate) {
return new java.util.Date(sqlDate.getTime());
}
/**
* Answer a java.util.Date from a sql.Time
*
* @param time - time representation of util date
* @return - java.util.Date representation of the time
*/
public static java.util.Date utilDateFromTime(java.sql.Time time) {
return new java.util.Date(time.getTime());
}
/**
* Answer a java.util.Date from a timestamp
*
* @param timestampObject - timestamp representation of date
* @return - java.util.Date representation of timestampObject
*/
public static java.util.Date utilDateFromTimestamp(java.sql.Timestamp timestampObject) {
// Bug 2719624 - Conditionally remove workaround for java bug which truncated
// nanoseconds from timestamp.getTime(). We will now only recalculate the nanoseconds
// When timestamp.getTime() results in nanoseconds == 0;
long time = timestampObject.getTime();
boolean appendNanos = ((time % 1000) == 0);
if (appendNanos) {
return new java.util.Date(time + (timestampObject.getNanos() / 1000000));
} else {
return new java.util.Date(time);
}
}
/**
* Convert the specified array into a vector.
*/
public static Vector vectorFromArray(Object[] array) {
Vector result = new Vector(array.length);
for (int i = 0; i < array.length; i++) {
result.addElement(array[i]);
}
return result;
}
/**
* Convert the byte array to a HEX string.
* HEX allows for binary data to be printed.
*/
public static void writeHexString(byte[] bytes, Writer writer) throws IOException {
writer.write(buildHexStringFromBytes(bytes));
}
/**
* Check if the value is 0 (int/long) for primitive ids.
*/
public static boolean isEquivalentToNull(Object value) {
return (!isZeroValidPrimaryKey
&& (((value.getClass() == ClassConstants.LONG) && (((Long)value).longValue() == 0L))
|| ((value.getClass() == ClassConstants.INTEGER) && (((Integer)value).intValue() == 0))));
}
/**
* Returns true if the passed value is Number that is negative or equals to zero.
*/
public static boolean isNumberNegativeOrZero(Object value) {
return ((value.getClass() == ClassConstants.BIGDECIMAL) && (((BigDecimal)value).signum() <= 0)) ||
((value.getClass() == ClassConstants.BIGINTEGER) && (((BigInteger)value).signum() <= 0)) ||
((value instanceof Number) && (((Number)value).longValue() <= 0));
}
/**
* Return an integer representing the number of occurrences (using equals()) of the
* specified object in the specified list.
* If the list is null or empty (or both the object and the list is null), 0 is returned.
*/
public static int countOccurrencesOf(Object comparisonObject, List list) {
int instances = 0;
boolean comparisonObjectIsNull = comparisonObject == null;
if (list != null) {
for (int i = 0; i < list.size(); i++) {
Object listObject = list.get(i);
if ((comparisonObjectIsNull & listObject == null) || (!comparisonObjectIsNull && comparisonObject.equals(listObject))) {
instances++;
}
}
}
return instances;
}
/**
* Convert the URL into a URI allowing for special chars.
*/
public static URI toURI(java.net.URL url) throws URISyntaxException {
try {
// Attempt to use url.toURI since it will deal with all urls
// without special characters and URISyntaxException allows us
// to catch issues with special characters. This will handle
// URLs that already have special characters replaced such as
// URLS derived from searches for persistence.xml on the Java
// System class loader
return url.toURI();
} catch (URISyntaxException exception) {
// Use multi-argument constructor for URI since single-argument
// constructor and URL.toURI() do not deal with special
// characters in path
return new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), null);
}
}
/**
* Return the get method name weaved for a value-holder attribute.
*/
public static String getWeavedValueHolderGetMethodName(String attributeName) {
return PERSISTENCE_GET + attributeName + "_vh";
}
/**
* Return the set method name weaved for a value-holder attribute.
*/
public static String getWeavedValueHolderSetMethodName(String attributeName) {
return PERSISTENCE_SET + attributeName + "_vh";
}
/**
* Return the set method name weaved for getting attribute value.
* This method is always weaved in field access case.
* In property access case the method weaved only if attribute name is the same as property name:
* for instance, the method weaved for "manager" attribute that uses "getManager" / "setManager" access methods,
* but not for "m_address" attribute that uses "getAddress" / "setAddress" access methods.
*/
public static String getWeavedGetMethodName(String attributeName) {
return PERSISTENCE_GET + attributeName;
}
/**
* Return the set method name weaved for setting attribute value.
* This method is always weaved in field access case.
* In property access case the method weaved only if attribute name is the same as property name:
* for instance, the method weaved for "manager" attribute that uses "getManager" / "setManager" access methods,
* but not for "m_address" attribute that uses "getAddress" / "setAddress" access methods.
*/
public static String getWeavedSetMethodName(String attributeName) {
return PERSISTENCE_SET + attributeName;
}
/**
* Close a closeable object, eating the exception
*/
public static void close(Closeable c) {
try {
if (c != null) {
c.close();
}
} catch (IOException exception) {
}
}
/**
* INTERNAL:
* Method to convert a getXyz or isXyz method name to an xyz attribute name.
* NOTE: The method name passed it may not actually be a method name, so
* by default return the name passed in.
*/
public static String getAttributeNameFromMethodName(String methodName) {
String restOfName = methodName;
// We're looking at method named 'get' or 'set', therefore,
// there is no attribute name, set it to "" string for now.
if (methodName.equals(GET_PROPERTY_METHOD_PREFIX) || methodName.equals(IS_PROPERTY_METHOD_PREFIX)) {
return "";
} else if (methodName.startsWith(GET_PROPERTY_METHOD_PREFIX)) {
restOfName = methodName.substring(POSITION_AFTER_GET_PREFIX);
} else if (methodName.startsWith(IS_PROPERTY_METHOD_PREFIX)){
restOfName = methodName.substring(POSITION_AFTER_IS_PREFIX);
}
//added for bug 234222 - property name generation differs from Introspector.decapitalize
return java.beans.Introspector.decapitalize(restOfName);
}
public static String getDefaultStartDatabaseDelimiter(){
if (defaultStartDatabaseDelimiter == null){
defaultStartDatabaseDelimiter = DEFAULT_DATABASE_DELIMITER;
}
return defaultStartDatabaseDelimiter;
}
public static String getDefaultEndDatabaseDelimiter(){
if (defaultEndDatabaseDelimiter == null){
defaultEndDatabaseDelimiter = DEFAULT_DATABASE_DELIMITER;
}
return defaultEndDatabaseDelimiter;
}
public static void setDefaultStartDatabaseDelimiter(String delimiter){
defaultStartDatabaseDelimiter = delimiter;
}
public static void setDefaultEndDatabaseDelimiter(String delimiter){
defaultEndDatabaseDelimiter = delimiter;
}
/**
* Convert the SQL like pattern to a regex pattern.
*/
public static String convertLikeToRegex(String like) {
// Bug 3936427 - Replace regular expression reserved characters with escaped version of those characters
// For instance replace ? with \?
String pattern = like.replaceAll("\\?", "\\\\?");
pattern = pattern.replaceAll("\\*", "\\\\*");
pattern = pattern.replaceAll("\\.", "\\\\.");
pattern = pattern.replaceAll("\\[", "\\\\[");
pattern = pattern.replaceAll("\\)", "\\\\)");
pattern = pattern.replaceAll("\\(", "\\\\(");
pattern = pattern.replaceAll("\\{", "\\\\{");
pattern = pattern.replaceAll("\\+", "\\\\+");
pattern = pattern.replaceAll("\\^", "\\\\^");
pattern = pattern.replaceAll("\\|", "\\\\|");
// regular expressions to substitute SQL wildcards with regex wildcards
// Use look behind operators to replace "%" which is not preceded by "\" with ".*"
pattern = pattern.replaceAll("(?<!\\\\)%", ".*");
// Use look behind operators to replace "_" which is not preceded by "\" with "."
pattern = pattern.replaceAll("(?<!\\\\)_", ".");
// replace "\%" with "%"
pattern = pattern.replaceAll("\\\\%", "%");
// replace "\_" with "_"
pattern = pattern.replaceAll("\\\\_", "_");
// regex requires ^ and $ if pattern must start at start and end at end of string as like requires.
pattern = "^" + pattern + "$";
return pattern;
}
}
| bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs | foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/helper/Helper.java | Java | epl-1.0 | 92,748 |
package com.odcgroup.page.model.widgets.matrix.impl;
import com.odcgroup.page.metamodel.MetaModel;
import com.odcgroup.page.metamodel.WidgetLibrary;
import com.odcgroup.page.metamodel.WidgetTemplate;
import com.odcgroup.page.metamodel.util.MetaModelRegistry;
import com.odcgroup.page.model.Widget;
import com.odcgroup.page.model.util.WidgetFactory;
import com.odcgroup.page.model.widgets.matrix.IMatrix;
import com.odcgroup.page.model.widgets.matrix.IMatrixAxis;
import com.odcgroup.page.model.widgets.matrix.IMatrixCell;
import com.odcgroup.page.model.widgets.matrix.IMatrixCellItem;
import com.odcgroup.page.model.widgets.matrix.IMatrixContentCell;
import com.odcgroup.page.model.widgets.matrix.IMatrixContentCellItem;
import com.odcgroup.page.model.widgets.matrix.IMatrixExtra;
import com.odcgroup.page.model.widgets.matrix.IMatrixExtraColumn;
import com.odcgroup.page.model.widgets.matrix.IMatrixExtraColumnItem;
import com.odcgroup.page.model.widgets.matrix.IMatrixFactory;
/**
*
* @author pkk
*
*/
public class MatrixFactory implements IMatrixFactory {
private static final String WIDGETTYPE_MATRIX = "Matrix";
private static final String WIDGETTYPE_MATRIXAXIS = "MatrixAxis";
private static final String WIDGETTYPE_MATRIXCELL = "MatrixCell";
private static final String WIDGETTYPE_MATRIXCONTENTCELL = "MatrixContentCell";
private static final String WIDGETTYPE_MATRIXCONTENTCELLITEM = "MatrixContentCellItem";
private static final String WIDGETTYPE_MATRIXCELLITEM = "MatrixCellItem";
private static final String WIDGETTYPE_MATRIXEXTRACOLUMN = "MatrixExtraColumn";
private static final String WIDGETTYPE_MATRIXEXTRACOLUMNITEM = "MatrixExtraColumnItem";
private static final String MATRIX_EXTRA_TEMPLATE = "MatrixExtra";
/** name of the xgui library */
private static final String XGUI_LIBRARY = "xgui";
/* (non-Javadoc)
* @see com.odcgroup.page.model.widgets.matrix.IMatrixFactory#adaptMatrixWidget(com.odcgroup.page.model.Widget)
*/
public IMatrix adaptMatrixWidget(Widget widget) {
if (!WIDGETTYPE_MATRIX.equalsIgnoreCase(widget.getTypeName())) {
throw new IllegalArgumentException("This is not a Matrix widget");
}
return new Matrix(widget);
}
/* (non-Javadoc)
* @see com.odcgroup.page.model.widgets.matrix.IMatrixFactory#adaptMatrixAxisWidget(com.odcgroup.page.model.Widget)
*/
public IMatrixAxis adaptMatrixAxisWidget(Widget widget) {
if (!WIDGETTYPE_MATRIXAXIS.equalsIgnoreCase(widget.getTypeName())) {
throw new IllegalArgumentException("This is not a MatrixAxis widget");
}
return new MatrixAxis(widget);
}
/* (non-Javadoc)
* @see com.odcgroup.page.model.widgets.matrix.IMatrixFactory#adaptMatrixCellWidget(com.odcgroup.page.model.Widget)
*/
public IMatrixCell adaptMatrixCellWidget(Widget widget) {
if (!WIDGETTYPE_MATRIXCELL.equalsIgnoreCase(widget.getTypeName())) {
throw new IllegalArgumentException("This is not a MatrixCell widget");
}
return new MatrixCell(widget);
}
/* (non-Javadoc)
* @see com.odcgroup.page.model.widgets.matrix.IMatrixFactory#adaptMatrixContentCellWidget(com.odcgroup.page.model.Widget)
*/
@Override
public IMatrixContentCell adaptMatrixContentCellWidget(Widget widget) {
if (!WIDGETTYPE_MATRIXCONTENTCELL.equalsIgnoreCase(widget.getTypeName())) {
throw new IllegalArgumentException("This is not a MatrixContentCell widget");
}
return new MatrixContentCell(widget);
}
/* (non-Javadoc)
* @see com.odcgroup.page.model.widgets.matrix.IMatrixFactory#adaptMatrixCellItemWidget(com.odcgroup.page.model.Widget)
*/
@Override
public IMatrixCellItem adaptMatrixCellItemWidget(Widget widget) {
if (!WIDGETTYPE_MATRIXCELLITEM.equalsIgnoreCase(widget.getTypeName())) {
throw new IllegalArgumentException("This is not a MatrixCellItem widget");
}
return new MatrixCellItem(widget);
}
/* (non-Javadoc)
* @see com.odcgroup.page.model.widgets.matrix.IMatrixFactory#adaptMatrixContentCellItemWidget(com.odcgroup.page.model.Widget)
*/
@Override
public IMatrixContentCellItem adaptMatrixContentCellItemWidget(Widget widget) {
if (!WIDGETTYPE_MATRIXCONTENTCELLITEM.equalsIgnoreCase(widget.getTypeName())) {
throw new IllegalArgumentException("This is not a MatrixContentCellItem widget");
}
return new MatrixContentCellItem(widget);
}
/* (non-Javadoc)
* @see com.odcgroup.page.model.widgets.matrix.IMatrixFactory#adapatMatrixExtraColumnItemWidget(com.odcgroup.page.model.Widget)
*/
@Override
public IMatrixExtraColumnItem adapatMatrixExtraColumnItemWidget(Widget widget) {
if (!WIDGETTYPE_MATRIXEXTRACOLUMNITEM.equalsIgnoreCase(widget.getTypeName())) {
throw new IllegalArgumentException("This is not a MatrixExtraColumnItem widget");
}
return new MatrixExtraColumnItem(widget);
}
/* (non-Javadoc)
* @see com.odcgroup.page.model.widgets.matrix.IMatrixFactory#adapatMatrixExtraColumnWidget(com.odcgroup.page.model.Widget)
*/
@Override
public IMatrixExtraColumn adapatMatrixExtraColumnWidget(Widget widget) {
if (!WIDGETTYPE_MATRIXEXTRACOLUMN.equalsIgnoreCase(widget.getTypeName())) {
throw new IllegalArgumentException("This is not a MatrixExtraColumn widget");
}
return new MatrixExtraColumn(widget);
}
/* (non-Javadoc)
* @see com.odcgroup.page.model.widgets.matrix.IMatrixFactory#createTableExtra()
*/
@Override
public IMatrixExtra createTableExtra() {
Widget widget = createWidget(MATRIX_EXTRA_TEMPLATE);
return new MatrixExtra(widget);
}
/**
* Create a new Widget instance given its template name
* @param TemplateName the name of the widget template
* @return Widget
*/
protected Widget createWidget(String TemplateName) {
MetaModel metamodel = MetaModelRegistry.getMetaModel();
WidgetLibrary library = metamodel.findWidgetLibrary(XGUI_LIBRARY);
WidgetTemplate template = library.findWidgetTemplate(TemplateName);
WidgetFactory factory = new WidgetFactory();
Widget widget = factory.create(template);
return widget;
}
}
| debabratahazra/DS | designstudio/components/page/core/com.odcgroup.page.model/src/main/java/com/odcgroup/page/model/widgets/matrix/impl/MatrixFactory.java | Java | epl-1.0 | 5,946 |
package com.odcgroup.t24.enquiry.editor.part;
import org.eclipse.draw2d.IFigure;
import org.eclipse.gef.EditPolicy;
import com.google.common.base.Joiner;
import com.odcgroup.t24.enquiry.editor.policy.EnquiryEditorComponentEditPolicy;
import com.odcgroup.t24.enquiry.enquiry.SelectionCriteria;
import com.odcgroup.t24.enquiry.figure.SelectionCriteriaFigure;
/**
*
* @author phanikumark
*
*/
public class SelectionCriteriaEditPart extends AbstractEnquiryEditPart {
@Override
protected IFigure createFigure() {
return new SelectionCriteriaFigure();
}
@Override
protected void createEditPolicies() {
installEditPolicy(EditPolicy.COMPONENT_ROLE, new EnquiryEditorComponentEditPolicy());
}
@Override
protected void refreshVisuals() {
SelectionCriteriaFigure figure = (SelectionCriteriaFigure) getFigure();
SelectionCriteria model = (SelectionCriteria) getModel();
final String labelText = Joiner.on(" ").join(model.getField(), model.getOperand(), model.getValues());
figure.getFieldLabel().setText(labelText);
}
}
| debabratahazra/DS | designstudio/components/t24/ui/com.odcgroup.t24.enquiry.editor/src/main/java/com/odcgroup/t24/enquiry/editor/part/SelectionCriteriaEditPart.java | Java | epl-1.0 | 1,040 |
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Free Eclipse icons';
}
| 32kda/com.onpositive.images | src/src/app/app.component.ts | TypeScript | epl-1.0 | 222 |
package de.simonscholz.junit4converter.converters;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.SimpleType;
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
import org.eclipse.jdt.core.dom.rewrite.ImportRewrite;
import de.simonscholz.junit4converter.JUnit4Converter;
public class StandardModuleTestCaseConverter extends JUnit4Converter implements
Converter {
private static final String MODULETESTCASE_CLASSNAME = "StandardModulTestCase";
private static final String MODULETESTCASE_QUALIFIEDNAME = "CH.obj.Application.Global.Servicelib.StandardModulTestCase";
private static final String MODULETEST_CLASSNAME = "StandardModulTest";
private static final String MODULETEST_QUALIFIEDNAME = "CH.obj.Application.Global.Servicelib.StandardModulTest";
private static final String BEFORE_METHOD = "checkPreconditions";
private final AST ast;
private final ASTRewrite rewriter;
private final ImportRewrite importRewriter;
private boolean wasModified;
private TestConversionHelper helper;
StandardModuleTestCaseConverter(AST ast, ASTRewrite rewriter,
ImportRewrite importRewriter) {
this.ast = ast;
this.rewriter = rewriter;
this.importRewriter = importRewriter;
this.helper = new TestConversionHelper(rewriter, importRewriter);
}
@Override
public boolean isConvertable(TypeDeclaration typeDeclaration) {
return helper.isTestCase(MODULETESTCASE_CLASSNAME, typeDeclaration);
}
@Override
public void convert(TypeDeclaration typeDeclaration) {
wasModified = true;
replaceSuperClass(typeDeclaration.getSuperclassType());
convertCheckPreConditionsIntoBefore(typeDeclaration.getMethods());
}
private void convertCheckPreConditionsIntoBefore(
MethodDeclaration... methods) {
for (MethodDeclaration method : methods) {
String methodName = method.getName().getFullyQualifiedName();
if (methodName.equals(BEFORE_METHOD)) {
removeAnnotation(rewriter, method, OVERRIDE_ANNOTATION_NAME);
createMarkerAnnotation(ast, rewriter, method,
BEFORE_ANNOTATION_NAME);
convertProtectedToPublic(ast, rewriter, method);
importRewriter.addImport(BEFORE_ANNOTATION_QUALIFIED_NAME);
}
}
}
private void replaceSuperClass(Type superclassType) {
SimpleType newNoDBTestRulesProviderSuperType = ast.newSimpleType(ast
.newSimpleName(MODULETEST_CLASSNAME));
rewriter.replace(superclassType, newNoDBTestRulesProviderSuperType,
null);
importRewriter.removeImport(MODULETESTCASE_QUALIFIEDNAME);
importRewriter.addImport(MODULETEST_QUALIFIEDNAME);
wasModified = true;
}
@Override
public boolean wasConverted() {
return wasModified;
}
}
| WtfJoke/codemodify | de.simonscholz.codemodify/src/de/simonscholz/junit4converter/converters/StandardModuleTestCaseConverter.java | Java | epl-1.0 | 2,841 |
require "rjava"
# Copyright (c) 2000, 2008 IBM Corporation and others.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# IBM Corporation - initial API and implementation
module Org::Eclipse::Swt::Internal::Win32
module BITMAPImports #:nodoc:
class_module.module_eval {
include ::Java::Lang
include ::Org::Eclipse::Swt::Internal::Win32
}
end
class BITMAP
include_class_members BITMAPImports
attr_accessor :bm_type
alias_method :attr_bm_type, :bm_type
undef_method :bm_type
alias_method :attr_bm_type=, :bm_type=
undef_method :bm_type=
attr_accessor :bm_width
alias_method :attr_bm_width, :bm_width
undef_method :bm_width
alias_method :attr_bm_width=, :bm_width=
undef_method :bm_width=
attr_accessor :bm_height
alias_method :attr_bm_height, :bm_height
undef_method :bm_height
alias_method :attr_bm_height=, :bm_height=
undef_method :bm_height=
attr_accessor :bm_width_bytes
alias_method :attr_bm_width_bytes, :bm_width_bytes
undef_method :bm_width_bytes
alias_method :attr_bm_width_bytes=, :bm_width_bytes=
undef_method :bm_width_bytes=
attr_accessor :bm_planes
alias_method :attr_bm_planes, :bm_planes
undef_method :bm_planes
alias_method :attr_bm_planes=, :bm_planes=
undef_method :bm_planes=
attr_accessor :bm_bits_pixel
alias_method :attr_bm_bits_pixel, :bm_bits_pixel
undef_method :bm_bits_pixel
alias_method :attr_bm_bits_pixel=, :bm_bits_pixel=
undef_method :bm_bits_pixel=
# @field cast=(LPVOID)
# long
attr_accessor :bm_bits
alias_method :attr_bm_bits, :bm_bits
undef_method :bm_bits
alias_method :attr_bm_bits=, :bm_bits=
undef_method :bm_bits=
class_module.module_eval {
const_set_lazy(:Sizeof) { OS._bitmap_sizeof }
const_attr_reader :Sizeof
}
typesig { [] }
def initialize
@bm_type = 0
@bm_width = 0
@bm_height = 0
@bm_width_bytes = 0
@bm_planes = 0
@bm_bits_pixel = 0
@bm_bits = 0
end
private
alias_method :initialize__bitmap, :initialize
end
end
| neelance/swt4ruby | swt4ruby/lib/mingw32-x86_32/org/eclipse/swt/internal/win32/BITMAP.rb | Ruby | epl-1.0 | 2,394 |
/*
* Copyright (c) 2015-2018 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
| sleshchenko/che | dashboard/src/app/stacks/list-stacks/import-stack/import-stack.controller.ts | TypeScript | epl-1.0 | 366 |
/**
* Copyright (c) 2014 Kay Erik Münch.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.spdx.org/licenses/EPL-1.0
*
* Contributors:
* Kay Erik Münch - initial API and implementation
*
*/
package de.kay_muench.reqif10.reqifcompiler.types.complex;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.emf.common.util.EList;
import org.eclipse.rmf.reqif10.AttributeDefinitionEnumeration;
import org.eclipse.rmf.reqif10.AttributeValueEnumeration;
import org.eclipse.rmf.reqif10.EnumValue;
import org.eclipse.rmf.reqif10.ReqIF10Factory;
public class EnumeratedAttributeValue {
private AttributeValueEnumeration value;
public EnumeratedAttributeValue(AttributeDefinitionEnumeration def) {
value = ReqIF10Factory.eINSTANCE.createAttributeValueEnumeration();
value.setDefinition(def);
}
public AttributeValueEnumeration getValue() {
return value;
}
public void setValue(int v) {
List<EnumValue> newValues = new ArrayList<EnumValue>();
final EList<EnumValue> enumValues = value.getDefinition().getType()
.getSpecifiedValues();
for (EnumValue enumValue : enumValues) {
if (enumValue.getProperties().getKey()
.equals(BigInteger.valueOf(v))) {
newValues.add(enumValue);
break;
}
}
value.getValues().clear();
value.getValues().addAll(newValues);
}
} | KayErikMuench/reqiftools | reqifcompiler/src/main/java/de/kay_muench/reqif10/reqifcompiler/types/complex/EnumeratedAttributeValue.java | Java | epl-1.0 | 1,520 |
<?php
/**
*
*
* Copyright (c) 2010 Keith Palmer / ConsoliBYTE, LLC.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* @license LICENSE.txt
* @author Keith Palmer <Keith@ConsoliBYTE.com>
*
* @package QuickBooks
* @subpackage IPP
*/
QuickBooks_Loader::load('/QuickBooks/IPP/Service.php');
class QuickBooks_IPP_Service_Invoice extends QuickBooks_IPP_Service
{
public function findAll($Context, $realmID, $query = null, $page = 1, $size = 50)
{
return parent::_findAll($Context, $realmID, QuickBooks_IPP_IDS::RESOURCE_INVOICE, $query, null, $page, $size);
}
/**
*
*
*
*/
public function findById($Context, $realmID, $ID, $domain = null)
{
$xml = null;
return parent::_findById($Context, $realmID, QuickBooks_IPP_IDS::RESOURCE_INVOICE, $ID, $domain, $xml);
}
public function add($Context, $realmID, $Object)
{
return parent::_add($Context, $realmID, QuickBooks_IPP_IDS::RESOURCE_INVOICE, $Object);
}
public function update($Context, $realmID, $IDType, $Object)
{
return parent::_update($Context, $realmID, QuickBooks_IPP_IDS::RESOURCE_INVOICE, $Object, $IDType);
}
public function query($Context, $realm, $query)
{
return parent::_query($Context, $realm, $query);
}
} | 1bigidea/quickbooks-php | QuickBooks/IPP/Service/Invoice.php | PHP | epl-1.0 | 1,436 |
<?php
/**
* @package com_zoo
* @author YOOtheme http://www.yootheme.com
* @copyright Copyright (C) YOOtheme GmbH
* @license http://www.gnu.org/licenses/gpl.html GNU/GPL
*/
/*
Class: ManagerController
The controller class for application manager
*/
class ManagerController extends AppController {
public $group;
public $application;
public function __construct($default = array()) {
parent::__construct($default);
// set base url
$this->baseurl = $this->app->link(array('controller' => $this->controller), false);
// get application group
$this->group = $this->app->request->getString('group');
// if group exists
if ($this->group) {
// add group to base url
$this->baseurl .= '&group='.$this->group;
// create application object
$this->application = $this->app->object->create('Application');
$this->application->setGroup($this->group);
}
// register tasks
$this->registerTask('addtype', 'edittype');
$this->registerTask('applytype', 'savetype');
$this->registerTask('applyelements', 'saveelements');
$this->registerTask('applyassignelements', 'saveassignelements');
$this->registerTask('applysubmission', 'savesubmission');
}
public function display($cachable = false, $urlparams = false) {
// set toolbar items
$this->app->toolbar->title(JText::_('App Manager'), $this->app->get('icon'));
JToolBar::getInstance('toolbar')->appendButton('Popup', 'stats', 'Check For Modifications', JRoute::_(JUri::root() . 'administrator/index.php?option='.$this->app->component->self->name.'&controller='.$this->controller.'&task=checkmodifications&tmpl=component', true, -1), 570, 350);
JToolBar::getInstance('toolbar')->appendButton('Popup', 'preview', 'Check Requirements', JRoute::_(JUri::root() . 'administrator/index.php?option='.$this->app->component->self->name.'&controller='.$this->controller.'&task=checkrequirements&tmpl=component', true, -1), 570, 350);
if ($this->app->get('cache_routes', false)) {
$this->app->toolbar->custom('disableRouteCaching', 'options', 'Disable Route Caching', 'Disable Route Caching', false);
} else {
$this->app->toolbar->custom('enableRouteCaching', 'options', 'Enable Route Caching', 'Enable Route Caching', false);
}
$this->app->toolbar->custom('cleandb', 'refresh', 'Refresh', 'Clean Database', false);
$this->app->toolbar->custom('dobackup', 'archive', 'Backup Database', 'Backup Database', false);
$this->app->zoo->toolbarHelp();
// get applications
$this->applications = $this->app->application->groups();
// display view
$this->getView()->display();
}
public function info() {
// set toolbar items
$this->app->system->application->JComponentTitle = $this->application->getToolbarTitle(JText::_('Information').': '.$this->application->getMetaData('name'));
$this->app->toolbar->custom('doexport', 'archive', 'Archive', 'Export', false);
$this->app->toolbar->custom('uninstallapplication', 'delete', 'Delete', 'Uninstall', false);
$this->app->toolbar->deleteList('APP_DELETE_WARNING', 'removeapplication');
$this->app->zoo->toolbarHelp();
// get application instances for selected group
$this->applications = $this->app->application->getApplications($this->application->getGroup());
// display view
$this->getView()->setLayout('info')->display();
}
public function installApplication() {
// check for request forgeries
$this->app->session->checkToken() or jexit('Invalid Token');
// get the uploaded file information
$userfile = $this->app->request->getVar('install_package', null, 'files', 'array');
try {
$result = $this->app->install->installApplicationFromUserfile($userfile);
$update = $result == 2 ? 'updated' : 'installed';
// set redirect message
$msg = JText::sprintf('Application group (%s) successfully.', $update);
} catch (InstallHelperException $e) {
// raise notice on exception
$this->app->error->raiseNotice(0, JText::sprintf('Error installing Application group (%s).', $e));
$msg = null;
}
$this->setRedirect($this->baseurl, $msg);
}
public function uninstallApplication() {
// check for request forgeries
$this->app->session->checkToken() or jexit('Invalid Token');
try {
$this->app->install->uninstallApplication($this->application);
// set redirect message
$msg = JText::_('Application group uninstalled successful.');
$link = $this->baseurl;
} catch (InstallHelperException $e) {
// raise notice on exception
$this->app->error->raiseNotice(0, JText::sprintf('Error uninstalling application group (%s).', $e));
$msg = null;
$link = $this->baseurl.'&task=info';
}
$this->setRedirect($link, $msg);
}
public function removeApplication() {
// check for request forgeries
$this->app->session->checkToken() or jexit('Invalid Token');
// init vars
$cid = $this->app->request->get('cid', 'array', array());
if (count($cid) < 1) {
$this->app->error->raiseError(500, JText::_('Select a application to delete'));
}
try {
$table = $this->app->table->application;
// delete applications
foreach ($cid as $id) {
$table->delete($table->get($id));
}
// set redirect message
$msg = JText::_('Application Deleted');
} catch (AppException $e) {
// raise notice on exception
$this->app->error->raiseNotice(0, JText::sprintf('Error Deleting Application (%s).', $e));
$msg = null;
}
$this->setRedirect($this->baseurl.'&task=info', $msg);
}
public function types() {
// set toolbar items
$this->app->system->application->JComponentTitle = $this->application->getToolbarTitle(JText::_('Types').': ' . $this->application->getMetaData('name'));
$this->app->toolbar->addNew('addtype');
$this->app->toolbar->custom('copytype', 'copy', '', 'Copy');
$this->app->toolbar->deleteList('', 'removetype');
$this->app->toolbar->editList('edittype');
$this->app->zoo->toolbarHelp();
// get types
$this->types = $this->application->getTypes();
// get templates
$this->templates = $this->application->getTemplates();
// get extensions / trigger layout init event
$this->extensions = $this->app->event->dispatcher->notify($this->app->event->create($this->app, 'layout:init'))->getReturnValue();
// display view
$this->getView()->setLayout('types')->display();
}
public function editType() {
// disable menu
$this->app->request->setVar('hidemainmenu', 1);
// get request vars
$cid = $this->app->request->get('cid.0', 'string', '');
$this->edit = $cid ? true : false;
// get type
if (empty($cid)) {
$this->type = $this->app->object->create('Type', array(null, $this->application));
} else {
$this->type = $this->application->getType($cid);
}
// set toolbar items
$this->app->system->application->JComponentTitle = $this->application->getToolbarTitle(JText::_('Type').': '.$this->type->name.' <small><small>[ '.($this->edit ? JText::_('Edit') : JText::_('New')).' ]</small></small>');
$this->app->toolbar->apply('applytype');
$this->app->toolbar->save('savetype');
$this->app->toolbar->cancel('types', $this->edit ? 'Close' : 'Cancel');
$this->app->zoo->toolbarHelp();
// display view
ob_start();
$this->getView()->setLayout('edittype')->display();
$output = ob_get_contents();
ob_end_clean();
// trigger edit event
$this->app->event->dispatcher->notify($this->app->event->create($this->type, 'type:editdisplay', array('html' => &$output)));
echo $output;
}
public function copyType() {
// check for request forgeries
$this->app->session->checkToken() or jexit('Invalid Token');
// init vars
$msg = '';
$cid = $this->app->request->get('cid', 'array', array());
if (count($cid) < 1) {
$this->app->error->raiseError(500, JText::_('Select a type to copy'));
}
// copy types
foreach ($cid as $id) {
try {
// get type
$type = $this->application->getType($id);
// copy type
$copy = $this->app->object->create('Type', array(null, $this->application));
$copy->identifier = $type->identifier.'-copy'; // set copied alias
$this->app->type->setUniqueIndentifier($copy); // set unique identifier
$copy->name = sprintf('%s (%s)', $type->name, JText::_('Copy')); // set copied name
// give elements a new unique id
$elements = array();
foreach ($type->elements as $identifier => $element) {
if ($type->getElement($identifier) && $type->getElement($identifier)->getGroup() != 'Core') {
$elements[$this->app->utility->generateUUID()] = $element;
} else {
$elements[$identifier] = $element;
}
}
$copy->elements = $elements;
// save copied type
$copy->save();
// trigger copied event
$this->app->event->dispatcher->notify($this->app->event->create($copy, 'type:copied', array('old_id' => $id)));
$msg = JText::_('Type Copied');
} catch (AppException $e) {
// raise notice on exception
$this->app->error->raiseNotice(0, JText::sprintf('Error Copying Type (%s).', $e));
$msg = null;
break;
}
}
$this->setRedirect($this->baseurl.'&task=types', $msg);
}
public function saveType() {
// check for request forgeries
$this->app->session->checkToken() or jexit('Invalid Token');
// init vars
$post = $this->app->request->get('post:', 'array', array());
$cid = $this->app->request->get('cid.0', 'string', '');
// get type
$type = $this->application->getType($cid);
// type is new ?
if (!$type) {
$type = $this->app->object->create('Type', array(null, $this->application));
}
// filter identifier
$post['identifier'] = $this->app->string->sluggify($post['identifier'] == '' ? $post['name'] : $post['identifier'], true);
try {
// set post data and save type
$type->bind($post);
// ensure unique identifier
$this->app->type->setUniqueIndentifier($type);
// save type
$type->save();
// set redirect message
$msg = JText::_('Type Saved');
} catch (AppException $e) {
// raise notice on exception
$this->app->error->raiseNotice(0, JText::sprintf('Error Saving Type (%s).', $e));
$this->_task = 'apply';
$msg = null;
}
switch ($this->getTask()) {
case 'applytype':
$link = $this->baseurl.'&task=edittype&cid[]='.$type->id;
break;
case 'savetype':
default:
$link = $this->baseurl.'&task=types';
break;
}
$this->setRedirect($link, $msg);
}
public function removeType() {
// check for request forgeries
$this->app->session->checkToken() or jexit('Invalid Token');
// init vars
$msg = '';
$cid = $this->app->request->get('cid', 'array', array());
if (count($cid) < 1) {
$this->app->error->raiseError(500, JText::_('Select a type to delete'));
}
foreach ($cid as $id) {
try {
// delete type
$type = $this->application->getType($id);
$type->delete();
// trigger after save event
$this->app->event->dispatcher->notify($this->app->event->create($type, 'type:deleted'));
// set redirect message
$msg = JText::_('Type Deleted');
} catch (AppException $e) {
// raise notice on exception
$this->app->error->raiseNotice(0, JText::sprintf('Error Deleting Type (%s).', $e));
$msg = null;
break;
}
}
$this->setRedirect($this->baseurl.'&task=types', $msg);
}
public function editElements() {
// disable menu
$this->app->request->setVar('hidemainmenu', 1);
// get request vars
$cid = $this->app->request->get('cid.0', 'string', '');
// get type
$this->type = $this->application->getType($cid);
// set toolbar items
$this->app->system->application->JComponentTitle = $this->application->getToolbarTitle(JText::_('Type').': '.$this->type->name.' <small><small>[ '.JText::_('Edit elements').' ]</small></small>');
$this->app->toolbar->apply('applyelements');
$this->app->toolbar->save('saveelements');
$this->app->toolbar->cancel('types', 'Close');
$this->app->zoo->toolbarHelp();
// sort elements by group
$this->elements = array();
foreach ($this->app->element->getAll($this->application) as $element) {
$this->elements[$element->getGroup()][$element->getElementType()] = $element;
}
ksort($this->elements);
foreach ($this->elements as $group => $elements) {
ksort($elements);
$this->elements[$group] = $elements;
}
// display view
$this->getView()->setLayout('editElements')->display();
}
public function addElement() {
// get request vars
$element = $this->app->request->getWord('element', 'text');
// load element
$this->element = $this->app->element->create($element, $this->application);
$this->element->identifier = $this->app->utility->generateUUID();
// display view
$this->getView()->setLayout('addElement')->display();
}
public function saveElements() {
// check for request forgeries
$this->app->session->checkToken() or jexit('Invalid Token');
// init vars
$post = $this->app->request->get('post:', 'array', array());
$cid = $this->app->request->get('cid.0', 'string', '');
try {
// save types elements
$type = $this->application->getType($cid);
// bind and save elements
$type->bindElements($post)->save();
// reset related item search data
$table = $this->app->table->item;
$items = $table->getByType($type->id, $this->application->id);
foreach ($items as $item) {
$table->save($item);
}
$msg = JText::_('Elements Saved');
} catch (AppException $e) {
$this->app->error->raiseNotice(0, JText::sprintf('Error Saving Elements (%s)', $e));
$this->_task = 'applyelements';
$msg = null;
}
switch ($this->getTask()) {
case 'applyelements':
$link = $this->baseurl.'&task=editelements&cid[]='.$type->id;
break;
case 'saveelements':
default:
$link = $this->baseurl.'&task=types';
break;
}
$this->setRedirect($link, $msg);
}
public function assignElements() {
// disable menu
$this->app->request->setVar('hidemainmenu', 1);
// init vars
$type = $this->app->request->getString('type');
$this->relative_path = urldecode($this->app->request->getVar('path'));
$this->path = $this->relative_path ? JPATH_ROOT . '/' . $this->relative_path : '';
$this->layout = $this->app->request->getString('layout');
$dispatcher = JDispatcher::getInstance();
if (strpos($this->relative_path, 'plugins') === 0) {
@list($_, $plugin_type, $plugin_name) = explode('/', $this->relative_path);
JPluginHelper::importPlugin($plugin_type, $plugin_name);
}
$dispatcher->trigger('registerZOOEvents');
// get type
$this->type = $this->application->getType($type);
if ($this->type) {
// set toolbar items
$this->app->system->application->JComponentTitle = $this->application->getToolbarTitle(JText::_('Type').': '.$this->type->name.' <small><small>[ '.JText::_('Assign elements').': '. $this->layout .' ]</small></small>');
$this->app->toolbar->apply('applyassignelements');
$this->app->toolbar->save('saveassignelements');
$this->app->toolbar->cancel('types');
$this->app->zoo->toolbarHelp();
// get renderer
$renderer = $this->app->renderer->create('item')->addPath($this->path);
// get positions and config
$this->config = $renderer->getConfig('item')->get($this->group.'.'.$type.'.'.$this->layout);
$prefix = 'item.';
if ($renderer->pathExists('item'.DIRECTORY_SEPARATOR.$type)) {
$prefix .= $type.'.';
}
$this->positions = $renderer->getPositions($prefix.$this->layout);
// display view
ob_start();
$this->getView()->setLayout('assignelements')->display();
$output = ob_get_contents();
ob_end_clean();
// trigger edit event
$this->app->event->dispatcher->notify($this->app->event->create($this->type, 'type:assignelements', array('html' => &$output)));
echo $output;
} else {
$this->app->error->raiseNotice(0, JText::sprintf('Unable to find type (%s).', $type));
$this->setRedirect($this->baseurl . '&task=types&group=' . $this->application->getGroup());
}
}
public function saveAssignElements() {
// check for request forgeries
$this->app->session->checkToken() or jexit('Invalid Token');
// init vars
$type = $this->app->request->getString('type');
$layout = $this->app->request->getString('layout');
$relative_path = $this->app->request->getVar('path');
$path = $relative_path ? JPATH_ROOT . '/' . urldecode($relative_path) : '';
$positions = $this->app->request->getVar('positions', array(), 'post', 'array');
// unset unassigned position
unset($positions['unassigned']);
// get renderer
$renderer = $this->app->renderer->create('item')->addPath($path);
// clean config
$config = $renderer->getConfig('item');
foreach ($config as $key => $value) {
$parts = explode('.', $key);
if ($parts[0] == $this->group && !$this->application->getType($parts[1])) {
$config->remove($key);
}
}
// save config
$config->set($this->group.'.'.$type.'.'.$layout, $positions);
$renderer->saveConfig($config, $path.'/renderer/item/positions.config');
switch ($this->getTask()) {
case 'applyassignelements':
$link = $this->baseurl.'&task=assignelements&type='.$type.'&layout='.$layout.'&path='.$relative_path;
break;
default:
$link = $this->baseurl.'&task=types';
break;
}
$this->setRedirect($link, JText::_('Elements Assigned'));
}
public function assignSubmission() {
// disable menu
$this->app->request->setVar('hidemainmenu', 1);
// init vars
$type = $this->app->request->getString('type');
$this->template = $this->app->request->getString('template');
$this->layout = $this->app->request->getString('layout');
// get type
$this->type = $this->application->getType($type);
// set toolbar items
$this->app->system->application->JComponentTitle = $this->application->getToolbarTitle(JText::_('Type').': '.$this->type->name.' <small><small>[ '.JText::_('Assign Submittable elements').': '. $this->layout .' ]</small></small>');
$this->app->toolbar->apply('applysubmission');
$this->app->toolbar->save('savesubmission');
$this->app->toolbar->cancel('types');
$this->app->zoo->toolbarHelp();
// for template
$this->path = $this->application->getPath().'/templates/'.$this->template;
// get renderer
$renderer = $this->app->renderer->create('submission')->addPath($this->path);
// get positions and config
$this->config = $renderer->getConfig('item')->get($this->group.'.'.$type.'.'.$this->layout);
$prefix = 'item.';
if ($renderer->pathExists('item'.DIRECTORY_SEPARATOR.$type)) {
$prefix .= $type.'.';
}
$this->positions = $renderer->getPositions($prefix.$this->layout);
// display view
$this->getView()->setLayout('assignsubmission')->display();
}
public function saveSubmission() {
// check for request forgeries
$this->app->session->checkToken() or jexit('Invalid Token');
// init vars
$type = $this->app->request->getString('type');
$template = $this->app->request->getString('template');
$layout = $this->app->request->getString('layout');
$positions = $this->app->request->getVar('positions', array(), 'post', 'array');
// unset unassigned position
unset($positions['unassigned']);
// for template, module
$path = '';
if ($template) {
$path = $this->application->getPath().'/templates/'.$template;
}
// get renderer
$renderer = $this->app->renderer->create('submission')->addPath($path);
// clean config
$config = $renderer->getConfig('item');
foreach ($config as $key => $value) {
$parts = explode('.', $key);
if ($parts[0] == $this->group && !$this->application->getType($parts[1])) {
$config->remove($key);
}
}
// save config
$config->set($this->group.'.'.$type.'.'.$layout, $positions);
$renderer->saveConfig($config, $path.'/renderer/item/positions.config');
switch ($this->getTask()) {
case 'applysubmission':
$link = $this->baseurl.'&task=assignsubmission&type='.$type.'&layout='.$layout;
$link .= $template ? '&template='.$template : null;
break;
default:
$link = $this->baseurl.'&task=types';
break;
}
$this->setRedirect($link, JText::_('Submitable Elements Assigned'));
}
public function doExport() {
// check for request forgeries
$this->app->session->checkToken() or jexit('Invalid Token');
$filepath = $this->app->path->path("tmp:").'/'.$this->application->getGroup().'.zip';
$read_directory = $this->application->getPath() . '/';
$zip = $this->app->archive->open($filepath, 'zip');
$files = $this->app->path->files($this->application->getResource(), true);
$files = array_map(create_function('$file', 'return "'.$read_directory.'".$file;'), $files);
$zip->create($files, PCLZIP_OPT_REMOVE_PATH, $read_directory);
if (is_readable($filepath) && JFile::exists($filepath)) {
$this->app->filesystem->output($filepath);
if (!JFile::delete($filepath)) {
$this->app->error->raiseNotice(0, JText::sprintf('Unable to delete file(%s).', $filepath));
$this->setRedirect($this->baseurl.'&task=info');
}
} else {
$this->app->error->raiseNotice(0, JText::sprintf('Unable to create file (%s).', $filepath));
$this->setRedirect($this->baseurl.'&task=info');
}
}
public function checkRequirements() {
$this->app->loader->register('AppRequirements', 'installation:requirements.php');
$requirements = $this->app->object->create('AppRequirements');
$requirements->checkRequirements();
$requirements->displayResults();
}
public function checkModifications() {
// add system.css for
$this->app->document->addStylesheet("root:administrator/templates/system/css/system.css");
try {
$this->results = $this->app->modification->check();
// display view
$this->getView()->setLayout('modifications')->display();
} catch (AppModificationException $e) {
$this->app->error->raiseNotice(0, $e);
}
}
public function cleanModifications() {
// check for request forgeries
$this->app->session->checkToken() or jexit('Invalid Token');
try {
$this->app->modification->clean();
$msg = JText::_('Unknown files removed.');
} catch (AppModificationException $e) {
$msg = JText::_('Error cleaning ZOO.');
$this->app->error->raiseNotice(0, $e);
}
$route = JRoute::_($this->baseurl.'&task=checkmodifications&tmpl=component', false);
$this->setRedirect($route, $msg);
}
public function verify() {
$result = false;
try {
$result = $this->app->modification->verify();
} catch (AppModificationException $e) {}
echo json_encode(compact('result'));
}
public function doBackup() {
if ($result = $this->app->backup->all()) {
$result = $this->app->backup->generateHeader() . $result;
$size = strlen($result);
while (@ob_end_clean());
header("Pragma: public");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Expires: 0");
header("Content-Transfer-Encoding: binary");
header('Content-Type: application/zip');
header('Content-Disposition: attachment;'
.' filename="zoo-db-backup-'.time().'-'.(md5(implode(',', $this->app->backup->getTables()))).'.sql";'
.' modification-date="'.date('r').'";'
.' size='.$size.';');
header("Content-Length: ".$size);
echo $result;
return;
}
// raise error on exception
$this->app->error->raiseNotice(0, JText::_('Error Creating Backup'));
$this->setRedirect($this->baseurl);
}
public function restoreBackup() {
// check for request forgeries
$this->app->session->checkToken() or jexit('Invalid Token');
// get the uploaded file information
$userfile = $this->app->request->getVar('backupfile', null, 'files', 'array');
try {
$file = $this->app->validator->create('file', array('extension' => array('sql')))->clean($userfile);
$this->app->backup->restore($file['tmp_name']);
$msg = JText::_('Database backup successfully restored');
} catch (AppValidatorException $e) {
$msg = '';
$this->app->error->raiseNotice(0, "Error uploading backup file. ($e) Please upload .sql files only.");
} catch (RuntimeException $e) {
$msg = '';
$this->app->error->raiseNotice(0, JText::sprintf("Error restoring ZOO backup. (%s)", $e->getMessage()));
}
$this->setRedirect($this->baseurl, $msg);
}
public function cleanDB() {
// init vars
$row = 0;
$db = $this->app->database;
if ($apps = $this->app->path->dirs('applications:')) {
$db->query(sprintf("DELETE FROM ".ZOO_TABLE_APPLICATION." WHERE application_group NOT IN ('%s')", implode("', '", $apps)));
}
$db->query("DELETE FROM ".ZOO_TABLE_ITEM." WHERE type = ''");
$row += $db->getAffectedRows();
$db->query("DELETE FROM ".ZOO_TABLE_ITEM." WHERE NOT EXISTS (SELECT id FROM ".ZOO_TABLE_APPLICATION." WHERE id = application_id)");
$row += $db->getAffectedRows();
$db->query("DELETE FROM ".ZOO_TABLE_CATEGORY." WHERE NOT EXISTS (SELECT id FROM ".ZOO_TABLE_APPLICATION." WHERE id = application_id)");
$row += $db->getAffectedRows();
$db->query("DELETE FROM ".ZOO_TABLE_SUBMISSION." WHERE NOT EXISTS (SELECT id FROM ".ZOO_TABLE_APPLICATION." WHERE id = application_id)");
$row += $db->getAffectedRows();
$db->query("DELETE FROM ".ZOO_TABLE_TAG." WHERE NOT EXISTS (SELECT id FROM ".ZOO_TABLE_ITEM." WHERE id = item_id)");
$row += $db->getAffectedRows();
$db->query("DELETE FROM ".ZOO_TABLE_COMMENT." WHERE NOT EXISTS (SELECT id FROM ".ZOO_TABLE_ITEM." WHERE id = item_id)");
$row += $db->getAffectedRows();
$db->query("DELETE FROM ".ZOO_TABLE_RATING." WHERE NOT EXISTS (SELECT id FROM ".ZOO_TABLE_ITEM." WHERE id = item_id)");
$row += $db->getAffectedRows();
$db->query("DELETE FROM ".ZOO_TABLE_SEARCH." WHERE NOT EXISTS (SELECT id FROM ".ZOO_TABLE_ITEM." WHERE id = item_id)");
$row += $db->getAffectedRows();
$db->query("DELETE FROM ".ZOO_TABLE_CATEGORY_ITEM." WHERE category_id != 0 AND (NOT EXISTS (SELECT id FROM ".ZOO_TABLE_ITEM." WHERE id = item_id) OR NOT EXISTS (SELECT id FROM ".ZOO_TABLE_CATEGORY." WHERE id = category_id))");
$row += $db->getAffectedRows();
// sanatize parent references
$db->query("UPDATE ".ZOO_TABLE_CATEGORY." SET parent = 0 WHERE parent != 0 AND NOT EXISTS (SELECT id FROM (SELECT id FROM ".ZOO_TABLE_CATEGORY.") as t WHERE t.id = parent)");
$db->query("UPDATE ".ZOO_TABLE_COMMENT." SET parent_id = 0 WHERE parent_id != 0 AND NOT EXISTS (SELECT id FROM (SELECT id FROM ".ZOO_TABLE_CATEGORY.") as t WHERE t.id = parent_id)");
// get the item table
$table = $this->app->table->item;
try {
$items = $table->all();
foreach ($items as $item) {
try {
$table->save($item);
} catch (Exception $e) {
$this->app->error->raiseNotice(0, JText::sprintf("Error updating search data for item with id %s. (%s)", $item->id, $e));
}
}
$msg = JText::sprintf('Cleaned database (Removed %s entries) and items search data has been updated.', $row);
} catch (Exception $e) {
$msg = '';
$this->app->error->raiseNotice(0, JText::sprintf("Error cleaning database. (%s)", $e));
}
$this->setRedirect($this->baseurl, $msg);
}
public function hideUpdateNotification() {
$this->app->update->hideUpdateNotification();
}
public function disableRouteCaching() {
$this->_toggleRouteCaching(false);
}
public function enableRouteCaching() {
$this->_toggleRouteCaching(true);
}
public function getAlias() {
$name = $this->app->request->getString('name', '');
$force_safe = $this->app->request->getBool('force_safe', false);
echo json_encode($this->app->string->sluggify($name, $force_safe));
}
protected function _toggleRouteCaching($state) {
$this->app->set('cache_routes', $state);
$this->app->component->self->save();
$this->app->route->clearCache();
$this->setRedirect($this->baseurl);
}
}
/*
Class: ManagerControllerException
*/
class ManagerControllerException extends AppException {} | lflayton/centralc | administrator/components/com_zoo/controllers/manager.php | PHP | gpl-2.0 | 29,008 |
/////////////////////////////////////////////////////////////////////////////
// Name: ExifHandler.cpp
// Purpose: ExifHandler class
// Author: Alex Thuering
// Created: 30.12.2007
// RCS-ID: $Id: ExifHandler.cpp,v 1.1 2007/12/30 22:45:02 ntalex Exp $
// Copyright: (c) Alex Thuering
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#include "ExifHandler.h"
#include <libexif/exif-loader.h>
int ExifHandler::getOrient(wxString filename) {
ExifData* exifData = exif_data_new_from_file(filename.mb_str());
if (!exifData)
return -1;
if (!exif_content_get_entry(exifData->ifd[EXIF_IFD_EXIF], EXIF_TAG_EXIF_VERSION))
return -1;
gint orient = -1;
ExifEntry* entry = exif_content_get_entry(exifData->ifd[EXIF_IFD_0], EXIF_TAG_ORIENTATION);
if (entry) {
ExifByteOrder byteOrder = exif_data_get_byte_order(exifData);
orient = exif_get_short(entry->data, byteOrder);
}
exif_data_unref(exifData);
return (int) orient;
}
| rpeyron/rphoto | lib/wxVillaLib/ExifHandler.cpp | C++ | gpl-2.0 | 1,015 |
/*
* Renjin : JVM-based interpreter for the R language for the statistical analysis
* Copyright © 2010-2019 BeDataDriven Groep B.V. and contributors
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, a copy is available at
* https://www.gnu.org/licenses/gpl-2.0.txt
*/
package org.renjin.compiler.ir.tac.functions;
import org.renjin.compiler.ir.tac.IRBodyBuilder;
import org.renjin.compiler.ir.tac.expressions.Expression;
import org.renjin.compiler.ir.tac.expressions.NestedFunction;
import org.renjin.eval.EvalException;
import org.renjin.sexp.FunctionCall;
import org.renjin.sexp.PairList;
import org.renjin.sexp.SEXP;
/**
* Translator for the {@code function} function.
*/
public class ClosureDefinitionTranslator extends FunctionCallTranslator {
@Override
public Expression translateToExpression(IRBodyBuilder builder,
TranslationContext context, FunctionCall call) {
PairList formals = EvalException.checkedCast(call.getArgument(0));
SEXP body = call.getArgument(1);
SEXP source = call.getArgument(2);
return new NestedFunction(formals, body);
}
@Override
public void addStatement(IRBodyBuilder builder, TranslationContext context,
FunctionCall call) {
// a closure whose value is not used has no side effects
// E.g.
// function(x) x*2
// has no effect.
}
}
| bedatadriven/renjin | core/src/main/java/org/renjin/compiler/ir/tac/functions/ClosureDefinitionTranslator.java | Java | gpl-2.0 | 1,957 |
/*
* Copyright (c) 1998-2008 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Resin Open Source is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Nam Nguyen
*/
package com.caucho.quercus.lib.gettext.expr;
public class MulExpr extends BinaryExpr
{
public MulExpr(Expr _left, Expr _right)
{
super(_left, _right);
}
public int eval(int n)
{
return _left.eval(n) * _right.eval(n);
}
}
| moriyoshi/quercus-gae | src/main/java/com/caucho/quercus/lib/gettext/expr/MulExpr.java | Java | gpl-2.0 | 1,273 |
<?php
/*
* Configuration
*/
$dirname = dirname(__FILE__).'/../traductions/';
$main_lg = 'fr_FR';
$menu->current('main/params/clean');
$titre_page = $dico->t('NettoyerDoublonsSku');
$ref = $url->get("id");
if ($ref > 0) {
/*
* On met à jour les ref des SKU
*/
if ($_POST['refsku'] == "ok") {
$q = "UPDATE dt_sku SET ref_ultralog =".$_POST['ref']." WHERE id =".$_POST['sku'];
$sql->query($q);
}
/*
* On affiche les détails des SKU
*/
$q1 = "SELECT s.id, s.actif, ph.phrase
FROM dt_sku AS s
INNER JOIN dt_phrases AS ph
ON s.phrase_ultralog = ph.id
AND s.ref_ultralog = ".$ref;
$rs1 = $sql->query($q1);
$main = '<p>'.$page->l($dico->t('Retour'), $url->make("CleanSku")).'</p>';
$main .= '<p>'.$dico->t('Reference').' : '.$ref.'</p>';
$main .= '<form name="doublons" action="'.$url->make("CleanSku").'" method="post">';
$main .= '<table border="1">';
while ($row1 = $sql->fetch($rs1)) {
$main .= '<tr>';
$nom_statut = "inactif";
if ($row1['actif'] == 1) {
$nom_statut = "actif";
}
$main .= '<td>'.$row1['id'].'</td>';
$main .= '<td>'.$row1['phrase'].'</td>';
$main .= '<td>'.$nom_statut.'</td>';
$q2 = "SELECT id_produits FROM dt_sku_variantes WHERE id_sku = ".$row1['id'];
$rs2 = $sql->query($q2);
if (mysql_num_rows($rs2) > 0) {
$row2 = $sql->fetch($rs2);
$q3 = "SELECT p.id, p.actif, ph.phrase
FROM dt_produits AS p
INNER JOIN dt_phrases AS ph
ON ph.id = p.phrase_nom
AND p.id = ".$row2['id_produits'];
$rs3 = $sql->query($q3);
$row3 = $sql->fetch($rs3);
$nom_statutb = "inactif";
if ($row3['actif'] == 1) {
$nom_statutb = "actif";
}
$main .= '<td>'.$row3['id'].'</td>';
$main .= '<td>'.$row3['phrase'].'</td>';
$main .= '<td>'.$nom_statutb.'</td>';
}
else {
$main .= '<td> - </td><td> - </td><td> - </td>';
}
$main .= '<td><input type="checkbox" name="idsku[]" value="'.$row1['id'].'" /></td>';
$main .= '</tr>';
}
$main .= '</table>';
$main .= '<input type="hidden" name="sku" value="ok" />';
$main .= '<input type="submit" name="valider" value="'.$dico->t('Envoyer').'" />';
$main .= '</form>';
$main .= '<form name="updsku" action="#" method="post">';
$main .= '<fieldset><legend>'.$dico->t('MettreJourRefSku').'</legend>';
$main .= '<p><label for="sku">SKU = <input type="text" name="sku" value="" /></label></p>';
$main .= '<p><label for="ref">REF = <input type="text" name="ref" value="" /></label></p>';
$main .= '<input type="hidden" name="refsku" value="ok" />';
$main .= '<p><input type="submit" name="envoyer" value="'.$dico->t('Envoyer').'" /></p>';
$main .= '</fieldset></form>';
}
else {
/*
* On supprime les sku doublons
*/
if ($_POST['sku'] == "ok") {
foreach($_POST['idsku'] as $key => $id) {
$q = "DELETE FROM dt_sku WHERE id = ".$id;
$q1 = "DELETE FROM dt_sku_accessoires WHERE id_sku = ".$id;
$q2 = "DELETE FROM dt_sku_attributs WHERE id_sku = ".$id;
$q3 = "DELETE FROM dt_sku_composants WHERE id_sku = ".$id;
$q4 = "DELETE FROM dt_sku_variantes WHERE id_sku = ".$id;
$q5 = "DELETE FROM dt_images_sku WHERE id_sku = ".$id;
$q6 = "DELETE FROM dt_prix WHERE id_sku = ".$id;
$q7 = "DELETE FROM dt_prix_degressifs WHERE id_sku = ".$id;
$sql->query($q);
$sql->query($q1);
$sql->query($q2);
$sql->query($q3);
$sql->query($q4);
$sql->query($q5);
$sql->query($q6);
$sql->query($q7);
}
}
/*
* On récupère tous les doublons (champ ref_ultralog).
*/
$q = "SELECT id, ref_ultralog FROM dt_sku ORDER BY ref_ultralog";
$rs = $sql->query($q);
$doublons = array();
$prev = 0;
while($row = $sql->fetch($rs)) {
if ($prev == $row['ref_ultralog'] AND $prev > 0) {
$doublons[] = $row['ref_ultralog'];
}
$prev = $row['ref_ultralog'];
}
$doublons_bis = array_unique($doublons);
/*
* Affichage
*/
$main = '<p>'.count($doublons_bis).' '.$dico->t('ItemsDoublons').'</p>';
$main .= '<ul id="liste_sku">';
foreach($doublons_bis as $id => $ref) {
$link_ref = $url->make("CleanSku", array("action" => "edit", "id" => $ref ));
$main .= '<li><a href="'.$link_ref.'">REF = '.$ref.'</li>';
}
$main .= '</ul>';
}
?> | noparking/alticcio | admin/pages/601_cleansku.php | PHP | gpl-2.0 | 4,152 |
<?php
/* Copyright (C) 2011-2015 Emmanuel DEROME - All rights reserved */
// Prevents any direct access
defined('_JEXEC') or die();
// echo "<h1>\n";
// echo JText::_('COM_EGS_ENTREPRISE');
// echo "</h1>\n";
?>
<form action="index.php" method="post" name="adminForm" id="adminForm">
<?php
$user = JFactory::getUser(); // gets current user object
$isEntreprise = (array_search('11', $user->groups)); // sets flag when user group is '11' that is 'EGS Entreprise'
$isProf = (array_search('9', $user->groups)); // sets flag when user group is '9' that is 'EGS Professeur'
echo $this->getToolbar($isEntreprise, $isProf);
echo "<div class='pagetitle icon-48-article'><h2>\n";
echo JText::_('COM_EGS_ENTREPRISE') . " : " . $this->entreprise->nom;
echo "</h2></div>\n";
?>
<div>
<fieldset class="adminform">
<table class="admintable">
<tr>
<td width="110" class="key">
<label for="nom">
<?php echo JText::_('COM_EGS_ENTREPRISES_NOM'); ?>:
</label>
</td>
<td>
<?php if ($isEntreprise) {
?> <input class="inputbox" type="text" name="nom" id="nom" size="60" value="<?php echo $this->entreprise->nom; ?>" />
<?php } else {
?> <input type="hidden" name="nom" value="<?php echo $this->entreprise->nom; ?>" /> <?php
echo $this->entreprise->nom;
} ?>
</td>
</tr>
<tr>
<td width="110" class="key">
<label for="logo">
<?php echo JText::_('COM_EGS_ENTREPRISES_LOGO'); ?>:
</label>
</td>
<td>
<?php echo "<img src='" . JURI::root() . "images/logos/" . $this->entreprise->logo . "' border='0' />"; ?>
<?php if ($isEntreprise) {
?> <input class="inputbox" type="text" name="logo" id="logo" size="60" value="<?php echo $this->entreprise->logo; ?>" /> <?php
} ?>
</td>
</tr>
<tr>
<td width="110" class="key">
<label for="activite">
<?php echo JText::_('COM_EGS_ENTREPRISES_ACTIVITE'); ?>:
</label>
</td>
<td>
<?php if ($isEntreprise) {
?> <textarea class="inputbox" type="text" name="activite" id="activite" cols='60' rows='4'><?php echo $this->entreprise->activite; ?></textarea>
<?php } else {
?> <input type="hidden" name="activite" value="<?php echo $this->entreprise->activite; ?>" /> <?php
echo $this->entreprise->activite;
} ?>
</td>
</tr>
<tr>
<td width="110" class="key">
<label for="siteWeb">
<?php echo JText::_('COM_EGS_ENTREPRISES_SITEWEB'); ?>:
</label>
</td>
<td>
<?php if ($isEntreprise) {
?> <input class="inputbox" type="text" name="siteWeb" id="siteWeb" size="60" value="<?php echo $this->entreprise->siteWeb; ?>" />
<?php } else {
?> <input type="hidden" name="siteWeb" value="<?php echo $this->entreprise->siteWeb; ?>" /> <?php
echo $this->entreprise->siteWeb;
} ?>
</td>
</tr>
<tr>
<td width="110" class="key">
<label for="adrRue">
<?php echo JText::_('COM_EGS_ENTREPRISES_ADR_RUE'); ?>:
</label>
</td>
<td>
<?php if ($isEntreprise) {
?> <input class="inputbox" type="text" name="adrRue" id="adrRue" size="60" value="<?php echo $this->entreprise->adrRue; ?>" />
<?php } else {
?> <input type="hidden" name="adrRue" value="<?php echo $this->entreprise->adrRue; ?>" /> <?php
echo $this->entreprise->adrRue;
} ?>
</td>
</tr>
<tr>
<td width="110" class="key">
<label for="adrVille">
<?php echo JText::_('COM_EGS_ENTREPRISES_ADR_VILLE'); ?>:
</label>
</td>
<td>
<?php if ($isEntreprise) {
?> <input class="inputbox" type="text" name="adrVille" id="adrVille" size="60" value="<?php echo $this->entreprise->adrVille; ?>" />
<?php } else {
?> <input type="hidden" name="adrVille" value="<?php echo $this->entreprise->adrVille; ?>" /> <?php
echo $this->entreprise->adrVille;
} ?>
</td>
</tr>
<tr>
<td width="110" class="key">
<label for="adrCP">
<?php echo JText::_('COM_EGS_ENTREPRISES_ADR_CP'); ?>:
</label>
</td>
<td>
<?php if ($isEntreprise) {
?> <input class="inputbox" type="text" name="adrCP" id="adrCP" size="60" value="<?php echo $this->entreprise->adrCP; ?>" />
<?php } else {
?> <input type="hidden" name="adrCP" value="<?php echo $this->entreprise->adrCP; ?>" /> <?php
echo $this->entreprise->adrCP;
} ?>
</td>
</tr>
<tr>
<td width="110" class="key">
<label for="pays_id">
<?php echo JText::_('COM_EGS_ENTREPRISES_ADR_PAYS'); ?>:
</label>
</td>
<td>
<?php if ($isEntreprise) {
?> <select class="inputbox" name="pays_id" id="pays_id"> <?php
$db =& JFactory::getDBO();
$query2 = 'SELECT * FROM #__egs_pays ORDER BY pays';
$db->setQuery($query2);
$rows2 = $db->loadObjectList();
foreach ($rows2 as $row2) {
if ($this->entreprise->pays_id == $row2->id){
echo "<option value='$row2->id' selected='selected'>$row2->pays</option>\n";
}else{
echo "<option value='$row2->id'>$row2->pays</option>\n";
}
}
?> </select> <?php
} else {
?> <input type="hidden" name="pays_id" value="<?php echo $this->entreprise->pays_id; ?>" /> <?php
$db = JFactory::getDBO();
$query2 = 'SELECT * FROM #__egs_pays WHERE id = ' . $this->entreprise->pays_id;
$db->setQuery($query2);
$row2 = $db->loadObject();
if ($row2) {echo $row2->pays;}
} ?>
</td>
</tr>
</table>
</fieldset>
</div>
<div class="clr"></div>
<div class="clr"></div>
<input type="hidden" name="option" value="com_egs" />
<input type="hidden" name="id" value="<?php echo $this->entreprise->id; ?>" />
<input type="hidden" name="task" value="" />
<input type="hidden" name="controller" value="entreprises" />
</form>
| Mohsan1995/egs.com | components/com_egs/views/entreprise/tmpl/form.php | PHP | gpl-2.0 | 6,237 |
//Auto generated file
//Do not edit this file
package org.sisiya.ui.standart;
import org.sql2o.Connection;
import org.sql2o.Query;
import java.util.List;
import org.sisiya.ui.Application;
import java.util.Date;
public class System_service_alert extends Model{
//Fields
protected int id;
protected int user_id;
protected int system_id;
protected int service_id;
protected int alert_type_id;
protected int status_id;
protected int frequency;
protected boolean enabled;
protected Date last_alert_time;
private ModelHooks mh;
private Boolean isNew;
//Constructer
public System_service_alert(){
isNew = true;
//Default Constructer
fields.add(new Field("id","int","system_service_alert-id",true,true));
fields.add(new Field("user_id","int","system_service_alert-user_id",false,false));
fields.add(new Field("system_id","int","system_service_alert-system_id",false,false));
fields.add(new Field("service_id","int","system_service_alert-service_id",false,false));
fields.add(new Field("alert_type_id","int","system_service_alert-alert_type_id",false,false));
fields.add(new Field("status_id","int","system_service_alert-status_id",false,false));
fields.add(new Field("frequency","int","system_service_alert-frequency",false,false));
fields.add(new Field("enabled","boolean","system_service_alert-enabled",false,false));
fields.add(new Field("last_alert_time","Date","system_service_alert-last_alert_time",false,false));
}
public void registerHooks(ModelHooks _mh){
mh = _mh;
}
//Setters
public void setId(int _id){
id = _id;
}
public void setUser_id(int _user_id){
user_id = _user_id;
}
public void setSystem_id(int _system_id){
system_id = _system_id;
}
public void setService_id(int _service_id){
service_id = _service_id;
}
public void setAlert_type_id(int _alert_type_id){
alert_type_id = _alert_type_id;
}
public void setStatus_id(int _status_id){
status_id = _status_id;
}
public void setFrequency(int _frequency){
frequency = _frequency;
}
public void setEnabled(boolean _enabled){
enabled = _enabled;
}
public void setLast_alert_time(Date _last_alert_time){
last_alert_time = _last_alert_time;
}
public void setIsNew(boolean b){
isNew = b;
}
//Getters
public int getId(){
return id;
}
public int getUser_id(){
return user_id;
}
public int getSystem_id(){
return system_id;
}
public int getService_id(){
return service_id;
}
public int getAlert_type_id(){
return alert_type_id;
}
public int getStatus_id(){
return status_id;
}
public int getFrequency(){
return frequency;
}
public boolean getEnabled(){
return enabled;
}
public Date getLast_alert_time(){
return last_alert_time;
}
public Boolean isNew() {
return isNew;
}
//Data Access Methods
//Data Access Methods
public boolean save(Connection _connection){
return(save(_connection,true,true));
}
public boolean save(Connection _connection,boolean doValidate,boolean executeHooks){
if(doValidate){
try {
if(!mh.validate(_connection)){
return(false);
}
} catch (Exception e) {
errors.add(new Error(e.getClass().getName(), e.getMessage()));
return(false);
}
if(!isReadyToSave()){
return(false);
}
}
if(executeHooks){
try {
if(isNew()){
if(!mh.beforeInsert(_connection)){return(false);}
}else{
if(!mh.beforeUpdate(_connection)){return(false);}
}
if(!mh.beforeSave(_connection)){return(false);}
} catch (Exception e) {
errors.add(new Error(e.getClass().getName(), e.getMessage()));
return(false);
}
//Actual db update
if(isNew()){
try {
if(!insert(_connection)){return(false);}
if(!mh.afterInsert(_connection)){return(false);}
if(!mh.afterSave(_connection)){return(false);}
} catch (Exception e) {
errors.add(new Error(e.getClass().getName(), e.getMessage()));
return(false);
}
}else{
try {
if(!update(_connection)){return(false);}
if(!mh.afterUpdate(_connection)){return(false);}
if(!mh.afterSave(_connection)){return(false);}
} catch (Exception e) {
errors.add(new Error(e.getClass().getName(), e.getMessage()));
return(false);
}
}
}else{
//Actual db operation without hooks
if(isNew()){
try {
if(!insert(_connection)){return(false);}
} catch (Exception e) {
errors.add(new Error(e.getClass().getName(), e.getMessage()));
return(false);
}
}else{
try {
if(!update(_connection)){return(false);}
} catch (Exception e) {
errors.add(new Error(e.getClass().getName(), e.getMessage()));
return(false);
}
}
}
return true;
}
public boolean destroy(Connection _connection,boolean executeHooks){
if(executeHooks){
if(!mh.beforeDestroy(_connection)){return(false);}
}
if(!delete(_connection)){return(false);}
if(executeHooks){
if(!mh.afterDestroy(_connection)){return(false);}
}
return(true);
}
public boolean destroy(Connection _connection){
return(destroy(_connection,true));
}
//Private Data Acess utility Methods
private boolean insert(Connection _connection){
Query query;
query = _connection.createQuery(insertSql(),true);
query = query.addParameter("user_idP",user_id);
query = query.addParameter("system_idP",system_id);
query = query.addParameter("service_idP",service_id);
query = query.addParameter("alert_type_idP",alert_type_id);
query = query.addParameter("status_idP",status_id);
query = query.addParameter("frequencyP",frequency);
query = query.addParameter("enabledP",enabled);
query = query.addParameter("last_alert_timeP",last_alert_time);
id = (int) query.executeUpdate().getKey();
return(true);
}
private boolean update(Connection _connection){
Query query;
query = _connection.createQuery(updateSql());
query = query.addParameter("idP",id);
query = query.addParameter("user_idP",user_id);
query = query.addParameter("system_idP",system_id);
query = query.addParameter("service_idP",service_id);
query = query.addParameter("alert_type_idP",alert_type_id);
query = query.addParameter("status_idP",status_id);
query = query.addParameter("frequencyP",frequency);
query = query.addParameter("enabledP",enabled);
query = query.addParameter("last_alert_timeP",last_alert_time);
query.executeUpdate();
return(true);
}
private boolean delete(Connection _connection){
Query query;
query = _connection.createQuery(deleteSql());
query.addParameter("idP",id);
query.executeUpdate();
return(true);
}
private String insertSql(){
String querySql = "insert into system_service_alerts( ";
querySql += "user_id,";
querySql += "system_id,";
querySql += "service_id,";
querySql += "alert_type_id,";
querySql += "status_id,";
querySql += "frequency,";
querySql += "enabled,";
querySql += "last_alert_time)";
querySql += "values (";
querySql += ":user_idP,";
querySql += ":system_idP,";
querySql += ":service_idP,";
querySql += ":alert_type_idP,";
querySql += ":status_idP,";
querySql += ":frequencyP,";
querySql += ":enabledP,";
querySql += ":last_alert_timeP)";
return querySql;
}
private String updateSql(){
String querySql = "update system_service_alerts set ";
querySql += "user_id = :user_idP, " ;
querySql += "system_id = :system_idP, " ;
querySql += "service_id = :service_idP, " ;
querySql += "alert_type_id = :alert_type_idP, " ;
querySql += "status_id = :status_idP, " ;
querySql += "frequency = :frequencyP, " ;
querySql += "enabled = :enabledP, " ;
querySql += "last_alert_time = :last_alert_timeP ";
querySql += " where id = :idP";
return querySql;
}
private String deleteSql(){
String querySql = "delete from system_service_alerts where id = :idP";
return querySql;
}
}
| erdalmutlu1/sisiya2 | ui/web/src/main/java/org/sisiya/ui/standart/System_service_alert.java | Java | gpl-2.0 | 8,129 |
package owuor.f8th.adapters;
import java.util.List;
import owuor.f8th.R;
import owuor.f8th.ContentProvider.F8thContentProvider;
import owuor.f8th.database.NotificationsTable;
import owuor.f8th.types.F8th;
import owuor.f8th.types.Notification;
import android.content.Context;
import android.graphics.Color;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class NotificationAdapter extends ArrayAdapter<Notification> {
private LayoutInflater layoutInflater;
private Context context;
public NotificationAdapter(Context context) {
super(context, android.R.layout.simple_list_item_2);
this.context = context;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}// end of constructor
public void setNotifyList(List<Notification> data) {
clear();
if (data != null) {
for (Notification appEntry : data) {
add(appEntry);
}
notifyDataSetChanged();
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_profile_notify_row, null);
holder = new ViewHolder();
holder.photoView = (ImageView)convertView.findViewById(R.id.imgSender);
holder.delete = (ImageView)convertView.findViewById(R.id.imgDeleteNotify);
holder.sender = (TextView) convertView.findViewById(R.id.txtFrom);
holder.message = (TextView) convertView.findViewById(R.id.txtMessage);
holder.date = (TextView) convertView.findViewById(R.id.txtDate);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final Notification notification = getItem(position);
if(notification.getStatus().equalsIgnoreCase(F8th.NOTIFY_UNREAD)){
holder.sender.setTextColor(Color.RED);
}
holder.sender.setText(notification.getSender());
holder.message.setText(notification.getMessage());
holder.date.setText(notification.getDateSent());
holder.delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Uri uri = Uri.parse(F8thContentProvider.CONTENT_URI + "/" + NotificationsTable.TABLE_NOTIFY);
String selection = NotificationsTable.COLUMN_NOTIFY_ID + "='" + notification.getNotifyId() + "'";
context.getContentResolver().delete(uri, selection, null);
NotificationAdapter.this.remove(notification);
notifyDataSetChanged();
}
});
return convertView;
}// end of method getView()
static class ViewHolder {
ImageView photoView,delete;
TextView sender, message, date;
}
}// END OF CLASS NotificationAdapter | owuorJnr/f8th | src/owuor/f8th/adapters/NotificationAdapter.java | Java | gpl-2.0 | 2,832 |
/*********************************************************************/
// dar - disk archive - a backup/restoration program
// Copyright (C) 2002-2022 Denis Corbin
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// to contact the author, see the AUTHOR file
/*********************************************************************/
#include "../my_config.h"
extern "C"
{
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
} // end extern "C"
#include "tools.hpp"
#include "erreurs.hpp"
#include "fichier_libcurl.hpp"
using namespace std;
namespace libdar
{
#if defined ( LIBCURL_AVAILABLE ) && defined ( LIBTHREADAR_AVAILABLE )
fichier_libcurl::fichier_libcurl(const shared_ptr<user_interaction> & dialog,
const std::string & chemin,
mycurl_protocol proto,
const shared_ptr<mycurl_easyhandle_node> & handle,
gf_mode m,
U_I waiting,
bool force_permission,
U_I permission,
bool erase): fichier_global(dialog, m),
end_data_mode(false),
sub_is_dying(false),
ehandle(handle),
metadatamode(false),
current_offset(0),
has_maxpos(false),
maxpos(0),
append_write(!erase),
meta_inbuf(0),
wait_delay(waiting),
interthread(10, tampon_size),
synchronize(2),
x_proto(proto)
{
try
{
if(!ehandle)
throw SRC_BUG;
// setting x_ref_handle to carry all options that will always be present for this object
ehandle->setopt(CURLOPT_URL, chemin);
switch(get_mode())
{
case gf_read_only:
ehandle->setopt(CURLOPT_WRITEDATA, (void *)this);
break;
case gf_write_only:
ehandle->setopt(CURLOPT_READDATA, (void *)this);
ehandle->setopt(CURLOPT_UPLOAD, 1L);
break;
case gf_read_write:
throw Efeature("read-write mode for fichier libcurl");
default:
throw SRC_BUG;
}
switch_to_metadata(true);
if(append_write && m != gf_read_only)
current_offset = get_size();
}
catch(...)
{
detruit();
throw;
}
}
void fichier_libcurl::change_permission(U_I perm)
{
struct mycurl_slist headers;
string order = tools_printf("site CHMOD %o", perm);
switch_to_metadata(true);
try
{
headers.append(order);
ehandle->setopt(CURLOPT_QUOTE, headers);
ehandle->setopt(CURLOPT_NOBODY, (long)1);
try
{
ehandle->apply(get_pointer(), wait_delay);
}
catch(...)
{
ehandle->setopt_default(CURLOPT_QUOTE);
ehandle->setopt_default(CURLOPT_NOBODY);
throw;
}
ehandle->setopt_default(CURLOPT_QUOTE);
ehandle->setopt_default(CURLOPT_NOBODY);
}
catch(Egeneric & e)
{
e.prepend_message("Error while changing file permission on remote repository");
throw;
}
}
infinint fichier_libcurl::get_size() const
{
double filesize;
fichier_libcurl *me = const_cast<fichier_libcurl *>(this);
if(me == nullptr)
throw SRC_BUG;
if(!has_maxpos || get_mode() != gf_read_only)
{
try
{
me->switch_to_metadata(true);
me->ehandle->setopt(CURLOPT_NOBODY, (long)1);
try
{
me->ehandle->apply(get_pointer(), wait_delay);
me->ehandle->getinfo(CURLINFO_CONTENT_LENGTH_DOWNLOAD, &filesize);
if(filesize == -1) // file does not exist (or filesize is not known)
filesize = 0;
me->maxpos = tools_double2infinint(filesize);
me->has_maxpos = true;
}
catch(...)
{
me->ehandle->setopt_default(CURLOPT_NOBODY);
throw;
}
me->ehandle->setopt_default(CURLOPT_NOBODY);
}
catch(Egeneric & e)
{
e.prepend_message("Error while reading file size on a remote repository");
throw;
}
}
return maxpos;
}
bool fichier_libcurl::skippable(skippability direction, const infinint & amount)
{
if(get_mode() == gf_read_only)
{
switch(direction)
{
case skip_backward:
return amount <= current_offset;
case skip_forward:
if(!has_maxpos)
(void)get_size();
if(!has_maxpos)
throw SRC_BUG;
return current_offset + amount < maxpos;
default:
throw SRC_BUG;
}
}
else
return false;
}
bool fichier_libcurl::skip(const infinint & pos)
{
if(pos == current_offset)
return true;
switch(get_mode())
{
case gf_read_only:
switch_to_metadata(true); // necessary to stop current subthread and change easy_handle offset
current_offset = pos;
flush_read();
break;
case gf_write_only:
throw Erange("fichier_libcurl::skip", string(gettext("libcurl does not allow skipping in write mode")));
case gf_read_write:
throw SRC_BUG;
default:
throw SRC_BUG;
}
return true;
}
bool fichier_libcurl::skip_to_eof()
{
(void)get_size();
if(!has_maxpos)
throw SRC_BUG; // get_size() sould either throw an exception or set maxpos
if(get_mode() == gf_write_only)
return true;
else
return skip(maxpos);
}
bool fichier_libcurl::skip_relative(S_I x)
{
if(x >= 0)
{
infinint tmp(x);
tmp += current_offset;
return skip(tmp);
}
else
{
infinint tmp(-x);
if(tmp > current_offset)
{
skip(0);
return false;
}
else
{
tmp = current_offset - tmp;
return skip(tmp);
}
}
}
void fichier_libcurl::inherited_read_ahead(const infinint & amount)
{
relaunch_thread(amount);
}
void fichier_libcurl::inherited_truncate(const infinint & pos)
{
if(pos != get_position())
throw Erange("fichier_libcurl::inherited_truncate", string(gettext("libcurl does not allow truncating at a given position while uploading files")));
}
void fichier_libcurl::inherited_sync_write()
{
// nothing to do because there is no data in transit
// except in interthread but it cannot be flushed faster
// than the normal multi-thread process does
}
void fichier_libcurl::inherited_flush_read()
{
switch_to_metadata(true);
interthread.reset();
}
void fichier_libcurl::inherited_terminate()
{
switch(get_mode())
{
case gf_write_only:
switch_to_metadata(true);
break;
case gf_read_only:
switch_to_metadata(true);
break;
case gf_read_write:
throw SRC_BUG;
default:
throw SRC_BUG;
}
}
U_I fichier_libcurl::fichier_global_inherited_write(const char *a, U_I size)
{
U_I wrote = 0;
bool full = false;
char *ptr;
unsigned int ptr_size;
switch_to_metadata(false);
while(wrote < size && !full)
{
try
{
if(!is_running() || sub_is_dying)
{
join();
throw SRC_BUG;
// inherited_run() should throw an exception
// as this is not a normal condition:
// we have not yet finished writing
// data and child thread has already ended
}
}
catch(Edata & e)
{
// remote disk is full
full = true;
}
if(!full)
{
U_I toadd = size - wrote;
interthread.get_block_to_feed(ptr, ptr_size);
if(toadd <= ptr_size)
{
memcpy(ptr, a + wrote, toadd);
interthread.feed(ptr, toadd);
wrote = size;
}
else
{
memcpy(ptr, a + wrote, ptr_size);
interthread.feed(ptr, ptr_size);
wrote += ptr_size;
}
}
}
current_offset += wrote;
if(current_offset > 0)
append_write = true; // we can now ignore the request to erase data
// and we now need to swap in write append mode
return wrote;
}
bool fichier_libcurl::fichier_global_inherited_read(char *a, U_I size, U_I & read, std::string & message)
{
char *ptr;
unsigned int ptr_size;
U_I room;
U_I delta;
bool maybe_eof = false;
set_subthread(size);
read = 0;
do
{
delta = 0;
while(read + delta < size && (!sub_is_dying || interthread.is_not_empty()))
{
interthread.fetch(ptr, ptr_size);
room = size - read - delta;
if(room >= ptr_size)
{
memcpy(a + read + delta, ptr, ptr_size);
interthread.fetch_recycle(ptr);
delta += ptr_size;
}
else
{
memcpy(a + read + delta, ptr, room);
delta += room;
ptr_size -= room;
memmove(ptr, ptr + room, ptr_size);
interthread.fetch_push_back(ptr, ptr_size);
}
}
current_offset += delta;
read += delta;
if(read < size // we requested more data than what we got so far
&& (!has_maxpos // we don't know where is EOF
|| current_offset < maxpos) // or we have not yet reached EOF
&& !maybe_eof) // avoid looping endelessly
{
maybe_eof = (delta == 0);
U_I remaining = size - read;
// if interthread is empty and thread has not been launched at least once
// we can only now switch to data mode because current_offset is now correct.
// This will (re-)launch the thread that should fill interthread pipe with data
set_subthread(remaining);
size = read + remaining;
}
}
while(read < size && (is_running() || interthread.is_not_empty()));
return true;
}
void fichier_libcurl::inherited_run()
{
try
{
// parent thread is still suspended
shared_ptr<user_interaction> thread_ui = get_pointer();
infinint local_network_block = network_block; // set before unlocking parent thread
try
{
if(!thread_ui)
throw Ememory("fichier_libcurl::inherited_run");
subthread_cur_offset = current_offset;
}
catch(...)
{
initialize_subthread();
throw;
}
// after next call, the parent thread will be running
initialize_subthread();
if(local_network_block.is_zero()) // network_block may be non null only in read-only mode
{
do
{
ehandle->apply(thread_ui, wait_delay, end_data_mode);
}
while(!end_data_mode || still_data_to_write());
}
else // reading by block to avoid having interrupting libcurl
{
do
{
subthread_net_offset = 0; // keeps trace of the amount of bytes sent to main thread by callback
set_range(subthread_cur_offset, local_network_block);
try
{
ehandle->apply(thread_ui, wait_delay);
subthread_cur_offset += subthread_net_offset;
if(local_network_block < subthread_net_offset)
throw SRC_BUG; // we acquired more data from libcurl than expected!
local_network_block -= subthread_net_offset;
}
catch(...)
{
unset_range();
throw;
}
unset_range();
}
while(!subthread_net_offset.is_zero() // we just grabbed some data in this ending cycle (not reached eof)
&& !end_data_mode // the current thread has not been asked to stop
&& !local_network_block.is_zero()); // whe still not have gathered all the requested data
}
}
catch(...)
{
finalize_subthread();
throw;
}
finalize_subthread();
}
void fichier_libcurl::initialize_subthread()
{
sub_is_dying = false;
synchronize.wait(); // release calling thread as we, as child thread, do now exist
}
void fichier_libcurl::finalize_subthread()
{
sub_is_dying = true;
if(!end_data_mode) // natural death, main thread has not required our death
{
char *ptr;
unsigned int ptr_size;
switch(get_mode())
{
case gf_write_only:
// making room in the pile to toggle main thread if
// it was suspended waiting for a block to feed
interthread.fetch(ptr, ptr_size);
interthread.fetch_recycle(ptr);
break;
case gf_read_only:
// sending a zero length block to toggle main thread
// if it was suspended waiting for a block to fetch
interthread.get_block_to_feed(ptr, ptr_size);
interthread.feed(ptr, 0); // means eof to main thread
break;
case gf_read_write:
throw SRC_BUG;
default:
throw SRC_BUG;
}
}
}
void fichier_libcurl::set_range(const infinint & begin, const infinint & range_size)
{
infinint end_range = begin + range_size - 1;
string range = tools_printf("%i-%i", &begin, &end_range);
// setting the block size if necessary
ehandle->setopt(CURLOPT_RANGE, range);
}
void fichier_libcurl::unset_range()
{
ehandle->setopt_default(CURLOPT_RANGE);
}
void fichier_libcurl::switch_to_metadata(bool mode)
{
if(mode == metadatamode)
return;
if(!mode) // data mode
{
infinint resume;
curl_off_t cur_pos = 0;
long do_append;
switch(get_mode())
{
case gf_read_only:
ehandle->setopt(CURLOPT_WRITEFUNCTION, (void*)write_data_callback);
if(network_block.is_zero())
{
// setting the offset of the next byte to read / write
resume = current_offset;
resume.unstack(cur_pos);
if(!resume.is_zero())
throw Erange("fichier_libcurl::switch_to_metadata",
gettext("Integer too large for libcurl, cannot skip at the requested offset in the remote repository"));
ehandle->setopt(CURLOPT_RESUME_FROM_LARGE, cur_pos);
}
// else (network_block != 0) the subthread will make use of range
// this parameter is set back to its default in stop_thread()
break;
case gf_write_only:
ehandle->setopt(CURLOPT_READFUNCTION, (void*)read_data_callback);
// setting the offset of the next byte to read / write
do_append = (append_write ? 1 : 0);
ehandle->setopt(CURLOPT_APPEND, do_append);
// should also set the CURLOPT_INFILESIZE_LARGE option but file size is not known at this time
break;
case gf_read_write:
throw SRC_BUG;
default:
throw SRC_BUG;
}
run_thread();
}
else // metadata mode
{
stop_thread();
meta_inbuf = 0; // we don't care existing metadata remaining in transfer
switch(get_mode())
{
case gf_read_only:
ehandle->setopt(CURLOPT_WRITEFUNCTION, (void*)write_meta_callback);
break;
case gf_write_only:
ehandle->setopt(CURLOPT_READFUNCTION, (void*)read_meta_callback);
break;
case gf_read_write:
throw SRC_BUG;
default:
throw SRC_BUG;
}
}
metadatamode = mode;
}
void fichier_libcurl::detruit()
{
try
{
terminate();
}
catch(...)
{
// ignore all errors
}
}
void fichier_libcurl::run_thread()
{
if(is_running())
throw SRC_BUG;
if(interthread.is_not_empty())
{
char *ptr;
unsigned int ptr_size;
bool bug = false;
// the interthread may keep
// a single empty block pending
// to be fetched.
interthread.fetch(ptr, ptr_size);
if(ptr_size != 0)
bug = true;
interthread.fetch_recycle(ptr);
if(bug)
throw SRC_BUG;
// now interthread should be empty
if(interthread.is_not_empty())
bug = true;
if(bug)
throw SRC_BUG;
// interthread should have been purged when
// previous thread had ended
}
end_data_mode = false;
run();
synchronize.wait(); // waiting for child thread to be ready
}
void fichier_libcurl::stop_thread()
{
if(is_running())
{
char *ptr = nullptr;
unsigned int ptr_size;
end_data_mode = true;
switch(get_mode())
{
case gf_write_only:
interthread.get_block_to_feed(ptr, ptr_size);
interthread.feed(ptr, 0); // trigger the thread if it was waiting for data from interthread
break;
case gf_read_only:
if(interthread.is_full())
{
interthread.fetch(ptr, ptr_size);
interthread.fetch_recycle(ptr); // trigger the thread if it was waiting for a free block to fill
}
break;
case gf_read_write:
throw SRC_BUG;
default:
throw SRC_BUG;
}
}
join();
ehandle->setopt_default(CURLOPT_RESUME_FROM_LARGE);
}
void fichier_libcurl::relaunch_thread(const infinint & block_size)
{
if(metadatamode)
{
if(x_proto == proto_ftp)
network_block = 0;
else
network_block = block_size;
switch_to_metadata(false);
}
else
{
if(sub_is_dying)
{
stop_thread();
if(x_proto == proto_ftp)
network_block = 0;
else
network_block = block_size;
run_thread();
}
// else thread is still running so
// we cannot change the network_block size
}
}
size_t fichier_libcurl::write_data_callback(char *buffer, size_t size, size_t nmemb, void *userp)
{
size_t remain = size * nmemb;
size_t lu = 0;
fichier_libcurl *me = (fichier_libcurl *)(userp);
char *ptr;
unsigned int ptr_size;
if(me == nullptr)
throw SRC_BUG;
while(!me->end_data_mode && remain > 0)
{
me->interthread.get_block_to_feed(ptr, ptr_size);
if(remain <= ptr_size)
{
memcpy(ptr, buffer + lu, remain);
me->interthread.feed(ptr, remain);
lu += remain;
remain = 0;
}
else
{
memcpy(ptr, buffer + lu, ptr_size);
me->interthread.feed(ptr, ptr_size);
remain -= ptr_size;
lu += ptr_size;
}
}
if(me->network_block > 0)
me->subthread_net_offset += lu;
if(me->end_data_mode)
{
if(me->network_block == 0)
{
if(remain > 0) // not all data could be sent to main thread
lu = 0; // to force easy_perform() that called us, to return
}
else
{
if(remain > 0)
throw SRC_BUG;
// main thread should not ask us to stop
// until we have provided all the requested data
}
}
return lu;
}
size_t fichier_libcurl::read_data_callback(char *bufptr, size_t size, size_t nitems, void *userp)
{
size_t ret;
size_t room = size * nitems;
fichier_libcurl *me = (fichier_libcurl *)(userp);
char *ptr;
unsigned int ptr_size;
if(me == nullptr)
throw SRC_BUG;
me->interthread.fetch(ptr, ptr_size);
if(ptr_size <= room)
{
memcpy(bufptr, ptr, ptr_size);
me->interthread.fetch_recycle(ptr);
ret = ptr_size;
}
else
{
memcpy(bufptr, ptr, room);
ptr_size -= room;
memmove(ptr, ptr + room, ptr_size);
me->interthread.fetch_push_back(ptr, ptr_size);
ret = room;
}
return ret;
}
size_t fichier_libcurl::write_meta_callback(char *buffer, size_t size, size_t nmemb, void *userp)
{
return size * nmemb;
}
size_t fichier_libcurl::read_meta_callback(char *bufptr, size_t size, size_t nitems, void *userp)
{
return 0;
}
void fichier_libcurl::set_subthread(U_I & needed_bytes)
{
if(interthread.is_empty())
{
// cannot switch to data mode if some data are
// in transit because current_offset would be
// wrongly positionned in the requested to libcurl
if(metadatamode)
{
if(x_proto == proto_ftp)
network_block = 0;
// because reading by block lead control session to
// be reset when ftp is used, leading a huge amount
// of connection an FTP server might see as DoS atempt
else
{
if(has_maxpos && maxpos <= current_offset + needed_bytes)
{
infinint tmp = maxpos - current_offset;
// this sets size the value of tmp:
needed_bytes = 0;
tmp.unstack(needed_bytes);
if(!tmp.is_zero())
throw SRC_BUG;
network_block = 0;
}
else
network_block = needed_bytes;
}
switch_to_metadata(false);
}
else
{
if(sub_is_dying)
relaunch_thread(needed_bytes);
}
}
}
bool fichier_libcurl::still_data_to_write()
{
if(get_mode() == gf_write_only)
{
if(interthread.is_empty())
return false;
else
{
char *ptr;
unsigned int size;
interthread.fetch(ptr, size);
if(size == 0)
{
interthread.fetch_recycle(ptr);
return false;
}
else
{
interthread.fetch_push_back(ptr, size);
return true;
}
}
}
else
return false;
}
#endif
} // end of namespace
| Edrusb/DAR | src/libdar/fichier_libcurl.cpp | C++ | gpl-2.0 | 20,103 |
package org.xiaotian.config;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.log4j.Logger;
import org.xiaotian.config.bean.ConfigFile;
import org.xiaotian.config.bean.ConfigFiles;
import org.xiaotian.extend.CMyFile;
/**
* 按照指定方式(配置文件plugin和mapping.xml在同一目录)读写文件的工具类 <BR>
*
* @author xiaotian15
*
*/
public class ConfigFilesFinder {
private static Logger m_logger = Logger.getLogger(ConfigFilesFinder.class);
/**
* 负有所有配置文件信息的ConfigFile集合
*/
private ConfigFiles m_oConfigFiles = null;
/**
* 配置文件存放的根文件夹位置,是查找的入口
*/
private ArrayList<String> m_pConfigFileRootPaths = new ArrayList<String>();
/**
* 要查找的配置文件的名称,如 config.xml
*/
private String m_sConfigXmlFile;
private HashMap<String, ConfigFile> m_mapAlreadyDoneWithFileNames = new HashMap<String, ConfigFile>();
public ConfigFilesFinder(String _sConfigFileRootPath, String _sConfigXmlFile) {
m_pConfigFileRootPaths.add(_sConfigFileRootPath);
this.m_sConfigXmlFile = _sConfigXmlFile;
}
public ConfigFilesFinder(ArrayList<String> _arConfigFileRootPaths,
String _sConfigXmlFile) {
this.m_pConfigFileRootPaths = _arConfigFileRootPaths;
this.m_sConfigXmlFile = _sConfigXmlFile;
}
/**
* 得到已经组织好的配置文件集合
*
* @return 包含config.xml - mapping.xml的CfgFiles对象
* @throws ConfigException
* 可能的文件读取错误
*/
public ConfigFiles getConfigFiles() throws ConfigException {
if (m_oConfigFiles == null) {
m_oConfigFiles = new ConfigFiles();
for (int i = 0; i < m_pConfigFileRootPaths.size(); i++) {
String sConfigFileRootPath = (String) m_pConfigFileRootPaths
.get(i);
if (m_logger.isDebugEnabled())
m_logger.debug("begin to load config files from["
+ sConfigFileRootPath + "]...");
File fRoot = new File(sConfigFileRootPath);
lookupCfgFiles(fRoot);
}
} else {
if (m_logger.isDebugEnabled())
m_logger.debug("the files have been loaded.");
}
return m_oConfigFiles;
}
/**
* 刷新
*/
public ConfigFiles refresh() throws ConfigException {
m_oConfigFiles = null;
return getConfigFiles();
}
/**
* 递归检索指定目录,将查找的文件加入到m_hshFiles中去
*
* @param _file
* 文件夹路径或者文件路径,后者是递归跳出的条件
*/
private void lookupCfgFiles(File _file) {
if (_file.isFile()) {
// 不是指定的文件名
if (!_file.getName().equals(this.m_sConfigXmlFile)) {
return;
}
// 在与Config.xml同级的目录中寻找配置对象的描述文件:mapping.xml
String sMapping = CMyFile.extractFilePath(_file.getPath())
+ ConfigConstants.NAME_FILE_MAPPING;
File fMapping = CMyFile.fileExists(sMapping) ? new File(sMapping)
: null;
// 分解配置文件
String sAbsolutFileName = _file.getAbsolutePath();
String sConfigFileNameExcludeProjectPath = extractConfigFileNameExcludeProjectPath(sAbsolutFileName);
// 判断是否处理,如果处理了,判断Mapping文件是否设置,没有直接返回
ConfigFile configFile = (ConfigFile) m_mapAlreadyDoneWithFileNames
.get(sConfigFileNameExcludeProjectPath);
if (configFile != null) {
if (configFile.getMapping() == null && fMapping != null) {
configFile.setMapping(fMapping);
}
return;
}
// 记录下已经处理的配置文件
configFile = new ConfigFile(_file, fMapping);
m_mapAlreadyDoneWithFileNames.put(
sConfigFileNameExcludeProjectPath, configFile);
if (m_logger.isDebugEnabled()) {
m_logger.debug("load xml file[" + _file.getPath() + "]");
}
m_oConfigFiles.add(configFile);
return;
}
// 递归调用,遍历所有子文件夹
File[] dirs = _file.listFiles();
if (dirs == null) {
m_logger.warn("May be a IOException,find an invalid dir:"
+ _file.getAbsolutePath());
return;
}
for (int i = 0; i < dirs.length; i++) {
lookupCfgFiles(dirs[i]);
}
}
/**
* 获取s_sAppRootPath后面的路径<BR>
*
* @param _sAbsolutFileName
* config文件的root路径
* @return
*/
private String extractConfigFileNameExcludeProjectPath(
String _sAbsolutFileName) {
String sConfigFilePathFlag = File.separatorChar
+ ConfigConstants.CONFIG_ROOT_PATH + File.separatorChar;
String sConfigFileNameExcludeProjectPath = _sAbsolutFileName;
int nPos = _sAbsolutFileName.indexOf(sConfigFilePathFlag);
if (nPos >= 0) {
sConfigFileNameExcludeProjectPath = _sAbsolutFileName
.substring(nPos);
}
return sConfigFileNameExcludeProjectPath;
}
} | xiaotian15/meister | meister-config-server/src/main/java/org/xiaotian/config/ConfigFilesFinder.java | Java | gpl-2.0 | 4,912 |
/*
pbrt source code Copyright(c) 1998-2012 Matt Pharr and Greg Humphreys.
This file is part of pbrt.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// materials/measured.cpp*
#include "stdafx.h"
#include "materials/measured.h"
#include "paramset.h"
#include "floatfile.h"
/*
File format descriptions:
-- Irregularly Sampled Isotropic BRDF --
This is the format of the BRDFs in the scenes/brdfs/ folder of the pbrt
distribution. This is a simple text format of numbers in a particular
format; the hash character # is used to denote a comment that continues
to the end of the current line.
The first number in the file gives the number of wavelengths at which the
reflection data was measured, numWls. This is followed by numWls values
that give the frequency in nm of these wavelengths. Each BRDF
measurement is represented by 4+numWls values. The first two give the
(theta,phi) angles of the incident illumination direction, the next two
give (theta,phi) for the measured reflection direction, and the following
numWls give the spectral coefficients for the measurement at the
wavelength specified at the start of the file.
-- Regular Half-Angle BRDF --
This is the file format used in the MERL BRDF database; see http://merl.com/brdf.
This file format is a binary format, with numbers encoded in low-endian
form. It represents a regular 3D tabularization of BRDF samples in RGB
color where the dimensions indexed over are (delta phi, delta theta,
sqrt(theta_h)). Here, theta_h is the angle between the halfangle vector
and the normal, and delta theta and delta phi are the offset in theta and
phi of one of the two directions. (Note that the offset would be the
same for the other direction, since it's from the half-angle vector.)
The starts with three 32-bit integers, giving the resolution of the
overall table. It then containes a number of samples equal to the
product of those three integers, times 3 (for RGB). Samples are laid out
with delta phi the minor index, then delta theta, then sqrt(theta_h) as
the major index.
In the file each sample should be scaled by RGB(1500,1500,1500/1.6) of
the original measurement. (In order words, the sample values are scaled
by the inverse of that as they are read in.
*/
// MeasuredMaterial Method Definitions
static map<string, float *> loadedRegularHalfangle;
static map<string, KdTree<IrregIsotropicBRDFSample> *> loadedThetaPhi;
MeasuredMaterial::MeasuredMaterial(const string &filename,
Reference<Texture<float> > bump) {
bumpMap = bump;
const char *suffix = strrchr(filename.c_str(), '.');
regularHalfangleData = NULL;
thetaPhiData = NULL;
if (!suffix)
Error("No suffix in measured BRDF filename \"%s\". "
"Can't determine file type (.brdf / .merl)", filename.c_str());
else if (!strcmp(suffix, ".brdf") || !strcmp(suffix, ".BRDF")) {
// Load $(\theta, \phi)$ measured BRDF data
if (loadedThetaPhi.find(filename) != loadedThetaPhi.end()) {
thetaPhiData = loadedThetaPhi[filename];
return;
}
vector<float> values;
if (!ReadFloatFile(filename.c_str(), &values)) {
Error("Unable to read BRDF data from file \"%s\"", filename.c_str());
return;
}
uint32_t pos = 0;
int numWls = int(values[pos++]);
if ((values.size() - 1 - numWls) % (4 + numWls) != 0) {
Error("Excess or insufficient data in theta, phi BRDF file \"%s\"",
filename.c_str());
return;
}
vector<float> wls;
for (int i = 0; i < numWls; ++i)
wls.push_back(values[pos++]);
BBox bbox;
vector<IrregIsotropicBRDFSample> samples;
while (pos < values.size()) {
float thetai = values[pos++];
float phii = values[pos++];
float thetao = values[pos++];
float phio = values[pos++];
Vector wo = SphericalDirection(sinf(thetao), cosf(thetao), phio);
Vector wi = SphericalDirection(sinf(thetai), cosf(thetai), phii);
Spectrum s = Spectrum::FromSampled(&wls[0], &values[pos], numWls);
pos += numWls;
Point p = BRDFRemap(wo, wi);
samples.push_back(IrregIsotropicBRDFSample(p, s));
bbox = Union(bbox, p);
}
loadedThetaPhi[filename] = thetaPhiData = new KdTree<IrregIsotropicBRDFSample>(samples);
}
else {
// Load RegularHalfangle BRDF Data
nThetaH = 90;
nThetaD = 90;
nPhiD = 180;
if (loadedRegularHalfangle.find(filename) != loadedRegularHalfangle.end()) {
regularHalfangleData = loadedRegularHalfangle[filename];
return;
}
FILE *f = fopen(filename.c_str(), "rb");
if (!f) {
Error("Unable to open BRDF data file \"%s\"", filename.c_str());
return;
}
int dims[3];
if (fread(dims, sizeof(int), 3, f) != 3) {
Error("Premature end-of-file in measured BRDF data file \"%s\"",
filename.c_str());
fclose(f);
return;
}
uint32_t n = dims[0] * dims[1] * dims[2];
if (n != nThetaH * nThetaD * nPhiD) {
Error("Dimensions don't match\n");
fclose(f);
return;
}
regularHalfangleData = new float[3*n];
const uint32_t chunkSize = 2*nPhiD;
double *tmp = ALLOCA(double, chunkSize);
uint32_t nChunks = n / chunkSize;
Assert((n % chunkSize) == 0);
float scales[3] = { 1.f/1500.f,
1.15f/1500.f,
1.66f/1500.f };
for (int c = 0; c < 3; ++c) {
int offset = 0;
for (uint32_t i = 0; i < nChunks; ++i) {
if (fread(tmp, sizeof(double), chunkSize, f) != chunkSize) {
Error("Premature end-of-file in measured BRDF data file \"%s\"",
filename.c_str());
delete[] regularHalfangleData;
regularHalfangleData = NULL;
fclose(f);
return;
}
for (uint32_t j = 0; j < chunkSize; ++j){
regularHalfangleData[3 * offset++ + c] = max(0., tmp[j] * scales[c]);
}
}
}
loadedRegularHalfangle[filename] = regularHalfangleData;
fclose(f);
}
}
BSDF *MeasuredMaterial::GetBSDF(const DifferentialGeometry &dgGeom,
const DifferentialGeometry &dgShading,
MemoryArena &arena) const {
// Allocate _BSDF_, possibly doing bump mapping with _bumpMap_
DifferentialGeometry dgs;
if (bumpMap)
Bump(bumpMap, dgGeom, dgShading, &dgs);
else
dgs = dgShading;
BSDF *bsdf = BSDF_ALLOC(arena, BSDF)(dgs, dgGeom.nn);
if (regularHalfangleData)
bsdf->Add(BSDF_ALLOC(arena, RegularHalfangleBRDF)
(regularHalfangleData, nThetaH, nThetaD, nPhiD));
else if (thetaPhiData)
bsdf->Add(BSDF_ALLOC(arena, IrregIsotropicBRDF)(thetaPhiData));
return bsdf;
}
MeasuredMaterial *CreateMeasuredMaterial(const Transform &xform,
const TextureParams &mp) {
Reference<Texture<float> > bumpMap = mp.GetFloatTextureOrNull("bumpmap");
return new MeasuredMaterial(mp.FindFilename("filename"), bumpMap);
}
| dnx4015/pbrt-importance-sampling | pbrt-v2-master/src/materials/measured.cpp | C++ | gpl-2.0 | 8,817 |
package com.shinydev.wrappers;
import au.com.bytecode.opencsv.CSVReader;
import com.shinydev.justcoin.model.JustcoinTransaction;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import static com.google.common.base.Preconditions.checkArgument;
public class JustcoinWrapper {
private static final Logger LOG = LoggerFactory.getLogger(JustcoinWrapper.class);
private final String justcoinCvsFileLocation;
private final DateTimeZone zone;
public JustcoinWrapper(String justcoinCvsFileLocation, DateTimeZone zone) {
this.justcoinCvsFileLocation = justcoinCvsFileLocation;
this.zone = zone;
}
public List<JustcoinTransaction> getJustcoinCreditTransactions(DateTime start, DateTime end) throws IOException {
checkArgument(start.getZone().equals(zone), "start date should be with the same zone as passed in constructor");
checkArgument(end.getZone().equals(zone), "end date should be with the same zone as passed in constructor");
CSVReader reader = new CSVReader(new FileReader(justcoinCvsFileLocation));
List<String[]> myEntries = new ArrayList<>();
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
if ("id".equals(nextLine[0])) {
LOG.debug("Parsed Justcoin CVS header");
} else {
myEntries.add(nextLine);
}
}
List<JustcoinTransaction> justcoinTransactions = myEntries.stream()
.map(entry -> new JustcoinTransaction(
entry[0],
entry[1],
Long.valueOf(entry[2]), //long
DateTime.parse(entry[3]).withZone(zone),
entry[4],
new BigDecimal(entry[5]) //big decimal
))
.collect(Collectors.toList());
return justcoinTransactions.stream()
.filter(tx -> tx.getDateTime().isAfter(start))
.filter(tx -> tx.getDateTime().isBefore(end))
.collect(Collectors.toList());
}
}
| nakedpony/justcoin-ripple-checker | src/main/java/com/shinydev/wrappers/JustcoinWrapper.java | Java | gpl-2.0 | 2,350 |
/*
Copyright (C) 2012-2016 Carl Hetherington <cth@carlh.net>
This file is part of DCP-o-matic.
DCP-o-matic is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
DCP-o-matic is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with DCP-o-matic. If not, see <http://www.gnu.org/licenses/>.
*/
#include "cinema_dialog.h"
#include "wx_util.h"
#include "lib/dcpomatic_assert.h"
#include "lib/util.h"
#include <boost/foreach.hpp>
using std::string;
using std::vector;
using std::copy;
using std::back_inserter;
using std::list;
using std::cout;
using boost::bind;
static string
column (string s)
{
return s;
}
CinemaDialog::CinemaDialog (wxWindow* parent, wxString title, string name, list<string> emails, string notes, int utc_offset_hour, int utc_offset_minute)
: wxDialog (parent, wxID_ANY, title)
{
wxBoxSizer* overall_sizer = new wxBoxSizer (wxVERTICAL);
SetSizer (overall_sizer);
wxGridBagSizer* sizer = new wxGridBagSizer (DCPOMATIC_SIZER_X_GAP, DCPOMATIC_SIZER_Y_GAP);
int r = 0;
add_label_to_sizer (sizer, this, _("Name"), true, wxGBPosition (r, 0));
_name = new wxTextCtrl (this, wxID_ANY, std_to_wx (name), wxDefaultPosition, wxSize (500, -1));
sizer->Add (_name, wxGBPosition (r, 1));
++r;
add_label_to_sizer (sizer, this, _("UTC offset (time zone)"), true, wxGBPosition (r, 0));
_utc_offset = new wxChoice (this, wxID_ANY);
sizer->Add (_utc_offset, wxGBPosition (r, 1));
++r;
add_label_to_sizer (sizer, this, _("Notes"), true, wxGBPosition (r, 0));
_notes = new wxTextCtrl (this, wxID_ANY, std_to_wx (notes), wxDefaultPosition, wxSize (500, -1));
sizer->Add (_notes, wxGBPosition (r, 1));
++r;
add_label_to_sizer (sizer, this, _("Email addresses for KDM delivery"), false, wxGBPosition (r, 0), wxGBSpan (1, 2));
++r;
copy (emails.begin(), emails.end(), back_inserter (_emails));
vector<string> columns;
columns.push_back (wx_to_std (_("Address")));
_email_list = new EditableList<string, EmailDialog> (
this, columns, bind (&CinemaDialog::get_emails, this), bind (&CinemaDialog::set_emails, this, _1), bind (&column, _1)
);
sizer->Add (_email_list, wxGBPosition (r, 0), wxGBSpan (1, 2), wxEXPAND);
++r;
overall_sizer->Add (sizer, 1, wxEXPAND | wxALL, DCPOMATIC_DIALOG_BORDER);
wxSizer* buttons = CreateSeparatedButtonSizer (wxOK | wxCANCEL);
if (buttons) {
overall_sizer->Add (buttons, wxSizerFlags().Expand().DoubleBorder());
}
_offsets.push_back (Offset (_("UTC-11"), -11, 0));
_offsets.push_back (Offset (_("UTC-10"), -10, 0));
_offsets.push_back (Offset (_("UTC-9"), -9, 0));
_offsets.push_back (Offset (_("UTC-8"), -8, 0));
_offsets.push_back (Offset (_("UTC-7"), -7, 0));
_offsets.push_back (Offset (_("UTC-6"), -6, 0));
_offsets.push_back (Offset (_("UTC-5"), -5, 0));
_offsets.push_back (Offset (_("UTC-4:30"), -4, 30));
_offsets.push_back (Offset (_("UTC-4"), -4, 0));
_offsets.push_back (Offset (_("UTC-3:30"), -3, 30));
_offsets.push_back (Offset (_("UTC-3"), -3, 0));
_offsets.push_back (Offset (_("UTC-2"), -2, 0));
_offsets.push_back (Offset (_("UTC-1"), -1, 0));
_offsets.push_back (Offset (_("UTC") , 0, 0));
_offsets.push_back (Offset (_("UTC+1"), 1, 0));
_offsets.push_back (Offset (_("UTC+2"), 2, 0));
_offsets.push_back (Offset (_("UTC+3"), 3, 0));
_offsets.push_back (Offset (_("UTC+4"), 4, 0));
_offsets.push_back (Offset (_("UTC+5"), 5, 0));
_offsets.push_back (Offset (_("UTC+5:30"), 5, 30));
_offsets.push_back (Offset (_("UTC+6"), 6, 0));
_offsets.push_back (Offset (_("UTC+7"), 7, 0));
_offsets.push_back (Offset (_("UTC+8"), 8, 0));
_offsets.push_back (Offset (_("UTC+9"), 9, 0));
_offsets.push_back (Offset (_("UTC+9:30"), 9, 30));
_offsets.push_back (Offset (_("UTC+10"), 10, 0));
_offsets.push_back (Offset (_("UTC+11"), 11, 0));
_offsets.push_back (Offset (_("UTC+12"), 12, 0));
/* Default to UTC */
size_t sel = 13;
for (size_t i = 0; i < _offsets.size(); ++i) {
_utc_offset->Append (_offsets[i].name);
if (_offsets[i].hour == utc_offset_hour && _offsets[i].minute == utc_offset_minute) {
sel = i;
}
}
_utc_offset->SetSelection (sel);
overall_sizer->Layout ();
overall_sizer->SetSizeHints (this);
}
string
CinemaDialog::name () const
{
return wx_to_std (_name->GetValue());
}
void
CinemaDialog::set_emails (vector<string> e)
{
_emails = e;
}
vector<string>
CinemaDialog::get_emails () const
{
return _emails;
}
list<string>
CinemaDialog::emails () const
{
list<string> e;
copy (_emails.begin(), _emails.end(), back_inserter (e));
return e;
}
int
CinemaDialog::utc_offset_hour () const
{
int const sel = _utc_offset->GetSelection();
if (sel < 0 || sel > int (_offsets.size())) {
return 0;
}
return _offsets[sel].hour;
}
int
CinemaDialog::utc_offset_minute () const
{
int const sel = _utc_offset->GetSelection();
if (sel < 0 || sel > int (_offsets.size())) {
return 0;
}
return _offsets[sel].minute;
}
string
CinemaDialog::notes () const
{
return wx_to_std (_notes->GetValue ());
}
| GrokImageCompression/dcpomatic | src/wx/cinema_dialog.cc | C++ | gpl-2.0 | 5,515 |
/*
* ObjectReference2.cpp
*
* Created on: Oct 16, 2015
* Author: kfulks
*/
#include "../../Concept/Reference/ObjectReference2.h"
#include <iostream>
namespace gitux {
using namespace std;
ObjectReference2::ObjectReference2() :
myRef() {
// TODO Auto-generated constructor stub
cout << "ObjectReference2 constructor" << endl;
}
ObjectReference2::~ObjectReference2() {
// TODO Auto-generated destructor stub
cout << "ObjectReference2 destructor" << endl;
}
void ObjectReference2::SetReference(int &testRef) {
myRef = &testRef;
}
void ObjectReference2::ChangeReference(int &testRef) {
testRef = 2;
}
void ObjectReference2::PrintReference() {
cout << "ObjectReference2 value is " << *myRef << endl;
}
} /* namespace gitux */
| gi-tux/CppExamples | src/Concept/Reference/ObjectReference2.cpp | C++ | gpl-2.0 | 751 |
from colab.plugins.utils.proxy_data_api import ProxyDataAPI
class JenkinsDataAPI(ProxyDataAPI):
def fetch_data(self):
pass
| rafamanzo/colab | colab/plugins/jenkins/data_api.py | Python | gpl-2.0 | 138 |
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
| krues8dr/govify | app/Models/User.php | PHP | gpl-2.0 | 741 |
/**********************************************************
* Common JS function calls. *
* Copyright © 2001-2007 E-Blah. *
* Part of the E-Blah Software. Released under the GPL. *
* Last Update: September 17, 2007 *
**********************************************************/
// AJAX: developer.apple.com/internet/webcontent/xmlhttpreq.html
var req;
function EditMessage(url,saveopen,savemessage,messageid) {
EditMessage2(url,saveopen,savemessage);
function EditMessage2(url,saveopen,savemessage,messageid) {
req = false;
if(window.XMLHttpRequest) { // Non IE browsers
try { req = new XMLHttpRequest(encoding="utf-8"); }
catch(e) { req = false; }
} else if(window.ActiveXObject) { // IE
try { req = new ActiveXObject("Msxml2.XMLHTTP"); }
catch(e) {
try { req = new ActiveXObject("Microsoft.XMLHTTP"); }
catch(e) { req = false; }
}
}
if(req) {
req.onreadystatechange = processReqChange;
req.open("POST", url, true); // Use POST so we don't get CACHED items!
if(saveopen == 1) { req.send("message="+encodeURIComponent(savemessage)); }
else if(saveopen == 2) {
req.send(savemessage);
} else { req.send('TEMP'); }
} else { alert('There was an error loading this page.'); }
}
function processReqChange() {
if(req.readyState != 4) { document.getElementById(messageid).innerHTML = '<div class="loading"> </div>'; }
if(req.readyState == 4) {
if (req.status == 200) {
document.getElementById(messageid).innerHTML = req.responseText;
} else { alert('There was an error loading this page.'); }
}
}
}
// Let's do some menus ...
// Some code based from: www.quirksmode.org/js/findpos.html
function findPosX(obj) {
var curleft = 0;
if(obj.offsetParent) {
while (obj.offsetParent) {
curleft += obj.offsetLeft
obj = obj.offsetParent;
}
}
else if(obj.x)
curleft += obj.x;
return curleft;
}
function findPosY(obj,plussize) {
var curtop = plussize;
if(navigator.userAgent.indexOf("Firefox") != -1) { curtop = (curtop/2); }
if(navigator.userAgent.indexOf("IE") != -1) { curtop = (curtop+12); }
if(obj.offsetParent) {
while (obj.offsetParent) {
curtop += obj.offsetTop
obj = obj.offsetParent;
}
}
else if(obj.y)
curtop += obj.y;
return curtop;
}
// Creating Menus ...
function CreateMenus(obj,plussize,JSinput) {
var newX = findPosX(obj);
var newY = findPosY(obj,plussize);
var x = document.getElementById('menu-eblah');
x.style.top = newY + 'px';
x.style.left = newX + 'px';
document.getElementById('menu-eblah').innerHTML = ConstructLinks(JSinput);
document.getElementById('menu-eblah').style.visibility = '';
}
function ClearMenu() {
document.getElementById('menu-eblah').innerHTML = '';
document.getElementById('menu-eblah').style.visibility = 'hidden';
}
function ConstructLinks(JSinput) {
GetLinks(JSinput);
var link = '';
for(x in MenuItems) {
link += '<div style="padding: 5px;" class="win3">' + MenuItems[x] + '</div>';
}
return(link);
}
// Image Resize; from Martin's Mod for E-Blah
function resizeImg() {
var _resizeWidth = 750;
var ResizeMsg = 'Click to view original size ...';
var _resizeClass = 'imgcode';
var imgArray = document.getElementsByTagName('img');
for(var i = 0; i < imgArray.length; i++) {
var imgObj = imgArray[i];
if(imgObj.className == _resizeClass && imgObj.width > _resizeWidth) {
imgObj.style.width = _resizeWidth + 'px';
imgObj.onclick = ImagecodeWinOpen;
imgObj.title = ResizeMsg;
imgObj.style.cursor = 'pointer';
}
}
}
function ImagecodeWinOpen(e) {
var img = (e)?e.target.src:window.event.srcElement.src;
var w = window.open('','IMG','titlebar,scrollbars,resizable');
if (w) {
w.document.write('<html><body><div align="center"><a href="#" onclick="window.close(); return false"><img src="'+img+'"></a></div></body></html>');
w.document.close();
}
}
window.onload = resizeImg; | eblah/E-Blah-Forum | public_html/blahdocs/common.js | JavaScript | gpl-2.0 | 4,101 |
#region Usings
using System.Diagnostics;
#endregion
namespace Unity.IO.Compression
{
internal static class Crc32Helper
{
// Table for CRC calculation
private static readonly uint[] crcTable = new uint[256]
{
0x00000000u, 0x77073096u, 0xee0e612cu, 0x990951bau, 0x076dc419u,
0x706af48fu, 0xe963a535u, 0x9e6495a3u, 0x0edb8832u, 0x79dcb8a4u,
0xe0d5e91eu, 0x97d2d988u, 0x09b64c2bu, 0x7eb17cbdu, 0xe7b82d07u,
0x90bf1d91u, 0x1db71064u, 0x6ab020f2u, 0xf3b97148u, 0x84be41deu,
0x1adad47du, 0x6ddde4ebu, 0xf4d4b551u, 0x83d385c7u, 0x136c9856u,
0x646ba8c0u, 0xfd62f97au, 0x8a65c9ecu, 0x14015c4fu, 0x63066cd9u,
0xfa0f3d63u, 0x8d080df5u, 0x3b6e20c8u, 0x4c69105eu, 0xd56041e4u,
0xa2677172u, 0x3c03e4d1u, 0x4b04d447u, 0xd20d85fdu, 0xa50ab56bu,
0x35b5a8fau, 0x42b2986cu, 0xdbbbc9d6u, 0xacbcf940u, 0x32d86ce3u,
0x45df5c75u, 0xdcd60dcfu, 0xabd13d59u, 0x26d930acu, 0x51de003au,
0xc8d75180u, 0xbfd06116u, 0x21b4f4b5u, 0x56b3c423u, 0xcfba9599u,
0xb8bda50fu, 0x2802b89eu, 0x5f058808u, 0xc60cd9b2u, 0xb10be924u,
0x2f6f7c87u, 0x58684c11u, 0xc1611dabu, 0xb6662d3du, 0x76dc4190u,
0x01db7106u, 0x98d220bcu, 0xefd5102au, 0x71b18589u, 0x06b6b51fu,
0x9fbfe4a5u, 0xe8b8d433u, 0x7807c9a2u, 0x0f00f934u, 0x9609a88eu,
0xe10e9818u, 0x7f6a0dbbu, 0x086d3d2du, 0x91646c97u, 0xe6635c01u,
0x6b6b51f4u, 0x1c6c6162u, 0x856530d8u, 0xf262004eu, 0x6c0695edu,
0x1b01a57bu, 0x8208f4c1u, 0xf50fc457u, 0x65b0d9c6u, 0x12b7e950u,
0x8bbeb8eau, 0xfcb9887cu, 0x62dd1ddfu, 0x15da2d49u, 0x8cd37cf3u,
0xfbd44c65u, 0x4db26158u, 0x3ab551ceu, 0xa3bc0074u, 0xd4bb30e2u,
0x4adfa541u, 0x3dd895d7u, 0xa4d1c46du, 0xd3d6f4fbu, 0x4369e96au,
0x346ed9fcu, 0xad678846u, 0xda60b8d0u, 0x44042d73u, 0x33031de5u,
0xaa0a4c5fu, 0xdd0d7cc9u, 0x5005713cu, 0x270241aau, 0xbe0b1010u,
0xc90c2086u, 0x5768b525u, 0x206f85b3u, 0xb966d409u, 0xce61e49fu,
0x5edef90eu, 0x29d9c998u, 0xb0d09822u, 0xc7d7a8b4u, 0x59b33d17u,
0x2eb40d81u, 0xb7bd5c3bu, 0xc0ba6cadu, 0xedb88320u, 0x9abfb3b6u,
0x03b6e20cu, 0x74b1d29au, 0xead54739u, 0x9dd277afu, 0x04db2615u,
0x73dc1683u, 0xe3630b12u, 0x94643b84u, 0x0d6d6a3eu, 0x7a6a5aa8u,
0xe40ecf0bu, 0x9309ff9du, 0x0a00ae27u, 0x7d079eb1u, 0xf00f9344u,
0x8708a3d2u, 0x1e01f268u, 0x6906c2feu, 0xf762575du, 0x806567cbu,
0x196c3671u, 0x6e6b06e7u, 0xfed41b76u, 0x89d32be0u, 0x10da7a5au,
0x67dd4accu, 0xf9b9df6fu, 0x8ebeeff9u, 0x17b7be43u, 0x60b08ed5u,
0xd6d6a3e8u, 0xa1d1937eu, 0x38d8c2c4u, 0x4fdff252u, 0xd1bb67f1u,
0xa6bc5767u, 0x3fb506ddu, 0x48b2364bu, 0xd80d2bdau, 0xaf0a1b4cu,
0x36034af6u, 0x41047a60u, 0xdf60efc3u, 0xa867df55u, 0x316e8eefu,
0x4669be79u, 0xcb61b38cu, 0xbc66831au, 0x256fd2a0u, 0x5268e236u,
0xcc0c7795u, 0xbb0b4703u, 0x220216b9u, 0x5505262fu, 0xc5ba3bbeu,
0xb2bd0b28u, 0x2bb45a92u, 0x5cb36a04u, 0xc2d7ffa7u, 0xb5d0cf31u,
0x2cd99e8bu, 0x5bdeae1du, 0x9b64c2b0u, 0xec63f226u, 0x756aa39cu,
0x026d930au, 0x9c0906a9u, 0xeb0e363fu, 0x72076785u, 0x05005713u,
0x95bf4a82u, 0xe2b87a14u, 0x7bb12baeu, 0x0cb61b38u, 0x92d28e9bu,
0xe5d5be0du, 0x7cdcefb7u, 0x0bdbdf21u, 0x86d3d2d4u, 0xf1d4e242u,
0x68ddb3f8u, 0x1fda836eu, 0x81be16cdu, 0xf6b9265bu, 0x6fb077e1u,
0x18b74777u, 0x88085ae6u, 0xff0f6a70u, 0x66063bcau, 0x11010b5cu,
0x8f659effu, 0xf862ae69u, 0x616bffd3u, 0x166ccf45u, 0xa00ae278u,
0xd70dd2eeu, 0x4e048354u, 0x3903b3c2u, 0xa7672661u, 0xd06016f7u,
0x4969474du, 0x3e6e77dbu, 0xaed16a4au, 0xd9d65adcu, 0x40df0b66u,
0x37d83bf0u, 0xa9bcae53u, 0xdebb9ec5u, 0x47b2cf7fu, 0x30b5ffe9u,
0xbdbdf21cu, 0xcabac28au, 0x53b39330u, 0x24b4a3a6u, 0xbad03605u,
0xcdd70693u, 0x54de5729u, 0x23d967bfu, 0xb3667a2eu, 0xc4614ab8u,
0x5d681b02u, 0x2a6f2b94u, 0xb40bbe37u, 0xc30c8ea1u, 0x5a05df1bu,
0x2d02ef8du
};
// Calculate CRC based on the old CRC and the new bytes
// See RFC1952 for details.
public static uint UpdateCrc32(uint crc32, byte[] buffer, int offset, int length)
{
Debug.Assert(buffer != null && offset >= 0 && length >= 0
&& offset <= buffer.Length - length, "check the caller");
crc32 ^= 0xffffffffU;
while (--length >= 0)
crc32 = crcTable[(crc32 ^ buffer[offset++]) & 0xFF] ^ (crc32 >> 8);
crc32 ^= 0xffffffffU;
return crc32;
}
}
} | supermax/TMS | TMS.Common/Assets/Runtime/Common/IO/Compression/Unity.IO.Compression/Crc32Helper.cs | C# | gpl-2.0 | 4,198 |
/*
* Copyright (c) 1998-2010 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Resin Open Source is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.env.thread;
import java.util.concurrent.locks.LockSupport;
import com.caucho.util.Alarm;
/**
* A generic pool of threads available for Alarms and Work tasks.
*/
final class ThreadTask {
private final Runnable _runnable;
private final ClassLoader _loader;
private volatile Thread _thread;
ThreadTask(Runnable runnable, ClassLoader loader, Thread thread)
{
_runnable = runnable;
_loader = loader;
_thread = thread;
}
final Runnable getRunnable()
{
return _runnable;
}
final ClassLoader getLoader()
{
return _loader;
}
void clearThread()
{
_thread = null;
}
final void wake()
{
Thread thread = _thread;
_thread = null;
if (thread != null)
LockSupport.unpark(thread);
}
final void park(long expires)
{
Thread thread = _thread;
while (_thread != null
&& Alarm.getCurrentTimeActual() < expires) {
try {
Thread.interrupted();
LockSupport.parkUntil(thread, expires);
} catch (Exception e) {
}
}
/*
if (_thread != null) {
System.out.println("TIMEOUT:" + thread);
Thread.dumpStack();
}
*/
_thread = null;
}
}
| CleverCloud/Quercus | resin/src/main/java/com/caucho/env/thread/ThreadTask.java | Java | gpl-2.0 | 2,251 |
"""Library for performing speech recognition with the Google Speech Recognition API."""
__author__ = 'Anthony Zhang (Uberi)'
__version__ = '1.0.4'
__license__ = 'BSD'
import io, subprocess, wave, shutil
import math, audioop, collections
import json, urllib.request
#wip: filter out clicks and other too short parts
class AudioSource(object):
def __init__(self):
raise NotImplementedError("this is an abstract class")
def __enter__(self):
raise NotImplementedError("this is an abstract class")
def __exit__(self, exc_type, exc_value, traceback):
raise NotImplementedError("this is an abstract class")
try:
import pyaudio
class Microphone(AudioSource):
def __init__(self, device_index = None):
self.device_index = device_index
self.format = pyaudio.paInt16 # 16-bit int sampling
self.SAMPLE_WIDTH = pyaudio.get_sample_size(self.format)
self.RATE = 16000 # sampling rate in Hertz
self.CHANNELS = 1 # mono audio
self.CHUNK = 1024 # number of frames stored in each buffer
self.audio = None
self.stream = None
def __enter__(self):
self.audio = pyaudio.PyAudio()
self.stream = self.audio.open(
input_device_index = self.device_index,
format = self.format, rate = self.RATE, channels = self.CHANNELS, frames_per_buffer = self.CHUNK,
input = True, # stream is an input stream
)
return self
def __exit__(self, exc_type, exc_value, traceback):
self.stream.stop_stream()
self.stream.close()
self.stream = None
self.audio.terminate()
except ImportError:
pass
class WavFile(AudioSource):
def __init__(self, filename_or_fileobject):
if isinstance(filename_or_fileobject, str):
self.filename = filename_or_fileobject
else:
self.filename = None
self.wav_file = filename_or_fileobject
self.stream = None
def __enter__(self):
if self.filename: self.wav_file = open(self.filename, "rb")
self.wav_reader = wave.open(self.wav_file, "rb")
self.SAMPLE_WIDTH = self.wav_reader.getsampwidth()
self.RATE = self.wav_reader.getframerate()
self.CHANNELS = self.wav_reader.getnchannels()
assert self.CHANNELS == 1 # audio must be mono
self.CHUNK = 4096
self.stream = WavFile.WavStream(self.wav_reader)
return self
def __exit__(self, exc_type, exc_value, traceback):
if self.filename: self.wav_file.close()
self.stream = None
class WavStream(object):
def __init__(self, wav_reader):
self.wav_reader = wav_reader
def read(self, size = -1):
if size == -1:
return self.wav_reader.readframes(self.wav_reader.getnframes())
return self.wav_reader.readframes(size)
class AudioData(object):
def __init__(self, rate, data):
self.rate = rate
self.data = data
class Recognizer(AudioSource):
def __init__(self, language = "fr-FR", key = "AIzaSyBOti4mM-6x9WDnZIjIeyEU21OpBXqWBgw"):
self.key = key
self.language = language
self.energy_threshold = 1500 # minimum audio energy to consider for recording
self.pause_threshold = 0.8 # seconds of quiet time before a phrase is considered complete
self.quiet_duration = 0.5 # amount of quiet time to keep on both sides of the recording
def samples_to_flac(self, source, frame_data):
import platform, os
with io.BytesIO() as wav_file:
with wave.open(wav_file, "wb") as wav_writer:
wav_writer.setsampwidth(source.SAMPLE_WIDTH)
wav_writer.setnchannels(source.CHANNELS)
wav_writer.setframerate(source.RATE)
wav_writer.writeframes(frame_data)
wav_data = wav_file.getvalue()
# determine which converter executable to use
system = platform.system()
path = os.path.dirname(os.path.abspath(__file__)) # directory of the current module file, where all the FLAC bundled binaries are stored
if shutil.which("flac") is not None: # check for installed version first
flac_converter = shutil.which("flac")
elif system == "Windows" and platform.machine() in {"i386", "x86", "x86_64", "AMD64"}: # Windows NT, use the bundled FLAC conversion utility
flac_converter = os.path.join(path, "flac-win32.exe")
elif system == "Linux" and platform.machine() in {"i386", "x86", "x86_64", "AMD64"}:
flac_converter = os.path.join(path, "flac-linux-i386")
else:
raise ChildProcessError("FLAC conversion utility not available - consider installing the FLAC utility")
process = subprocess.Popen("\"%s\" --stdout --totally-silent --best -" % flac_converter, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
flac_data, stderr = process.communicate(wav_data)
return flac_data
def record(self, source, duration = None):
assert isinstance(source, AudioSource) and source.stream
frames = io.BytesIO()
seconds_per_buffer = source.CHUNK / source.RATE
elapsed_time = 0
while True: # loop for the total number of chunks needed
elapsed_time += seconds_per_buffer
if duration and elapsed_time > duration: break
buffer = source.stream.read(source.CHUNK)
if len(buffer) == 0: break
frames.write(buffer)
frame_data = frames.getvalue()
frames.close()
return AudioData(source.RATE, self.samples_to_flac(source, frame_data))
def listen(self, source, timeout = None):
assert isinstance(source, AudioSource) and source.stream
# record audio data as raw samples
frames = collections.deque()
assert self.pause_threshold >= self.quiet_duration >= 0
seconds_per_buffer = source.CHUNK / source.RATE
pause_buffer_count = math.ceil(self.pause_threshold / seconds_per_buffer) # number of buffers of quiet audio before the phrase is complete
quiet_buffer_count = math.ceil(self.quiet_duration / seconds_per_buffer) # maximum number of buffers of quiet audio to retain before and after
elapsed_time = 0
# store audio input until the phrase starts
while True:
# handle timeout if specified
elapsed_time += seconds_per_buffer
if timeout and elapsed_time > timeout:
raise TimeoutError("listening timed out")
buffer = source.stream.read(source.CHUNK)
if len(buffer) == 0: break # reached end of the stream
frames.append(buffer)
# check if the audio input has stopped being quiet
energy = audioop.rms(buffer, source.SAMPLE_WIDTH) # energy of the audio signal
if energy > self.energy_threshold:
break
if len(frames) > quiet_buffer_count: # ensure we only keep the needed amount of quiet buffers
frames.popleft()
# read audio input until the phrase ends
pause_count = 0
while True:
buffer = source.stream.read(source.CHUNK)
if len(buffer) == 0: break # reached end of the stream
frames.append(buffer)
# check if the audio input has gone quiet for longer than the pause threshold
energy = audioop.rms(buffer, source.SAMPLE_WIDTH) # energy of the audio signal
if energy > self.energy_threshold:
pause_count = 0
else:
pause_count += 1
if pause_count > pause_buffer_count: # end of the phrase
break
# obtain frame data
for i in range(quiet_buffer_count, pause_buffer_count): frames.pop() # remove extra quiet frames at the end
frame_data = b"".join(list(frames))
return AudioData(source.RATE, self.samples_to_flac(source, frame_data))
def recognize(self, audio_data, show_all = False):
assert isinstance(audio_data, AudioData)
url = "http://www.google.com/speech-api/v2/recognize?client=chromium&lang=%s&key=%s" % (self.language, self.key)
self.request = urllib.request.Request(url, data = audio_data.data, headers = {"Content-Type": "audio/x-flac; rate=%s" % audio_data.rate})
# check for invalid key response from the server
try:
response = urllib.request.urlopen(self.request)
except:
raise KeyError("Server wouldn't respond (invalid key or quota has been maxed out)")
response_text = response.read().decode("utf-8")
# ignore any blank blocks
actual_result = []
for line in response_text.split("\n"):
if not line: continue
result = json.loads(line)["result"]
if len(result) != 0:
actual_result = result[0]
# make sure we have a list of transcriptions
if "alternative" not in actual_result:
raise LookupError("Speech is unintelligible")
# return the best guess unless told to do otherwise
if not show_all:
for prediction in actual_result["alternative"]:
if "confidence" in prediction:
return prediction["transcript"]
raise LookupError("Speech is unintelligible")
spoken_text = []
# check to see if Google thinks it's 100% correct
default_confidence = 0
if len(actual_result["alternative"])==1: default_confidence = 1
# return all the possibilities
for prediction in actual_result["alternative"]:
if "confidence" in prediction:
spoken_text.append({"text":prediction["transcript"],"confidence":prediction["confidence"]})
else:
spoken_text.append({"text":prediction["transcript"],"confidence":default_confidence})
return spoken_text
if __name__ == "__main__":
r = Recognizer()
m = Microphone()
while True:
print("Say something!")
with m as source:
audio = r.listen(source)
print("Got it! Now to recognize it...")
try:
print("You said " + r.recognize(audio))
except LookupError:
print("Oops! Didn't catch that")
| bizalu/sImulAcre | core/lib/speech_recognition/__init__.py | Python | gpl-2.0 | 10,485 |
/*
* aTunes
* Copyright (C) Alex Aranda, Sylvain Gaudard and contributors
*
* See http://www.atunes.org/wiki/index.php?title=Contributing for information about contributors
*
* http://www.atunes.org
* http://sourceforge.net/projects/atunes
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package net.sourceforge.atunes.gui.views.menus;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import net.sourceforge.atunes.model.IMenuBar;
/**
* The application menu bar.
*/
/**
* @author alex
*
*/
public final class ApplicationMenuBar extends JMenuBar implements IMenuBar {
private static final long serialVersionUID = 234977404080329591L;
private JMenu fileMenu;
private JMenu editMenu;
private JMenu viewMenu;
private JMenu playerMenu;
private PlayListMenu playListMenu;
private JMenu toolsMenu;
private JMenu deviceMenu;
private JMenu helpMenu;
/**
* @param playerMenu
*/
public void setPlayerMenu(JMenu playerMenu) {
this.playerMenu = playerMenu;
}
/**
* @param fileMenu
*/
public void setFileMenu(JMenu fileMenu) {
this.fileMenu = fileMenu;
}
/**
* @param editMenu
*/
public void setEditMenu(JMenu editMenu) {
this.editMenu = editMenu;
}
/**
* @param viewMenu
*/
public void setViewMenu(JMenu viewMenu) {
this.viewMenu = viewMenu;
}
/**
* @param toolsMenu
*/
public void setToolsMenu(JMenu toolsMenu) {
this.toolsMenu = toolsMenu;
}
/**
* @param deviceMenu
*/
public void setDeviceMenu(JMenu deviceMenu) {
this.deviceMenu = deviceMenu;
}
/* (non-Javadoc)
* @see javax.swing.JMenuBar#setHelpMenu(javax.swing.JMenu)
*/
public void setHelpMenu(JMenu helpMenu) {
this.helpMenu = helpMenu;
}
/**
* @param playListMenu
*/
public void setPlayListMenu(PlayListMenu playListMenu) {
this.playListMenu = playListMenu;
}
/**
* Adds the menus.
*/
@Override
public void initialize() {
add(fileMenu);
add(editMenu);
add(viewMenu);
add(playerMenu);
playListMenu.initialize();
add(playListMenu);
add(deviceMenu);
add(toolsMenu);
add(helpMenu);
}
/* (non-Javadoc)
* @see net.sourceforge.atunes.gui.views.menus.IMenuBar#addMenu(javax.swing.JMenu)
*/
@Override
public void addMenu(JMenu newMenu) {
remove(getComponentCount() - 1);
add(newMenu);
add(helpMenu);
}
@Override
public JMenuBar getSwingComponent() {
return this;
}
}
| PDavid/aTunes | aTunes/src/main/java/net/sourceforge/atunes/gui/views/menus/ApplicationMenuBar.java | Java | gpl-2.0 | 3,100 |
/*
* This program is free software; you can redistribute it and modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the license or (at your
* option) any later version.
*
* Authors: Olivier Lapicque <olivierl@jps.net>
*/
//////////////////////////////////////////////
// DSIK Internal Format (DSM) module loader //
//////////////////////////////////////////////
#include "stdafx.h"
#include "sndfile.h"
#pragma pack(1)
#define DSMID_RIFF 0x46464952 // "RIFF"
#define DSMID_DSMF 0x464d5344 // "DSMF"
#define DSMID_SONG 0x474e4f53 // "SONG"
#define DSMID_INST 0x54534e49 // "INST"
#define DSMID_PATT 0x54544150 // "PATT"
typedef struct DSMNOTE
{
BYTE note,ins,vol,cmd,inf;
} Q_PACKED DSMNOTE;
typedef struct DSMINST
{
DWORD id_INST;
DWORD inst_len;
CHAR filename[13];
BYTE flags;
BYTE flags2;
BYTE volume;
DWORD length;
DWORD loopstart;
DWORD loopend;
DWORD reserved1;
WORD c2spd;
WORD reserved2;
CHAR samplename[28];
} Q_PACKED DSMINST;
typedef struct DSMFILEHEADER
{
DWORD id_RIFF; // "RIFF"
DWORD riff_len;
DWORD id_DSMF; // "DSMF"
DWORD id_SONG; // "SONG"
DWORD song_len;
} Q_PACKED DSMFILEHEADER;
typedef struct DSMSONG
{
CHAR songname[28];
WORD reserved1;
WORD flags;
DWORD reserved2;
WORD numord;
WORD numsmp;
WORD numpat;
WORD numtrk;
BYTE globalvol;
BYTE mastervol;
BYTE speed;
BYTE bpm;
BYTE panpos[16];
BYTE orders[128];
} Q_PACKED DSMSONG;
typedef struct DSMPATT
{
DWORD id_PATT;
DWORD patt_len;
BYTE dummy1;
BYTE dummy2;
} Q_PACKED DSMPATT;
#pragma pack()
BOOL CSoundFile::ReadDSM(LPCBYTE lpStream, DWORD dwMemLength)
//-----------------------------------------------------------
{
DSMFILEHEADER *pfh = (DSMFILEHEADER *)lpStream;
DSMSONG *psong;
DWORD dwMemPos;
UINT nPat, nSmp;
if ((!lpStream) || (dwMemLength < 1024) || (pfh->id_RIFF != DSMID_RIFF)
|| (pfh->riff_len + 8 > dwMemLength) || (pfh->riff_len < 1024)
|| (pfh->id_DSMF != DSMID_DSMF) || (pfh->id_SONG != DSMID_SONG)
|| (pfh->song_len > dwMemLength)) return FALSE;
psong = (DSMSONG *)(lpStream + sizeof(DSMFILEHEADER));
dwMemPos = sizeof(DSMFILEHEADER) + pfh->song_len;
m_nType = MOD_TYPE_DSM;
m_nChannels = psong->numtrk;
if (m_nChannels < 4) m_nChannels = 4;
if (m_nChannels > 16) m_nChannels = 16;
m_nSamples = psong->numsmp;
if (m_nSamples > MAX_SAMPLES) m_nSamples = MAX_SAMPLES;
m_nDefaultSpeed = psong->speed;
m_nDefaultTempo = psong->bpm;
m_nDefaultGlobalVolume = psong->globalvol << 2;
if ((!m_nDefaultGlobalVolume) || (m_nDefaultGlobalVolume > 256)) m_nDefaultGlobalVolume = 256;
m_nSongPreAmp = psong->mastervol & 0x7F;
for (UINT iOrd=0; iOrd<MAX_ORDERS; iOrd++)
{
Order[iOrd] = (BYTE)((iOrd < psong->numord) ? psong->orders[iOrd] : 0xFF);
}
for (UINT iPan=0; iPan<16; iPan++)
{
ChnSettings[iPan].nPan = 0x80;
if (psong->panpos[iPan] <= 0x80)
{
ChnSettings[iPan].nPan = psong->panpos[iPan] << 1;
}
}
memcpy(m_szNames[0], psong->songname, 28);
nPat = 0;
nSmp = 1;
while (dwMemPos < dwMemLength - 8)
{
DSMPATT *ppatt = (DSMPATT *)(lpStream + dwMemPos);
DSMINST *pins = (DSMINST *)(lpStream+dwMemPos);
// Reading Patterns
if (ppatt->id_PATT == DSMID_PATT)
{
dwMemPos += 8;
if (dwMemPos + ppatt->patt_len >= dwMemLength) break;
DWORD dwPos = dwMemPos;
dwMemPos += ppatt->patt_len;
MODCOMMAND *m = AllocatePattern(64, m_nChannels);
if (!m) break;
PatternSize[nPat] = 64;
Patterns[nPat] = m;
UINT row = 0;
while ((row < 64) && (dwPos + 2 <= dwMemPos))
{
UINT flag = lpStream[dwPos++];
if (flag)
{
UINT ch = (flag & 0x0F) % m_nChannels;
if (flag & 0x80)
{
UINT note = lpStream[dwPos++];
if (note)
{
if (note <= 12*9) note += 12;
m[ch].note = (BYTE)note;
}
}
if (flag & 0x40)
{
m[ch].instr = lpStream[dwPos++];
}
if (flag & 0x20)
{
m[ch].volcmd = VOLCMD_VOLUME;
m[ch].vol = lpStream[dwPos++];
}
if (flag & 0x10)
{
UINT command = lpStream[dwPos++];
UINT param = lpStream[dwPos++];
switch(command)
{
// 4-bit Panning
case 0x08:
switch(param & 0xF0)
{
case 0x00: param <<= 4; break;
case 0x10: command = 0x0A; param = (param & 0x0F) << 4; break;
case 0x20: command = 0x0E; param = (param & 0x0F) | 0xA0; break;
case 0x30: command = 0x0E; param = (param & 0x0F) | 0x10; break;
case 0x40: command = 0x0E; param = (param & 0x0F) | 0x20; break;
default: command = 0;
}
break;
// Portamentos
case 0x11:
case 0x12:
command &= 0x0F;
break;
// 3D Sound (?)
case 0x13:
command = 'X' - 55;
param = 0x91;
break;
default:
// Volume + Offset (?)
command = ((command & 0xF0) == 0x20) ? 0x09 : 0;
}
m[ch].command = (BYTE)command;
m[ch].param = (BYTE)param;
if (command) ConvertModCommand(&m[ch]);
}
} else
{
m += m_nChannels;
row++;
}
}
nPat++;
} else
// Reading Samples
if ((nSmp <= m_nSamples) && (pins->id_INST == DSMID_INST))
{
if (dwMemPos + pins->inst_len >= dwMemLength - 8) break;
DWORD dwPos = dwMemPos + sizeof(DSMINST);
dwMemPos += 8 + pins->inst_len;
memcpy(m_szNames[nSmp], pins->samplename, 28);
MODINSTRUMENT *psmp = &Ins[nSmp];
memcpy(psmp->name, pins->filename, 13);
psmp->nGlobalVol = 64;
psmp->nC4Speed = pins->c2spd;
psmp->uFlags = (WORD)((pins->flags & 1) ? CHN_LOOP : 0);
psmp->nLength = pins->length;
psmp->nLoopStart = pins->loopstart;
psmp->nLoopEnd = pins->loopend;
psmp->nVolume = (WORD)(pins->volume << 2);
if (psmp->nVolume > 256) psmp->nVolume = 256;
UINT smptype = (pins->flags & 2) ? RS_PCM8S : RS_PCM8U;
ReadSample(psmp, smptype, (LPCSTR)(lpStream+dwPos), dwMemLength - dwPos);
nSmp++;
} else
{
break;
}
}
return TRUE;
}
| opieproject/opie | core/multimedia/opieplayer/modplug/load_dsm.cpp | C++ | gpl-2.0 | 5,990 |
<?php
$middleColumn .= "<h1><em><center>" . $this->objLanguage->code2Txt("mod_context_error_notincourse", "context",array('context'=>'Course')) . "</center></em></h1>";
$middleColumn .= "<br />";
echo $middleColumn;
?> | chisimba/modules | cmsadmin/templates/content/cms_notincontext_view_tpl.php | PHP | gpl-2.0 | 223 |
<?php
/*
* Plugin Name: Whimsy+ | Helper Class
* Version: 0.0.1
* Plugin URI: http://www.whimsycreative.co/framework/plus
* Description: A plugin packed with awesome features for Whimsy Framework.
* Author: Whimsy Creative Co.
* Author URI: http://www.whimsycreative.co
* Requires at least: 4.0
* Tested up to: 4.8
*
* Text Domain: whimsy-plus
* Domain Path: /language/
*
* @package WordPress
* @author Natasha Cozad
* @since 1.0.0
*/
if ( !class_exists( 'WhimsyPlusHelper' ) ) {
/**
* @since 1.0.0
* @access public
*/
class WhimsyPlusHelper {
/**
* @since 1.0.0
* @access public
* @return void
*/
function __construct() {
global $WhimsyPlusHelper;
/* Set up an empty class for the global $WhimsyPlusHelper object. */
$WhimsyPlusHelper = new stdClass;
/* Load the core functions/classes required by the rest of the framework. */
add_action( 'init', array( $this, 'includes' ), 1 );
/* Define fields for the Customizer. */
add_action( 'init', array( $this, 'fields' ), 50 );
/* Load the settings and controls for the Customizer. */
add_action( 'customize_register', array( $this, 'customize' ), 40 );
/* Load the core functions/classes required by the rest of the framework. */
add_action( 'after_setup_theme', array( $this, 'unhook' ), 400 );
/* Enqueue necessary scripts and CSS files for the skins . */
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue' ), 200 );
}
/**
* @since 1.0.0
* @access public
* @return void
*/
function fields() {
if( class_exists( 'Kirki' ) ) {
/* Layout */
Kirki::add_field( 'whimsy_plus', array(
'type' => 'slider',
'settings' => 'layout_size',
'label' => __( 'Site Width', 'whimsy-plus' ),
'description' => __( 'Set the width of the whole body of the site in %.', 'whimsy-plus' ),
'section' => 'whimsy_plus_layout',
'default' => '100',
'priority' => 1,
'output' => array(
array(
'element' => '#page',
'units' => '%',
'property' => 'width',
),
),
'transport' => 'auto',
'js_vars' => array(
array(
'element' => '#page',
'property' => 'width',
'units' => '%',
'function' => 'css',
),
),
) );
Kirki::add_field( 'whimsy_plus', array(
'type' => 'radio-image',
'settings' => 'whimsy_framework_layout',
'label' => __( 'Global Layout', 'whimsy-plus' ),
'section' => 'whimsy_plus_layout',
'default' => 'content-sidebar',
'priority' => 10,
'choices' => array(
'sidebar-content' => get_template_directory_uri() . '/library/img/sidebar-content.png',
'full-width' => get_template_directory_uri() . '/library/img/full-width.png',
'content-sidebar' => get_template_directory_uri() . '/library/img/content-sidebar.png',
),
) );
Kirki::add_field( 'whimsy_plus', array(
'type' => 'toggle',
'settings' => 'box_layout',
'label' => __( 'Enable Box-Style layout?', 'whimsy-plus' ),
'section' => 'whimsy_plus_layout',
'default' => false,
'priority' => 10,
) );
Kirki::add_field( 'whimsy_plus', array(
'type' => 'background',
'settings' => 'boxed_website_background',
'label' => __( 'Boxed Layout Content Background', 'kirki' ),
'description' => __( 'Content area background for boxed layout.', 'kirki' ),
'section' => 'whimsy_plus_layout',
'default' => array(
'background-color' => '#ffffff',
'background-image' => '',
'background-repeat' => 'no-repeat',
'background-size' => 'cover',
'background-attach' => 'fixed',
'background-position' => 'left-top',
'background-opacity' => 90,
),
'priority' => 10,
'active_callback' => array(
array(
'setting' => 'box_layout',
'operator' => '==',
'value' => true
),
),
'output' => array(
array(
'element' => '#page',
),
),
) );
// Kirki::add_field( 'whimsy_plus', array(
// 'type' => 'color',
// 'settings' => 'color_box_bg',
// 'label' => __( 'Box Background Color', 'whimsy-plus' ),
// 'section' => 'whimsy_plus_layout',
// 'default' => '#ffffff',
// 'priority' => 11,
// 'choices' => array(
// 'alpha' => true,
// ),
// 'active_callback' => array(
// array(
// 'setting' => 'box_layout',
// 'operator' => '==',
// 'value' => true
// ),
// ),
// 'output' => array(
// array(
// 'element' => '#page',
// 'property' => 'background-color',
// ),
// ),
// 'transport' => 'postMessage',
// 'js_vars' => array(
// array(
// 'element' => '#page',
// 'function' => 'css',
// 'property' => 'background-color',
// ),
// ),
// ) );
Kirki::add_field( 'whimsy_plus', array(
'type' => 'dimension',
'settings' => 'box_layout_margin',
'label' => __( 'Margin', 'whimsy-plus' ),
'description' => __( 'This controls how much blank space is between the sides of the browser window and your content.', 'whimsy-plus' ),
'section' => 'whimsy_plus_layout',
'default' => '0 auto',
'priority' => 13,
'active_callback' => array(
array(
'setting' => 'box_layout',
'operator' => '==',
'value' => true
),
),
'output' => array(
array(
'element' => '#page',
'property' => 'margin',
),
),
'transport' => 'postMessage',
'js_vars' => array(
array(
'element' => '#page',
'property' => 'margin',
'function' => 'css',
),
),
) );
Kirki::add_field( 'whimsy_plus', array(
'type' => 'dimension',
'settings' => 'box_layout_border_radius',
'label' => __( 'Border Radius', 'whimsy-plus' ),
'description' => __( 'This will curve the corners of the box layout.', 'whimsy-plus' ),
'section' => 'whimsy_plus_layout',
'default' => '0',
'priority' => 14,
'active_callback' => array(
array(
'setting' => 'box_layout',
'operator' => '==',
'value' => true
),
),
'output' => array(
array(
'element' => '#page',
'property' => 'border-radius',
),
),
'transport' => 'postMessage',
'js_vars' => array(
array(
'element' => '#page',
'property' => 'border-radius',
'function' => 'css',
),
)
) );
}
}
/**
* Include additional styles when in admin.
*/
function enqueue() {
// $whimsy_framework_layout = get_theme_mod( 'whimsy_framework_layout' );
// if ( $whimsy_framework_layout == 'sidebar-content' ) {
// wp_enqueue_style( 'whimsy-layout-sidebar-content', WHIMSY_CSS . 'layouts/sidebar-content.css' );
// }
// if ( $whimsy_framework_layout == 'full-width' ) {
// wp_enqueue_style( 'whimsy-layout-full-width', WHIMSY_CSS . 'layouts/full-width.css' );
// }
}
/**
* @since 1.0.0
* @access public
* @return void
*/
function includes() {
//require_once WHIMSY_PLUS_CUSTOMIZE . 'kirki/kirki.php';
// Include admin functions
//if ( is_admin() ) { include_once WHIMSY_PLUS_ADMIN . 'class-whimsy-plus-.php'; }
}
/**
* Updates to Whimsy Framework functions.
*/
function unhook() {
//remove_action( 'customize_preview_init', 'whimsy_customize_preview_js', 10 );
}
/**
* Updates to the Whimsy Framework Customizer.
*/
function customize ( $wp_customize ) {
// Clear out the original Whimsy Framework section to make way for new stuff.
//$wp_customize->remove_section( 'colors' );
}
}
}
$WhimsyPlusHelper = new WhimsyPlusHelper(); | WhimsyCreative/whimsy-plus | helpers/class-whimsy-plus-helper.php | PHP | gpl-2.0 | 8,486 |